<?php

namespace App\Controllers;



use App\Models\SmaDeliveryTimeModel;
use App\Models\SmaOrderSalesModel;
use App\Validation\SmaDeliveryTimeValidations;
use CodeIgniter\RESTful\ResourceController;
// use CodeIgniter\Database\RawSql;
use DateTime;

class SmaDeliveryTime extends ResourceController
{
    /**
     * Get delivery times.
     * 
     * Given a date return the avaiable delivery times for a selected location.
     *
     * Validation rules and messages are taken from SmaDeliveryTimeValidations file.
     *
     * @filesource App/Validation/SmaDeliveryTimeValidations
     * @return HttpResponse
     */
    public function avaiableDeliveryTime()
    {

        $rules = SmaDeliveryTimeValidations::avaiableDeliveryTimeRules();
        $this->request;
        $message = SmaDeliveryTimeValidations::avaiableDeliveryTimeMessages();
        if (!$this->validate($rules, $message)) {

            // if validation fails

            $response = [
                'status' => 400,
                'error' => true,
                'message' => $this->validator->getErrors(),
                'data' => [],
                'date' => $this->request->getVar('last_sync'),
            ];

            return $this->respondCreated($response);

        } else {
            $this->setModel(new SmaDeliveryTimeModel($this->dbGroupFromRequest()));
            // validate
            $date = $this->request->getVar('date');
            $location = $this->request->getVar('location')??null;
            $day_of_week = $this->getWeekday($date);
            #get max delivery per time param
            $max_delivery = SmaSettings::getSettingsColumnData('delivery_day_max_orders',$this->dbGroupFromRequest());
            
            $orders_model = new SmaOrderSalesModel($this->dbGroupFromRequest());

            $sub_query = $orders_model
                        ->select('sma_order_sales.delivery_time_id')
                        ->join('sma_addresses',"sma_addresses.id=sma_order_sales.address_id AND sma_addresses.location='$location'",'inner')
                        ->where(["sma_order_sales.delivery_day"=>$date])
                        ->groupBy("sma_order_sales.delivery_time_id")
                        ->having("COUNT(sma_order_sales.delivery_time_id)>='$max_delivery'")
                        ->getCompiledSelect();
            /**
             * To get only +30 min late delivery times
             */
            // date_default_timezone_set('Europe/London');
            date_default_timezone_set('America/Bogota');
            $current_date = date('Y-m-d H:i:s', time());
           
            // print_r($day_of_week);
            // echo $this->getDateOnly($date);
            
            
            $deliveryTimes = $this->model->select("*")
            ->where("sma_delivery_time.id NOT IN ($sub_query)")
            ->where("sma_delivery_time.day='$day_of_week'");
            
            if($this->getDateOnly($date)==$this->getDateOnly($current_date)){
                $dateTime = new DateTime($current_date);
                $dateTime->modify('+30 minutes');
                $time = $dateTime->format('H:i:s');
                $deliveryTimes->where(
                    "sma_delivery_time.time_1 > CAST('$time' AS time)"
                );
            }
            $response = [
                'status' => 200,
                'error' => false,
                'message' => 'Exito',
                'server_date_time' => $this->getServerDateTime(),
                'data' => [
                    'avaiable_delivery_times' => $deliveryTimes->get()
                                                               ->getResult(),
                ],
            ];
            return $this->respondCreated($response);
        }
    }

    /**
     * Returns the week day number from a given date
     *
     * @param string $date Date to get weekday num.
     * 
     * @return int
     */
    function getWeekday($date) {
        return date('N', strtotime($date));
    }
    /**
     * Returns only date part from a given date
     *
     * @param string $date Date to get weekday num.
     * 
     * @return int
     */
    function getDateOnly($date) {
        return date('Y-m-d', strtotime($date));
    }
}