<?php
namespace WpBookingProFrontend\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 WpBookingProFrontend\app\helpers\FrontendHelper;
use WpBookingProFrontend\app\Html\HtmlFrontend;

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

    public function getList()
    {
        $list_order =  parent::getList(); // TODO: Change the autogenerated stub
        foreach ($list_order as $order) {
            $query = $this->db->getQuery(true);
            $query->clear()
                ->select('customer.*')
                ->from($this->getTableName('customer') . ' AS customer')
                ->where('customer.id=' . (int)$order->customer_id);
            $order->customer = $this->db->setQuery($query)->loadObjectList();
            $order->customer_full_name = $order->customer[0]->first_name .' '.$order->customer[0]->last_name;
            $query->clear()
                ->select("order_detail.*")
                ->from($this->getTableName('order_detail') . ' AS order_detail')
                ->where('order_detail.order_id=' . (int)$order->id);
            $order->list_order_detail = $this->db->setQuery($query)->loadObjectList();

            if($order->type_recurring === 'weekly' || $order->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)$order->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);
                    }
                }
                $order->order_day_recurring = $order_day_recurring_select;
            }
            $list_rate=[];
            foreach ($order->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 service_name,service.price as service_price,service.image as service_image, service.description AS service_description')
                    ->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 = $order->type_recurring;
                foreach ($list_rate as &$rate) {
                    if($order->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';
                        /////////////////////
                        $startDate = HtmlFrontend::render_date($rate->start_date,'Y-m-d');
                        $endDate = HtmlFrontend::render_date($rate->end_date,'Y-m-d');
                        $startTime = HtmlFrontend::render_date($rate->start_date,'H:i');
                        $endTime = HtmlFrontend::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->day_recurring_register = array();
                    } else {
                        $start_recurring = strtotime($rate->date_start_recurring);
                        $end_recurring = strtotime($rate->date_end_recurring);
                        $specific_day = isset($order->specific_day)?json_decode($order->specific_day):array();
                        if($type_recurring == 'weekly' || $type_recurring == 'monthly') {
                            if($type_recurring == 'monthly' && $order->all_or_specific == 'specific-day') {
                                $number_day_recurring = count((array)$specific_day);
                            } else {
                                while($start_recurring <= $end_recurring) {
                                    $day = date('l', $start_recurring);
                                    if(in_array(strtolower($day),$order->order_day_recurring)) {
                                        $number_day_recurring++;
                                    }
                                    $start_recurring = strtotime("+1 day", $start_recurring);
                                }
                            }
                            $rate->day_recurring_register = FrontendHelper::getDateOfWeekDayInMonth($rate->date_start_recurring,$rate->date_end_recurring, $order->order_day_recurring);
                        } elseif($type_recurring == 'daily') {
                            while($start_recurring <= $end_recurring) {
                                $number_day_recurring++;
                                $start_recurring = strtotime("+1 day", $start_recurring);
                            }
                            $rate->day_recurring_register = array();
                        }

                    }

                }
                $order_detail->rate = $list_rate;
                $order->number_day_recurring = $number_day_recurring;
            }
            $order->list_rate = $list_rate;
        }
        return $list_order;
    }

    public function getListOrderByUserID() {
        if(is_user_logged_in()) {
            $modelUser = Model::getInstance('user');
            $user = $modelUser->getUserInfo();
            $db = Factory::getDBO();
            $query = $db->getQuery(true);
            $query->clear()
                ->select('*')
                ->from($this->getTableName('order'))
                ->where('user_id='.(int)$user->data->user_plugin->id)
            ;
            $list_order = $db->setQuery($query)->loadObjectList();
            foreach ($list_order as $order) {

                $query->clear()
                    ->select('name')
                    ->from($this->getTableName('order_status'))
                    ->where('open_source_order_status_id='.$query->quote($order->open_source_order_status_id) )
                ;
                $order->status_payment = $db->setQuery($query)->loadResult();

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

                if($order->type_recurring === 'weekly' || $order->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)$order->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);
                        }
                    }
                    $order->order_day_recurring = $order_day_recurring_select;
                }
                $list_rate=[];
                foreach ($order->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 service_name,service.price as service_price,service.image as service_image, service.description AS service_description')
                        ->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 = $order->type_recurring;
                    foreach ($list_rate as &$rate) {
                        if($order->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';
                            /////////////////////
                            $startDate = HtmlFrontend::render_date($rate->start_date,'Y-m-d');
                            $endDate = HtmlFrontend::render_date($rate->end_date,'Y-m-d');
                            $startTime = HtmlFrontend::render_date($rate->start_date,'H:i');
                            $endTime = HtmlFrontend::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->day_recurring_register = array();
                        } else {
                            $start_recurring = strtotime($rate->date_start_recurring);
                            $end_recurring = strtotime($rate->date_end_recurring);
                            $specific_day = isset($order->specific_day)?json_decode($order->specific_day):array();
                            if($type_recurring == 'weekly' || $type_recurring == 'monthly') {
                                if($type_recurring == 'monthly' && $order->all_or_specific == 'specific-day') {
                                    $number_day_recurring = count((array)$specific_day);
                                } else {
                                    while($start_recurring <= $end_recurring) {
                                        $day = date('l', $start_recurring);
                                        if(in_array(strtolower($day),$order->order_day_recurring)) {
                                            $number_day_recurring++;
                                        }
                                        $start_recurring = strtotime("+1 day", $start_recurring);
                                    }
                                }
                                $rate->day_recurring_register = FrontendHelper::getDateOfWeekDayInMonth($rate->date_start_recurring,$rate->date_end_recurring, $order->order_day_recurring);
                            } elseif($type_recurring == 'daily') {
                                while($start_recurring <= $end_recurring) {
                                    $number_day_recurring++;
                                    $start_recurring = strtotime("+1 day", $start_recurring);
                                }
                                $rate->day_recurring_register = array();
                            }

                        }

                    }
                    $order_detail->rate = $list_rate;
                    $order->number_day_recurring = $number_day_recurring;
                }
                $order->list_rate = $list_rate;
            }
            return $list_order;

        }
        return array();
    }
    public function getListOrderByVendorID() {
        if(is_user_logged_in()) {
            $modelUser = Model::getInstance('user');
            $user = $modelUser->getUserInfo();
            $db = Factory::getDBO();
            $query = $db->getQuery(true);
            $query->clear()
                ->select('*')
                ->from($this->getTableName('order'))
                ->where('vendor_id='.(int)$user->data->user_plugin->id)
            ;
            $list_order = $db->setQuery($query)->loadObjectList();
            foreach ($list_order as $order) {

                $query->clear()
                    ->select('name')
                    ->from($this->getTableName('order_status'))
                    ->where('open_source_order_status_id='.$query->quote($order->open_source_order_status_id) )
                ;
                $order->status_payment = $db->setQuery($query)->loadResult();

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

                if($order->type_recurring === 'weekly' || $order->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)$order->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);
                        }
                    }
                    $order->order_day_recurring = $order_day_recurring_select;
                }
                $list_rate=[];
                foreach ($order->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 service_name,service.price as service_price,service.image as service_image, service.description AS service_description')
                        ->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 = $order->type_recurring;
                    foreach ($list_rate as &$rate) {
                        if($order->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';
                            /////////////////////
                            $startDate = HtmlFrontend::render_date($rate->start_date,'Y-m-d');
                            $endDate = HtmlFrontend::render_date($rate->end_date,'Y-m-d');
                            $startTime = HtmlFrontend::render_date($rate->start_date,'H:i');
                            $endTime = HtmlFrontend::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->day_recurring_register = array();
                        } else {
                            $start_recurring = strtotime($rate->date_start_recurring);
                            $end_recurring = strtotime($rate->date_end_recurring);
                            $specific_day = isset($order->specific_day)?json_decode($order->specific_day):array();
                            if($type_recurring == 'weekly' || $type_recurring == 'monthly') {
                                if($type_recurring == 'monthly' && $order->all_or_specific == 'specific-day') {
                                    $number_day_recurring = count((array)$specific_day);
                                } else {
                                    while($start_recurring <= $end_recurring) {
                                        $day = date('l', $start_recurring);
                                        if(in_array(strtolower($day),$order->order_day_recurring)) {
                                            $number_day_recurring++;
                                        }
                                        $start_recurring = strtotime("+1 day", $start_recurring);
                                    }
                                }
                                $rate->day_recurring_register = FrontendHelper::getDateOfWeekDayInMonth($rate->date_start_recurring,$rate->date_end_recurring, $order->order_day_recurring);
                            } elseif($type_recurring == 'daily') {
                                while($start_recurring <= $end_recurring) {
                                    $number_day_recurring++;
                                    $start_recurring = strtotime("+1 day", $start_recurring);
                                }
                                $rate->day_recurring_register = array();
                            }

                        }

                    }
                    $order_detail->rate = $list_rate;
                    $order->number_day_recurring = $number_day_recurring;
                }
                $order->list_rate = $list_rate;
            }
            return $list_order;

        }
        return array();
    }

    public function getListServiceWishlistByUser() {
        if(is_user_logged_in()) {
            $user_id = isset($_SESSION['user_id']) ? sanitize_text_field($_SESSION['user_id']) : '';
            $db = Factory::getDBO();
            $query = $db->getQuery(true);
            $query->clear()
                ->select('service_id')
                ->from($this->getTableName('wishlist'))
                ->where('user_id='.(int)$user_id)
            ;
            $list_service_id = $db->setQuery($query)->loadColumn();
            if(!empty($list_service_id)) {
                $query->clear()
                    ->select('*')
                    ->from($this->getTableName('service'))
                    ->where('id IN ('.implode(',', $list_service_id).')')
                ;
                $list_service = $db->setQuery($query)->loadObjectList();
                foreach ($list_service as $service) {

                    $query->clear()
                        ->select('name')
                        ->from($this->getTableName('category'))
                        ->where('id='.(int)$service->category_id)
                    ;
                    $category_name = $db->setQuery($query)->loadResult();
                    $service->category_name = $category_name;
                }
                return $list_service;
            } else {
                return array();
            }

        }
        return array();
    }


}
