<?php
defined('_WPBOOKINGPRO_EXEC') or die;
use WooBooking\CMS\Filesystem\File;
use WooBooking\CMS\Utilities\Utility;
if(!class_exists("WpBookingPro_PackageController")) {
    /**
     * Class WpBookingPro_PackageController
     */
    class WpBookingPro_PackageController extends woobooking_controller
    {
        /**
         * @var string
         */
        public $view = "package";

        /**
         * @return mixed
         * @throws Exception
         */
        public function ajax_add_new_package()
        {
            //TODO check permission add new
            return self::view("package.form");
        }

        /**
         * @param null $data_post
         * @return array|bool|mixed
         * @throws Exception
         */
        public function ajax_save($data_post = null)
        {
            $input = Factory::getInput();
            if (!$data_post) {
                $data_post = $input->getData()['data'];
            }
            $rates = $data_post['rates'];
            $custom_address = $data_post['custom_address'];
            if ($data_post['location_id'] == "" && $custom_address != "") {
                $modelLocation = WooBookingModel::getInstance('location');
                $location = [
                    'address' => $custom_address,
                    'published' => 1
                ];
                $dataLocation = $modelLocation->save($location);
                $data_post['location_id'] = $dataLocation['id'];
            }
            $db = Factory::getDBO();
            $query = $db->getQuery(true);
            $tags = $data_post['tags'];
            $data_post['published'] = $data_post['published'] == 1 ? $data_post['published'] : 0;
            $package = parent::save($data_post); // TODO: Change the autogenerated stub
            $modelRate = WoobookingModel::getInstance('rate');
            $query->clear()
                ->delete(WoobookingTable::getWBTable('rate'))
                ->where('object_id=' . $package->id)
                ->where('type=' . $query->quote(WpBookingPro_RateHelperAdmin::getNamePackage()));
            $db->setQuery($query)->execute();
            if (count((array)$rates)) {
                foreach ($rates as $rate) {
                    list($from, $to) = explode(";", $rate);
                    $item_rate = [
                        "from" => Factory::getDate($from)->toSql(),
                        "to" => Factory::getDate($to)->toSql(),
                        "type" => WpBookingPro_RateHelperAdmin::getNamePackage(),
                        "package_id" => $package->id
                    ];
                    $package->item_rate = $modelRate->save($item_rate);
                }
            }
            $list_tag_id = [];
            if (count((array)$tags)) {
                $query->clear()
                    ->delete(WoobookingTable::getWBTable('package_tag'))
                    ->where('package_id=' . $package->id);
                $db->setQuery($query)->execute();
                $modelTag = WoobookingModel::getInstance('tag');
                foreach ($tags as $tag) {
                    $item = $modelTag->getTagByName($tag);
                    if (!$item) {
                        $data_tag = [
                            "name" => $tag
                        ];
                        $item = $modelTag->save($data_tag);
                    }
                    $list_tag_id[] = $item->id;
                }
            }
            if ($package && count((array)$list_tag_id)) {
                $query->clear()
                    ->delete(WoobookingTable::getWBTable('package_tag'))
                    ->where('package_id=' . $package->id);
                $db->setQuery($query)->execute();
                foreach ($list_tag_id as $rate_id) {
                    $query->clear()
                        ->insert(WoobookingTable::getWBTable('package_tag'))
                        ->set('package_id=' . $package->id)
                        ->set('tag_id=' . $rate_id);
                    $db->setQuery($query)->execute();
                }
            }
            //start save event
            $list_event_id = $data_post['list_event_id'];
            $query->clear()
                ->delete(WoobookingTable::getWBTable('package_event'))
                ->where('package_id=' . (int)$package->id);
            $db->setQuery($query)->execute();
            foreach ($list_event_id as $event_id) {
                $query->clear()
                    ->insert(WoobookingTable::getWBTable('package_event'))
                    ->set('package_id=' . (int)$package->id)
                    ->set('event_id=' . (int)$event_id);
                $db->setQuery($query)->execute();
            }
            $gallery = $data_post['gallery'];
            unset($data_post['gallery']);
            if (count((array)$gallery)) {
                foreach ($gallery as $image_item) {
                    $name = str_replace(' ', '_',Utility::gen_random_string()) . $image_item['name'];
                    $new_file_cover_path = WPBOOKINGPRO_PATH_ROOT . "/upload/packages/gallery/$name";
                    $data_image = $image_item['data'];
                    $data_image = base64_decode($data_image); // decode an image
                    if (!File::write($new_file_cover_path, $data_image)) {
                        throw new Exception("can not upload image gallery");
                    }
                    $modelGallery = WoobookingModel::getInstance('gallery');
                    $item_image_post = [
                        "id" => 0,
                        "type" => "package",
                        "object_id" => $package->id,
                        "path" => Utility::get_short_file_by_path($new_file_cover_path),
                        "name" => $image_item['name']
                    ];
                    $item_image_post = $modelGallery->save($item_image_post);
                    if (!$item_image_post) {
                        throw new Exception("can save gallery item");
                    }
                }
            }
            $list_image_gallery_deleted = $data_post['list_image_gallery_deleted'];
            $list_image_gallery_deleted = json_decode($list_image_gallery_deleted);
            if (count((array)$list_image_gallery_deleted)) {
                $query->clear()
                    ->select('*')
                    ->from(WoobookingTable::getWBTable('gallery') . ' AS gallery')
                    ->where('id IN (' . implode(',', $list_image_gallery_deleted) . ')')
                    ->where('type=' . $query->quote('package'));
                $list_image_in_gallery_need_delete = $db->setQuery($query)->loadObjectList();
                foreach ($list_image_in_gallery_need_delete as $item) {
                    File::delete(WPBOOKINGPRO_PATH_ROOT . "/" . $item->path);
                }
                $query->clear()
                    ->delete(WoobookingTable::getWBTable('gallery'))
                    ->where('id IN (' . implode(',', $list_image_gallery_deleted) . ')')
                    ->where('type=' . $query->quote('package'));
                $db->setQuery($query)->execute();
            }
            return $package;
        }

        /**
         * @return mixed
         * @throws Exception
         */
        public function ajax_get_rang_time_avail()
        {
            $data = json_decode(file_get_contents('php://input'));
            $date = $data->date;
            $package_id = $data->package_id;
            $package_model = $this->getModel('package');
            $list_date = $package_model->get_rang_time_avail($package_id, $date);
            return $list_date;
        }

        /**
         * @return bool
         * @throws Exception
         */
        public function ajax_delete()
        {
            $modelPackage = WoobookingModel::getInstance('package');
            $input = Factory::getInput();
            $list_delete_package_id = $input->get('list_delete_package_id', array(), 'array');
            foreach ($list_delete_package_id as $package_id) {
                $modelPackage->delete($package_id);
            }
            return true;
        }
    }
}
?>