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

        /**
         * @param array $data
         * @return array|bool|object
         * @throws Exception
         */
        public function save($data = array())
        {
            $input = Factory::getInput();

            $data_post = (array)$input->getData()['data'];
            if (empty($data_post)) {
                $data_post = (array)$input->getData();
            }

            $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;
        }

        /**
         * @param $category_id
         * @param $booking_date
         * @return array
         * @throws Exception
         */
        public function get_rang_time_avail($category_id, $booking_date)
        {
            $booking_date = Factory::getDate($booking_date);
            $model_category = $this->getModel('category');
            $db = Factory::getDBO();
            $query = $db->getQuery(true);
            $category = $model_category->getItem($category_id);
            $product = wc_get_product($category->woo_product_id);
            if ($product->status != "publish") {
                return array();
            }
            $rates = $category->rates;
            $rates = explode(';', $rates);
            if ($category->close == 1) {
                $close_date = Factory::getDate($category->close_date);
                if ($booking_date > $close_date) {
                    return [];
                }
            }
            $list_rate = [];
            foreach ($rates as $rate) {
                list($start, $end) = explode(',', $rate);
                $start = Factory::getDate($start);
                $end = Factory::getDate($end);
                //check in range
                $in_range = ($booking_date >= $start) && ($booking_date <= $end);
                //check recurring
                $list_recurring = [];
                if ($category->recurring == 1) {
                    $recurring_repeat = $category->recurring_repeat;
                    $recurring_until = Factory::getDate($category->recurring_until);
                    $list_recurring = self::get_date_recurring($start, $recurring_until, $recurring_repeat);
                }
                if ($in_range && count($list_recurring) && self::check_date_in_range_date($booking_date, $list_recurring)) {
                    $item_rate = [$start->format('h:i'), $end->format('h:i')];
                    $list_rate[] = $item_rate;
                } elseif ($in_range) {
                    $item_rate = [$start->format('h:i'), $end->format('h:i')];
                    $list_rate[] = $item_rate;
                }
            }
            return $list_rate;
        }

        /**
         * @param $date
         * @param $dates
         * @return bool
         */
        protected function check_date_in_range_date($date, $dates)
        {
            $date_strtotime = strtotime($date);
            foreach ($dates AS $date) {
                $timestamp = strtotime($date);
                if ($timestamp == $date_strtotime) {
                    return true;
                }
            }
            return false;
        }

        /**
         * @param $category_date
         * @param $category_end_date
         * @param $category_repetition_type
         * @return array
         */
        protected function get_date_recurring($category_date, $category_end_date, $category_repetition_type)
        {
            $date_calculation = "";
            $category_repetition_type = strtolower($category_repetition_type);
            switch ($category_repetition_type) {
                case "daily":
                    $date_calculation = " +1 day";
                    break;
                case "weekly":
                    $date_calculation = " +1 week";
                    break;
                case "monthly":
                    $date_calculation = " +1 month";
                    break;
                default:
                    $date_calculation = "none";
            }
            $dateArray[] = $category_date->format('Y-m-d');
            $day = $category_date;
            $to = $category_end_date;
            while ($day <= $to) {
                $day = $day->modify($date_calculation);
                $dateArray[] = $day->format('Y-m-d');
            }
            //here make above array as key in $a array
            return $dateArray;
        }

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