<?php
defined('_WPBOOKINGPRO_EXEC') or die;
use WooBooking\CMS\Filesystem\File;
use WooBooking\CMS\Registry\Registry;
use WooBooking\CMS\Utilities\Utility;
if(!class_exists("WpBookingPro_serviceModel")) {
    /**
     * Class WpBookingPro_serviceModel
     */
    class WpBookingPro_serviceModel extends WoobookingModelForm
    {
        /**
         * @var string
         */
        public $table_name = "service";
        /**
         * @var string
         */
        public $context = "service";

        /**
         * @param array $data_post
         * @return array|bool|object
         * @throws Exception
         */
        public function save($data_post = array())
        {
            $data_post['bringing_anyone'] = $data_post['bringing_anyone'] == 1 ? $data_post['bringing_anyone'] : 0;
            $data_post['payment_status'] = $data_post['payment_status'] == 1 ? $data_post['payment_status'] : 0;
            $image = $data_post['image'];
            unset($data_post['image']);
            $params = array();
            foreach ($data_post as $key => $value) {
                if (strpos($key, "params") !== false) {
                    $key = substr($key, 7);
                    $params[$key] = $value;
                }
            }
            $data_post['params'] = json_encode($params);
            $db = Factory::getDBO();
            $query = $db->getQuery(true);
            $service = parent::save($data_post); // TODO: Change the autogenerated stub
            if (!$service) {
                return false;
            }
            if ($image) {
                if ($image) {
                    $name = 'image-cover-' . $service->id . '-' . $image['name'];
                    $new_file_cover_path = WPBOOKINGPRO_PATH_ROOT . "/upload/services/images/$name";
                    $data_image = $image['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 cover");
                    }
                    $service->image = Utility::get_short_file_by_path($new_file_cover_path);
                }
                parent::save((array)$service);
            }
            $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/services/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" => "service",
                        "object_id" => $service->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 imte");
                    }
                }
            }
            $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('service'));
                $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('service'));
                $db->setQuery($query)->execute();
            }
            $query->clear()
                ->select('id')
                ->from(WoobookingTable::getWBTable('extra'))
                ->where('object_id=' . (int)$service->id)
                ->where('type=' . $query->quote('service'));
            $list_old_extra_id = $db->setQuery($query)->loadColumn();
            $extras = $data_post['extra'];
            $extraModel = WoobookingModel::getInstance('extra');
            $list_keep_id = [];
            if (!empty($extras)) {
                foreach ($extras as $extra) {
                    $extra = base64_decode($extra);
                    $extra = json_decode($extra);
                    $extra->type = "service";
                    $extra->object_id = $service->id;
                    if ($extra->id) {
                        $list_keep_id[] = $extra->id;
                    }
                    $extra = (array)$extra;
                    $extraModel->save($extra);
                }
            }
            $list_id_need_delete = array_diff($list_old_extra_id, $list_keep_id);
            if (count($list_id_need_delete)) {
                $query->clear()
                    ->delete(WoobookingTable::getWBTable('extra'))
                    ->where('object_id=' . (int)$service->id)
                    ->where('id IN (' . implode(',', $list_id_need_delete) . ')')
                    ->where('type=' . $query->quote('service'));
                $db->setQuery($query)->execute();
            }
            //start save employee
            $list_employee_id = $data_post['list_employee_id'];
            $query->clear()
                ->delete(WoobookingTable::getWBTable('service_employee'))
                ->where('service_id=' . (int)$service->id);
            $db->setQuery($query)->execute();
            foreach ($list_employee_id as $employee_id) {
                $query->clear()
                    ->insert(WoobookingTable::getWBTable('service_employee'))
                    ->set('service_id=' . (int)$service->id)
                    ->set('employee_id=' . (int)$employee_id);
                $db->setQuery($query)->execute();
            }
            return $service;
        }

        /**
         * @param int $id
         * @return mixed|object
         */
        public function getItem($id = 0)
        {
            $item = (object)parent::getItem($id); // TODO: Change the autogenerated stub
            $input = Factory::getInput();
            if (!$item->id) {
                $item->category_id = $input->getInt('category_id', 0);
            }
            $db = Factory::getDBO();
            $query = $db->getQuery(true);
            if ($item->id) {
                $query->clear()
                    ->select('extra.*')
                    ->from(WoobookingTable::getWBTable('extra') . ' AS extra')
                    ->where('object_id=' . $item->id)
                    ->where('type=' . $query->quote('service'));
                $item->extra = $db->setQuery($query)->loadObjectList();
                $query->clear()
                    ->select('gallery.*')
                    ->from(WoobookingTable::getWBTable('gallery') . ' AS gallery')
                    ->where('object_id=' . $item->id)
                    ->where('type=' . $query->quote('service'));
                $item->gallery = $db->setQuery($query)->loadObjectList();
                $query->clear()
                    ->select('service_employee.employee_id')
                    ->from(WoobookingTable::getWBTable('service_employee') . ' AS service_employee')
                    ->where('service_id=' . $item->id);
                $item->list_employee_id = $db->setQuery($query)->loadColumn();
                $query->clear()
                    ->select('location.id')
                    ->from(WoobookingTable::getWBTable('location') . ' AS location')
                    ->where('location.id=' . (int)$item->location_id);
                $item->location_id = $db->setQuery($query)->loadResult();;
            }
            $register = new Registry();
            $register->loadString($item->params);
            $item->params = $register;
            return $item;
        }
    }
}