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

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 WpBookingPro\Utilities\Utility;
use WpBookingProAdmin\app\helpers\AdminHelper;
use WpBookingProAdmin\app\Html\HtmlBackend;

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

    public function getListQuery()
    {
        $input = Factory::getInput();
        $user_id  = $input->getInt('user_id',0);
        $query=$this->db->getQuery(true);
        $query->select("DISTINCT a.*")
            ->from($this->getTableName().' AS a')
            ->where('a.type='.$query->quote(AdminHelper::getWpBookingServiceKey()))

        ;

        if($user_id > 0) {
            $query->where('a.user_id='.(int)$user_id);
        }

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

        return $query;
    }
    public function getList()
    {
        $query=$this->getListQuery();

        $list = $this->db->setQuery($query)->loadObjectList();
        foreach ($list as &$item) {
            if(is_user_logged_in()) {
                $modelUser = Model::getInstance('user');
                $user = $modelUser->getUserInfo();
                $item->customer = $user->data->user_plugin;
            } else {
                $query->clear()
                    ->select('customer.*, CONCAT(customer.first_name," ", customer.last_name) AS customer_full_name')
                    ->from($this->getTableName('customer').' AS customer')
                    ->where('customer.id='. (int)$item->customer_id)
                ;
                $customer=$this->db->setQuery($query)->loadObjectList();
                $item->customer=reset($customer);
            }

            $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 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 = $item->type_recurring;
                foreach ($list_rate as &$rate) {
                    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';
                        /////////////////////
                        $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;
                    } 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;

                        $start_recurring = strtotime($rate->date_start_recurring);
                        $end_recurring = strtotime($rate->date_end_recurring);
                        if($type_recurring == 'weekly' || $type_recurring == 'monthly') {
                            if($type_recurring == 'monthly' && $item->all_or_specific == 'specific-day') {
                                $number_day_recurring = count((array)json_decode($item->specific_day));
                            } else {
                                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);
                                }
                            }
                        } elseif($type_recurring == 'daily') {
                            while($start_recurring <= $end_recurring) {
                                $number_day_recurring++;
                                $start_recurring = strtotime("+1 day", $start_recurring);
                            }
                        }
                    }

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


}
