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

        /**
         * @param array $data
         * @return array|bool|object
         * @throws Exception
         */
        public function save($data = array())
        {
            $input = Factory::getInput();
            $data_post = $input->getData()['data'];
            $cover = $data_post['image'];
            unset($data_post['image']);
            $category = parent::save($data_post); // TODO: Change the autogenerated stub
            if ($cover) {
                if ($cover) {
                    $name = str_replace(' ', '_',Utility::random_string_by_time()) . $cover['name'];
                    $new_file_cover_path = WPBOOKINGPRO_PATH_ROOT . "/upload/employees/images/cover/$name";
                    $data_image = $cover['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");
                    }
                    $category->image = Utility::get_short_file_by_path($new_file_cover_path);
                }
                $category = parent::save((array)$category);
            }
            return $category;
        }

        /**
         * @param int $id
         * @return mixed
         */
        public function getItem($id = 0)
        {
            $item = parent::getItem($id); // TODO: Change the autogenerated stub
            if ($item) {
                $db = Factory::getDBO();
                $query = $db->getQuery(true)
                    ->select("tag.name")
                    ->from(WoobookingTable::getWBTable('category_tag') . ' AS category_tag')
                    ->leftJoin(WoobookingTable::getWBTable('tag') . ' AS tag ON tag.id=category_tag.tag_id')
                    ->where('category_tag.category_id=' . (int)$item->id);
                $item->tags = $db->setQuery($query)->loadColumn();
            }
            return $item;
        }

        /**
         * @return array
         */
        public function getHeader()
        {
            return array();
        }
    }
}