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


        /**
         * @return mixed
         * @throws Exception
         */
        public function ajax_add_new_event()
        {
            //TODO check permission add new
            return self::view("event.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'];
            }

            $data_post['open_date'] = Factory::getDate($data_post['open_date'])->toSql();
            $data_post['close_date'] = Factory::getDate($data_post['close_date'])->toSql();
            $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;

            $event = parent::save($data_post); // TODO: Change the autogenerated stub

            $modelRate = WoobookingModel::getInstance('rate');
            $query->clear()
                ->delete(WoobookingTable::getWBTable('rate'))
                ->where('object_id=' . $event->id)
                ->where('type=' . $query->quote(WpBookingPro_RateHelperAdmin::getEventName()));
            $db->setQuery($query)->execute();
            if (count($rates)) {
                foreach ($rates as $rate) {
                    $rate = (string)$rate;
                    list($from, $to) = explode(";", $rate);
                    $item_rate = [
                        "id" => 0,
                        "from" => Factory::getDate($from)->toSql(),
                        "to" => Factory::getDate($to)->toSql(),
                        "type" => WpBookingPro_RateHelperAdmin::getEventName(),
                        "object_id" => $event->id
                    ];
                    $item_rate = $modelRate->save($item_rate);
                }
            }
            $list_tag_id = [];
            if (count($tags)) {
                $query->clear()
                    ->delete(WoobookingTable::getWBTable('event_tag'))
                    ->where('event_id=' . $event->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 ($event && count($list_tag_id)) {
                $query->clear()
                    ->delete(WoobookingTable::getWBTable('event_tag'))
                    ->where('event_id=' . $event->id);
                $db->setQuery($query)->execute();
                foreach ($list_tag_id as $rate_id) {
                    $query->clear()
                        ->insert(WoobookingTable::getWBTable('event_tag'))
                        ->set('event_id=' . $event->id)
                        ->set('tag_id=' . $rate_id);
                    $db->setQuery($query)->execute();
                }
            }
            //start save employee
            $list_employee_id = $data_post['list_employee_id'];
            $query->clear()
                ->delete(WoobookingTable::getWBTable('event_employee'))
                ->where('event_id=' . (int)$event->id);
            $db->setQuery($query)->execute();
            foreach ($list_employee_id as $employee_id) {
                $query->clear()
                    ->insert(WoobookingTable::getWBTable('event_employee'))
                    ->set('event_id=' . (int)$event->id)
                    ->set('employee_id=' . (int)$employee_id);
                $db->setQuery($query)->execute();
            }
            $gallery = (array)$data_post['gallery'];
            unset($data_post['gallery']);
            if (count($gallery)) {
                foreach ($gallery as $image_item) {
                    $name = str_replace(' ', '_',Utility::gen_random_string()) . $image_item['name'];
                    $new_file_cover_path = WPBOOKINGPRO_PATH_ROOT . "/upload/events/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" => "event",
                        "object_id" => $event->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 = (array)json_decode($list_image_gallery_deleted);
            if (count($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('event'));
                $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('event'));
                $db->setQuery($query)->execute();
            }
            return $event;
        }

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

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