<?php
defined('_WPBOOKINGPRO_EXEC') or die;
if(!class_exists("WpBookingPro_LocationsModel")) {
    /**
     * Class WpBookingPro_LocationsModel
     */
    class WpBookingPro_LocationsModel extends WoobookingModelList
    {
        /**
         * @var string
         */
        public $table_name = "location";
        /**
         * @var string
         */
        public $context = "locations";

        /**
         * @param $data
         * @return array|bool
         */
        public function save($data)
        {
            $is_new = !$data['id'];
            if ($event = parent::save($data)) {
                if ($is_new) {
                    if ($post_id = wp_insert_post(array(
                        'post_title' => $event['name'],
                        'post_type' => 'product',
                        'post_status' => 'publish',
                        'post_content' => 'event',
                        'post_excerpt' => 'event'
                    ))) {
                        wp_set_object_terms($post_id, 'Races', 'product_cat');
                        wp_set_object_terms($post_id, 'simple', 'product_type');
                        update_post_meta($post_id, '_visibility', 'visible');
                        update_post_meta($post_id, '_stock_status', 'instock');
                        update_post_meta($post_id, 'total_sales', '0');
                        update_post_meta($post_id, '_downloadable', 'yes');
                        update_post_meta($post_id, '_virtual', 'yes');
                        update_post_meta($post_id, '_regular_price', "1");
                        update_post_meta($post_id, '_sale_price', "1");
                        update_post_meta($post_id, '_purchase_note', "");
                        update_post_meta($post_id, '_featured', "no");
                        update_post_meta($post_id, '_weight', "");
                        update_post_meta($post_id, '_length', "");
                        update_post_meta($post_id, '_width', "");
                        update_post_meta($post_id, '_height', "");
                        update_post_meta($post_id, '_sku', "");
                        update_post_meta($post_id, '_product_attributes', array());
                        update_post_meta($post_id, '_sale_price_dates_from', "");
                        update_post_meta($post_id, '_sale_price_dates_to', "");
                        update_post_meta($post_id, '_price', "1");
                        update_post_meta($post_id, '_sold_individually', "");
                        update_post_meta($post_id, '_manage_stock', "no");
                        update_post_meta($post_id, '_backorders', "no");
                        update_post_meta($post_id, '_stock', "");
                        $event['woo_product_id'] = $post_id;
                        $event = parent::save($event);
                    } else {
                        $this->delete($event['id']);
                        return false;
                    }
                }
            }
            return $event;
        }

        /**
         * @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;
        }

        /**
         * @param array $listId
         * @return mixed
         */
        public function getLocationByListId(Array $listId)
        {
            $db = $this->_db;
            $query = $db->getQuery(true);
            $query->select('location.*')
                ->from($this->getTableName('location') . ' AS location');
            if (!empty($listId)) {
                $query->where('location.id IN (' . implode(',', $listId) . ')');
            };
            $list = $db->setQuery($query)->loadObjectList();
            return $list;
        }

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