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

class OrderModel extends ModelForm
{
    /**
     * @var string
     */
    public $context = "order";
    /**
     * @var string
     */
    public $table_name = "order";
    public function getItem($id = 0)
    {
        $item = (object)parent::getItem($id); // TODO: Change the autogenerated stub

        $query = $this->db->getQuery(true);
        $query->clear()
            ->select('name')
            ->from($this->getTableName('order_status'))
            ->where('open_source_order_status_id='.$query->quote($item->open_source_order_status_id) )
        ;
        $item->status_payment = $this->db->setQuery($query)->loadResult();
        $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)$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 = 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;
                } 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);
                    $specific_day = isset($item->specific_day)?json_decode($item->specific_day):array();
                    if($type_recurring == 'weekly' || $type_recurring == 'monthly') {
                        if($type_recurring == 'monthly' && $item->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),$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 = $list_rate;
            $item->number_day_recurring = $number_day_recurring;
        }
        $item->list_rate = $list_rate;

        $query->clear()
            ->select('*')
            ->from($this->getTableName('coupon'))
            ->where('id='.(int)$item->coupon_id)
        ;
        $coupon = $this->_db->setQuery($query)->loadObject();
        if($coupon) {
            $item->coupon = $coupon;
        }

        return $item;
    }
    public function updateOrderAfterPaymentSuccess($data = array()) {

        $order_id = isset($data['order_id']) ? sanitize_text_field($data['order_id']) : '';
        $payment_schedule = isset($data['payment_schedule']) ? sanitize_text_field($data['payment_schedule']) : '';
        $day_ordinal = isset($data['day_ordinal']) ? sanitize_text_field($data['day_ordinal']) : '';
        $payment_paid_partial = isset($data['payment_paid_partial']) ? sanitize_text_field($data['payment_paid_partial']) : '';
        $payment_paid = isset($data['payment_paid']) ? sanitize_text_field($data['payment_paid']) : '';
        $balance_payment = isset($data['balance_payment'])?$data['balance_payment']:'';

        $db = Factory::getDBO();
        $query = $db->getQuery(true);
        $modelOrder = Model::getInstance('order');
        $order = $modelOrder->getItem($order_id);
        $rate = isset($order->list_rate)?reset($order->list_rate):array();
        if($order->payment_schedule == 'pay-later' && $order->total - $order->payment_paid > 0) {
            if($day_ordinal == 0) {
                $query->clear()
                    ->update($this->getTableName('order').' AS wborder')
                    ->set('wborder.order_status_alias='.$query->quote('ready-in-use'))
                    ->set('wborder.open_source_order_status_id='.$query->quote('processing'))
                    ->set('wborder.payment_paid='.((float)$payment_paid_partial))
                    ->where('wborder.id='.(int)$order_id)
                ;
                $db->setQuery($query)->execute();
                $query->clear()
                    ->update($this->getTableName('order_detail').' AS order_detail')
                    ->set('order_detail.payment_paid='.((float)$payment_paid_partial))
                    ->where('order_detail.order_id='.(int)$order_id)
                ;
                $db->setQuery($query)->execute();

                $query->clear()
                    ->update($this->getTableName('order_detail_rate').' AS order_detail_rate')
                    ->set('order_detail_rate.payment_paid='.((float)$payment_paid_partial))
                    ->where('order_detail_rate.id='.(int)$rate->id)
                ;
                $db->setQuery($query)->execute();
            } else {
                $query->clear()
                    ->update($this->getTableName('order').' AS wborder')
                    ->set('wborder.order_status_alias='.$query->quote('ready-in-use'))
                    ->set('wborder.open_source_order_status_id='.$query->quote('processing'))
                    ->set('wborder.payment_paid='.((float)$payment_paid + (float)$payment_paid_partial))
                    ->set('wborder.balance_payment='.((float)$balance_payment - (float)$payment_paid_partial))
                    ->where('wborder.id='.(int)$order_id)
                ;
                $db->setQuery($query)->execute();
                $query->clear()
                    ->update($this->getTableName('order_detail').' AS order_detail')
                    ->set('order_detail.payment_paid='.((float)$payment_paid + (float)$payment_paid_partial))
                    ->set('order_detail.balance_payment='.((float)$balance_payment - (float)$payment_paid_partial))
                    ->where('order_detail.order_id='.(int)$order_id)
                ;
                $db->setQuery($query)->execute();

                $query->clear()
                    ->update($this->getTableName('order_detail_rate').' AS order_detail_rate')
                    ->set('order_detail_rate.payment_paid='.((float)$payment_paid + (float)$payment_paid_partial))
                    ->set('order_detail_rate.balance_payment='.((float)$balance_payment - (float)$payment_paid_partial))
                    ->where('order_detail_rate.id='.(int)$rate->id)
                ;
                $db->setQuery($query)->execute();
            }


        } else {
            $query->clear()
                ->update($this->getTableName('order').' AS wborder')
                ->set('wborder.order_status_alias='.$query->quote('completed'))
                ->set('wborder.open_source_order_status_id='.$query->quote('completed'))
                ->set('wborder.payment_paid='.(float)$order->total)
                ->set('wborder.balance_payment= 0')
                ->where('wborder.id='.(int)$order_id)
            ;
            $db->setQuery($query)->execute();
            $query->clear()
                ->update($this->getTableName('order_detail').' AS order_detail')
                ->set('order_detail.payment_paid='.(float)$order->total)
                ->set('order_detail.balance_payment= 0')
                ->where('order_detail.order_id='.(int)$order_id)
            ;
            $db->setQuery($query)->execute();

            $query->clear()
                ->update($this->getTableName('order_detail_rate').' AS order_detail_rate')
                ->set('order_detail.payment_paid='.(float)$order->total)
                ->set('order_detail.balance_payment= 0')
                ->where('order_detail_rate.id='.(int)$rate->id)
            ;
            $db->setQuery($query)->execute();
        }



    }
    public function updateOrderAfterPaymentCancel($data = array()) {
        $order_id = isset($data['order_id'])?$data['order_id']:'';
        $db = Factory::getDBO();
        $query = $db->getQuery(true);
        $query->clear()
            ->update($this->getTableName('order'))
            ->set('open_source_order_status_id='.$query->quote('cancelled'))
            ->set('order_status_alias='.$query->quote('cancelled'))
            ->where('id='.(int)$order_id)
        ;
        $db->setQuery($query)->execute();
    }

    public function change_order_status($data=array())
    {
        $data_order = array(
            "id" => $data['order_id'],
            "open_source_order_status_id" => $data['open_source_order_status_id']
        );
        $order = parent::save($data_order);
        return $order;
    }
}
