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

        /**
         * @param array $data_post
         * @return array|bool|object
         * @throws Exception
         */
        public function save($data_post = array())
        {
            $data_post['iframe']=htmlentities($data_post['iframe']);
            $image = $data_post['image_location_avatar'];
            unset($data_post['image_location_avatar']);
            $location = parent::save($data_post); // TODO: Change the autogenerated stub
            if ($image) {
                if ($image) {
                    $name = str_replace(' ', '_',Utility::random_string_by_time()) . $image['name'];
                    $new_file_cover_path = WPBOOKINGPRO_PATH_ROOT . "/upload/locations/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");
                    }
                    $location->image_location_avatar = Utility::get_short_file_by_path($new_file_cover_path);
                }
                $location = parent::save((array)$location);
            }

            return $location;
        }

        /**
         * @param $event_id
         * @param $booking_date
         * @return array
         * @throws Exception
         */
        public function get_rang_time_avail($event_id, $booking_date)
        {
            $booking_date = Factory::getDate($booking_date);
            $model_event = $this->getModel('event');
            $db = Factory::getDBO();
            $query = $db->getQuery(true);
            $event = $model_event->getItem($event_id);
            $product = wc_get_product($event->woo_product_id);
            if ($product->status != "publish") {
                return array();
            }
            $rates = $event->rates;
            $rates = explode(';', $rates);
            if ($event->close == 1) {
                $close_date = Factory::getDate($event->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 ($event->recurring == 1) {
                    $recurring_repeat = $event->recurring_repeat;
                    $recurring_until = Factory::getDate($event->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 $event_date
         * @param $event_end_date
         * @param $event_repetition_type
         * @return array
         */
        protected function get_date_recurring($event_date, $event_end_date, $event_repetition_type)
        {
            $date_calculation = "";
            $event_repetition_type = strtolower($event_repetition_type);
            switch ($event_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[] = $event_date->format('Y-m-d');
            $day = $event_date;
            $to = $event_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();
        }
    }
}