<?php
namespace WpBookingProAdmin\app\models;
defined('_WPBOOKINGPRO_EXEC') or die;

use BaconQrCode\Common\Mode;
use WpBookingPro\Factory;
use WpBookingPro\Mvc\Model\Model;
use WpBookingPro\Mvc\Model\ModelForm;
use WpBookingPro\Form\Form;
use WpBookingPro\Mvc\Model\ModelList;
use WpBookingPro\Registry\Registry;
use WpBookingProAdmin\app\helpers\AdminHelper;
use WpBookingProAdmin\app\Html\HtmlBackend;

class CalendarModel extends ModelList
{
    /**
     * @var string
     */
    public $context = "calendar";
    /**
     * @var string
     */
    public $table_name = "order";


    /**
     * @return mixed
     */
    public function getListQuery()
    {


        $query=$this->db->getQuery(true);
        $query->select("a.*")
            ->from($this->getTableName().' AS a')
            ->where('a.open_source_order_status_id <>'.$query->quote('cancelled'))
            ->orWhere('a.order_status_alias <>'.$query->quote('cancelled'))

        ;
        $query->order($this->getState('list.ordering', 'a.ordering') . ' ' . $this->getState('list.direction', 'ASC'));

        return $query;
    }
    public function getList()
    {
        $db=Factory::getDBO();
        $query=$this->getListQuery();
        $list = $db->setQuery($query)->loadObjectList();
        $now = Factory::getDate();
        $list_rate=[];
        foreach ($list as $item) {
            if(is_user_logged_in()) {
                $modelUser = Model::getInstance('user');
                $user = $modelUser->getUserInfo();
                $item->customer = $user->data->user_plugin;
                $item->customer_full_name = $user->data->display_name;
            } else {
                $query->clear()
                    ->select('customer.*')
                    ->from($this->getTableName('customer') . ' AS customer')
                    ->where('customer.id=' . (int)$item->customer_id);
                $item->customer = $this->db->setQuery($query)->loadObjectList();
                $item->customer_full_name = $item->customer[0]->first_name .' '.$item->customer[0]->last_name;
            }

            $query->clear()
                ->select("order_detail.*")
                ->from($this->getTableName('order_detail') . ' AS order_detail')
                ->where('order_detail.order_id=' . (int)$item->id);
            $item->list_order_detail = $this->db->setQuery($query)->loadObjectList();

            if($item->type_recurring === 'weekly' || $item->type_recurring === 'monthly') {
                $query->clear()
                    ->select('order_day_recurring.*')
                    ->from($this->getTableName('order_day_recurring') .' AS order_day_recurring')
                    ->where('order_day_recurring.order_id='.(int)$item->id)
                ;
                $order_day_recurring = $this->_db->setQuery($query)->loadObject();
                $day = array("monday","tuesday","wednesday","thursday","friday","saturday","sunday");
                $order_day_recurring_select = array();
                foreach ($order_day_recurring as $key => $value) {
                    if(in_array($key, $day) && $value == 1) {
                        array_push($order_day_recurring_select, $key);
                    }
                }
                $item->order_day_recurring = $order_day_recurring_select;
            }
            $list_rate=[];
            foreach ($item->list_order_detail as $order_detail) {
                $query->clear()
                    ->select("order_detail_rate.*")
                    ->from($this->getTableName('order_detail_rate') . ' AS order_detail_rate')
                    ->leftJoin($this->getTableName('service') . ' AS service ON service.id=order_detail_rate.service_id')
                    ->select('service.name as title,service.price as service_price,service.image as service_image, service.description AS description, service.service_color AS service_color')
                    ->leftJoin($this->getTableName('location') . ' AS location  ON location.id=order_detail_rate.location_id')
                    ->select('location.address AS location_address')
                    ->leftJoin($this->getTableName('employee') . ' AS employee  ON employee.id=order_detail_rate.employee_id')
                    ->select('employee.first_name AS employee_first_name,employee.last_name AS employee_last_name,employee.cover AS employee_cover')
                    ->where('order_detail_id=' . (int)$order_detail->id);
                $list_rate = $this->db->setQuery($query)->loadObjectList();
                $number_day_recurring = 0;
                $type_recurring = $item->type_recurring;
                foreach ($list_rate as &$rate) {
                    if(is_user_logged_in()) {
                        $rate->customer_email = $item->customer->email;
                    } else {
                        $rate->customer_email = $item->customer[0]->email;
                    }

                    $rate->is_recurring = $item->is_recurring;
                    $rate->type_recurring = $type_recurring;
                    $rate->order_id = $item->id;
                    $rate->number_month_recurring = $item->number_month_recurring;
                    $rate->number_week_recurring = $item->number_week_recurring;
                    $rate->order_day_recurring = isset($item->order_day_recurring)?$item->order_day_recurring:array();
                    $rate->all_or_specific = isset($item->all_or_specific)?$item->all_or_specific:array();
                    $rate->specific_day = isset($item->specific_day)?json_decode($item->specific_day):array();
                    if($item->is_recurring == 0) {
                        $start_date = Factory::getDate($rate->start_date);
                        $end_date = Factory::getDate($rate->end_date);
                        $since_start = $start_date->diff($end_date);
                        $rate->duration = $since_start->h. ' hours '. $since_start->i. ' minutes';
                        $rate->start = $rate->start_date;
                        $rate->end = $rate->end_date;
                        /////////////////////
                        $startDate = HtmlBackend::render_date($rate->start_date,'Y-m-d');
                        $endDate = HtmlBackend::render_date($rate->end_date,'Y-m-d');
                        $startTime = HtmlBackend::render_date($rate->start_date,'H:i');
                        $endTime = HtmlBackend::render_date($rate->end_date,'H:i');
                        $rate->list_date_detail = ($start_date == $end_date) ? $startDate : $startDate . ' - ' . $endDate;
                        $rate->list_time_detail = $startTime . ' - ' . $endTime;
                        $rate->employee_fullname = $rate->employee_first_name.' '.$rate->employee_last_name;
                        $rate->editable = true;
                    } else {
                        $start_time = Factory::getDate($rate->time_start_recurring);
                        $end_time = Factory::getDate($rate->time_end_recurring);
                        $since_start = $start_time->diff($end_time);
                        $rate->duration = $since_start->h. ' hours '. $since_start->i. ' minutes';
                        $rate->employee_fullname = $rate->employee_first_name.' '.$rate->employee_last_name;
                        $rate->start = $rate->date_start_recurring .' '.$rate->time_start_recurring;
                        $rate->end = $rate->date_end_recurring .' '.$rate->time_end_recurring;
                        $startTime = HtmlBackend::render_date($rate->time_start_recurring,'H:i');
                        $endTime = HtmlBackend::render_date($rate->time_end_recurring,'H:i');
                        $rate->list_time_detail = $startTime . ' - ' . $endTime;

                        $start_recurring = strtotime($rate->date_start_recurring);
                        $end_recurring = strtotime($rate->date_end_recurring);
                        $rate->editable = false;
                        if($type_recurring == 'weekly' || $type_recurring == 'monthly') {
                            while($start_recurring <= $end_recurring) {
                                $day = date('l', $start_recurring);
                                if(in_array(strtolower($day),$item->order_day_recurring)) {
                                    $number_day_recurring++;
                                }
                                $start_recurring = strtotime("+1 day", $start_recurring);
                            }


                            if($type_recurring == 'monthly' && $item->all_or_specific == 'specific-day') {
                                $day_register = AdminHelper::getDateOfWeekDayInMonth($rate->date_start_recurring,$rate->date_end_recurring, $item->order_day_recurring);

                                $day_register =call_user_func_array("array_merge", $day_register);
                                $specific_day = isset($item->specific_day)?json_decode($item->specific_day):array();
                                $exdate = array_diff($day_register, $specific_day);
                                $weekday = implode(',',array_map(function ($v){
                                    return strtoupper(substr($v,0,2));
                                },$item->order_day_recurring));
                                $exDate = '';
                                foreach ($exdate as &$exdate_item) {
                                    $exdate_item = str_replace('-','',$exdate_item).'T'.str_replace(':','',$rate->time_start_recurring);
                                }
                                $exDate = implode(',', $exdate);
                                $rate->rrule1 = 'DTSTART:'.str_replace('-','',$rate->date_start_recurring) .'T'.str_replace(':','',$rate->time_start_recurring);
                                $rate->rrule2 = 'RRULE:FREQ=MONTHLY;COUNT='.$number_day_recurring.';BYDAY='.$weekday;
                                $rate->rrule3 = 'EXDATE:'.$exDate;
                            } else {
                                $rrule = new \stdClass();
                                $rrule->freq = $type_recurring;
                                $rrule->count = $number_day_recurring;
                                $rrule->byweekday = (array_map(function ($v){
                                    return substr($v,0,2);
                                },$item->order_day_recurring));
                                $rrule->dtstart = $rate->date_start_recurring .'T'.$rate->time_start_recurring;
                                $rate->rrule = $rrule;
                            }


                        } elseif($type_recurring == 'daily') {
                            while($start_recurring <= $end_recurring) {
                                $number_day_recurring++;
                                $start_recurring = strtotime("+1 day", $start_recurring);
                            }
                            $rrule = new \stdClass();
                            $rrule->freq = $type_recurring;
                            $rrule->count = $number_day_recurring;
                            $rrule->dtstart = $rate->date_start_recurring .'T'.$rate->time_start_recurring;
                            $rate->rrule = $rrule;
                        }
                    }

                }
                $order_detail->rate = $list_rate;
                $item->number_day_recurring = $number_day_recurring;
            }
            $item->list_rate = reset($list_rate);

        }

        return $list;
    }
    public function getListOrderByEmployeeId($employee_id=0) {
        $db=Factory::getDBO();
        $query=$this->getListQuery();
        $list = $db->setQuery($query)->loadObjectList();
        $now=Factory::getDate();
        $list_rate=[];
        foreach ($list as $item) {
            $query->clear()
                ->select('customer.*')
                ->from($this->getTableName('customer') . ' AS customer')
                ->where('customer.id=' . (int)$item->customer_id);
            $item->customer = $this->db->setQuery($query)->loadObjectList();
            $item->customer_full_name = $item->customer[0]->first_name .' '.$item->customer[0]->last_name;
            $query->clear()
                ->select("DISTINCT order_detail.*")
                ->from($this->getTableName('order_detail') . ' AS order_detail')
                ->where('order_detail.order_id=' . (int)$item->id);
            if($employee_id!== 0 ) {
                $query->where('order_detail.employee_id='.(int)$employee_id);
            }
            $item->list_order_detail = $this->db->setQuery($query)->loadObjectList();
            if($item->type_recurring === 'weekly' || $item->type_recurring === 'monthly') {
                $query->clear()
                    ->select('order_day_recurring.*')
                    ->from($this->getTableName('order_day_recurring') .' AS order_day_recurring')
                    ->where('order_day_recurring.order_id='.(int)$item->id)
                ;
                $order_day_recurring = $this->_db->setQuery($query)->loadObject();
                $day = array("monday","tuesday","wednesday","thursday","friday","saturday","sunday");
                $order_day_recurring_select = array();
                foreach ($order_day_recurring as $key => $value) {
                    if(in_array($key, $day) && $value == 1) {
                        array_push($order_day_recurring_select, $key);
                    }
                }
                $item->order_day_recurring = $order_day_recurring_select;
            }
            $list_rate=[];
            foreach ($item->list_order_detail as $order_detail) {
                $query->clear()
                    ->select("order_detail_rate.*")
                    ->from($this->getTableName('order_detail_rate') . ' AS order_detail_rate')
                    ->leftJoin($this->getTableName('service') . ' AS service ON service.id=order_detail_rate.service_id')
                    ->select('service.name as title,service.price as service_price,service.image as service_image, service.description AS description, service.service_color AS service_color')
                    ->leftJoin($this->getTableName('location') . ' AS location  ON location.id=order_detail_rate.location_id')
                    ->select('location.address AS location_address')
                    ->leftJoin($this->getTableName('employee') . ' AS employee  ON employee.id=order_detail_rate.employee_id')
                    ->select('employee.first_name AS employee_first_name,employee.last_name AS employee_last_name,employee.cover AS employee_cover')
                    ->where('order_detail_id=' . (int)$order_detail->id);
                $list_rate = $this->db->setQuery($query)->loadObjectList();
                $number_day_recurring = 0;
                $type_recurring = $item->type_recurring;
                foreach ($list_rate as &$rate) {
                    $rate->customer_email = $item->customer[0]->email;
                    $rate->is_recurring = $item->is_recurring;
                    $rate->type_recurring = $type_recurring;
                    $rate->order_id = $item->id;
                    $rate->number_month_recurring = $item->number_month_recurring;
                    $rate->number_week_recurring = $item->number_week_recurring;
                    $rate->order_day_recurring = isset($item->order_day_recurring)?$item->order_day_recurring:array();
                    $rate->all_or_specific = isset($item->all_or_specific)?$item->all_or_specific:'';
                    $rate->specific_day = isset($item->specific_day)?json_decode($item->specific_day):array();
                    if($item->is_recurring == 0) {
                        $start_date = Factory::getDate($rate->start_date);
                        $end_date = Factory::getDate($rate->end_date);
                        $since_start = $start_date->diff($end_date);
                        $rate->duration = $since_start->h. ' hours '. $since_start->i. ' minutes';
                        $rate->start = $rate->start_date;
                        $rate->end = $rate->end_date;
                        /////////////////////
                        $startDate = HtmlBackend::render_date($rate->start_date,'Y-m-d');
                        $endDate = HtmlBackend::render_date($rate->end_date,'Y-m-d');
                        $startTime = HtmlBackend::render_date($rate->start_date,'H:i');
                        $endTime = HtmlBackend::render_date($rate->end_date,'H:i');
                        $rate->list_date_detail = ($start_date == $end_date) ? $startDate : $startDate . ' - ' . $endDate;
                        $rate->list_time_detail = $startTime . ' - ' . $endTime;
                        $rate->employee_fullname = $rate->employee_first_name.' '.$rate->employee_last_name;
                        $rate->editable = true;
                    } else {
                        $start_time = Factory::getDate($rate->time_start_recurring);
                        $end_time = Factory::getDate($rate->time_end_recurring);
                        $since_start = $start_time->diff($end_time);
                        $rate->duration = $since_start->h. ' hours '. $since_start->i. ' minutes';
                        $rate->employee_fullname = $rate->employee_first_name.' '.$rate->employee_last_name;
                        $rate->start = $rate->date_start_recurring .' '.$rate->time_start_recurring;
                        $rate->end = $rate->date_end_recurring .' '.$rate->time_end_recurring;
                        $startTime = HtmlBackend::render_date($rate->time_start_recurring,'H:i');
                        $endTime = HtmlBackend::render_date($rate->time_end_recurring,'H:i');
                        $rate->list_time_detail = $startTime . ' - ' . $endTime;

                        $start_recurring = strtotime($rate->date_start_recurring);
                        $end_recurring = strtotime($rate->date_end_recurring);
                        $rate->editable = false;
                        if($type_recurring == 'weekly' || $type_recurring == 'monthly') {
                            while($start_recurring <= $end_recurring) {
                                $day = date('l', $start_recurring);
                                if(in_array(strtolower($day),$item->order_day_recurring)) {
                                    $number_day_recurring++;
                                }
                                $start_recurring = strtotime("+1 day", $start_recurring);
                            }



                            if($type_recurring == 'monthly' && $item->all_or_specific == 'specific-day') {
                                $day_register = AdminHelper::getDateOfWeekDayInMonth($rate->date_start_recurring,$rate->date_end_recurring, $item->order_day_recurring);
                                $day_register =call_user_func_array("array_merge", $day_register);
                                $specific_day = isset($item->specific_day)?json_decode($item->specific_day):array();
                                $exdate = array_diff($day_register, $specific_day);
                                $weekday = implode(',',array_map(function ($v){
                                    return strtoupper(substr($v,0,2));
                                },$item->order_day_recurring));
                                $exDate = '';
                                foreach ($exdate as &$exdate_item) {
                                    $exdate_item = str_replace('-','',$exdate_item).'T'.str_replace(':','',$rate->time_start_recurring);
                                }
                                $exDate = implode(',', $exdate);
                                $rate->rrule1 = 'DTSTART:'.str_replace('-','',$rate->date_start_recurring) .'T'.str_replace(':','',$rate->time_start_recurring);
                                $rate->rrule2 = 'RRULE:FREQ=MONTHLY;COUNT='.$number_day_recurring.';BYDAY='.$weekday;
                                $rate->rrule3 = 'EXDATE:'.$exDate;
                            } else {
                                $rrule = new \stdClass();
                                $rrule->freq = $type_recurring;
                                $rrule->count = $number_day_recurring;
                                $rrule->byweekday = (array_map(function ($v){
                                    return substr($v,0,2);
                                },$item->order_day_recurring));
                                $rrule->dtstart = $rate->date_start_recurring .'T'.$rate->time_start_recurring;
                                $rate->rrule = $rrule;
                            }


                        } elseif($type_recurring == 'daily') {
                            while($start_recurring <= $end_recurring) {
                                $number_day_recurring++;
                                $start_recurring = strtotime("+1 day", $start_recurring);
                            }
                            $rrule = new \stdClass();
                            $rrule->freq = $type_recurring;
                            $rrule->count = $number_day_recurring;
                            $rrule->dtstart = $rate->date_start_recurring .'T'.$rate->time_start_recurring;
                            $rate->rrule = $rrule;
                        }
                    }

                }
                $order_detail->rate = $list_rate;
                $item->number_day_recurring = $number_day_recurring;
            }
            $item->list_rate = reset($list_rate);

        }

        return $list;
    }

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


}
