<?php

namespace WpBookingProFrontend\app\controllers;

use Twilio\Rest\Client;
use WpBookingPro\Factory;
use WpBookingPro\Filesystem\Support\StringController;
use WpBookingPro\Mvc\Controller\ControllerFrontend;
use WpBookingPro\Mvc\Model\Model;
use WpBookingPro\Utilities\Utility;
use WpBookingProFrontend\app\helpers\ConfigHelper;
use WpBookingProFrontend\app\helpers\EmailHelper;
use WpBookingProFrontend\app\helpers\SmsHelper;

defined('_WPBOOKINGPRO_EXEC') or die;

/**
 * Class BlockController
 */
class CronjobController extends ControllerFrontend
{
    public function action_cron_job_send_sms() {
        $modelOrders = Model::getInstance('orders');
        $list_order = $modelOrders->getList();
        $appConfig = Factory::getAppConfig();
        $timezone = $appConfig->get('timezone','');
        date_default_timezone_set("$timezone");
        $now = date("Y-m-d H:i:s");

        foreach ($list_order as $order) {
            $rate = reset($order->list_rate);
            if($order->is_recurring == '1') {
                if($order->type_recurring == 'daily') {
                    $start_date_daily = strtotime($rate->date_start_recurring.' '.$rate->time_start_recurring);
                    $end_date_daily = strtotime($rate->date_end_recurring.' '.$rate->time_start_recurring);
                    $old_time = isset($order->time_send_sms)?$order->time_send_sms:0;
                    while($start_date_daily <= $end_date_daily) {
                        $start_date_daily_min = strtotime('-20 hours',$start_date_daily);

                        if(strtotime($now) > $start_date_daily_min && strtotime($now) <= $start_date_daily && $order->total > $order->payment_paid) {
                            if($old_time == 0){
                                $diff = abs($start_date_daily - strtotime($rate->date_start_recurring.' '.$rate->time_start_recurring));
                                $years = floor($diff / (365*60*60*24));
                                $months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
                                $days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
                                $day_ordinal = $days + 1;
                            } else {
                                $diff = abs($start_date_daily - $old_time);
                                $years = floor($diff / (365*60*60*24));
                                $months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
                                $days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
                                $day_ordinal = $days + 1;
                            }
                            if ($day_ordinal * $rate->price > $order->payment_paid) {
                                static::send_sms_schedule($order->id,$day_ordinal);
                            }

                            if($old_time < $start_date_daily) {
                                static::update_sms_time_send($order->id,$start_date_daily, $day_ordinal);
                            }
                        }
                        $start_date_daily = strtotime("+1 day", $start_date_daily);
                    }
                }  elseif($order->type_recurring == 'weekly' || $order->type_recurring == 'monthly') {


                    $old_time = isset($order->time_send_sms)?$order->time_send_sms:0;
                    if($order->type_recurring == 'monthly' && $order->specific_day == 'specific-day') {
                        $specific_day = isset($order->specific_day)?$order->specific_day:array();
                        usort($specific_day,array($this,'date_sort'));
                        foreach ($specific_day as $key => $day_recurring_register) {
                            $day_recurring_register_min = strtotime($day_recurring_register.' - 24 hours');
                            if(strtotime($now) > $day_recurring_register_min && strtotime($now) <= strtotime($day_recurring_register) && $order->total > $order->payment_paid) {
                                $day_ordinal = $key + 1;
                                if ($day_ordinal * $rate->price > $order->payment_paid) {
                                    static::send_sms_schedule($order->id,$day_ordinal);
                                }
                                if($old_time < strtotime($day_recurring_register)) {
                                    static::update_sms_time_send($order->id,strtotime($day_recurring_register), $day_ordinal);
                                }
                            }
                        }
                    } else {
                        $result = call_user_func_array("array_merge", $rate->day_recurring_register);
                        usort($result,array($this,'date_sort'));
                        foreach ($result as $key => $day_recurring_register) {
                            $day_recurring_register_min = strtotime($day_recurring_register.' - 24 hours');
                            if(strtotime($now) > $day_recurring_register_min && strtotime($now) <= strtotime($day_recurring_register) && $order->total > $order->payment_paid) {
                                $day_ordinal = $key + 1;
                                if ($day_ordinal * $rate->price > $order->payment_paid) {
                                    static::send_sms_schedule($order->id,$day_ordinal);
                                }
                                if($old_time < strtotime($day_recurring_register)) {
                                    static::update_sms_time_send($order->id,strtotime($day_recurring_register), $day_ordinal);
                                }
                            }
                        }
                    }

                }
            }
        }

    }
    public static function send_sms_schedule($order_id,$day_ordinal) {
        $modelOrder = Model::getInstance('order');
        $order = $modelOrder->getItem($order_id);
        $sms = static::get_sms_info_booking();
        $phone_sms = isset($sms->phone_register)?$sms->phone_register:'';
        $phonecode_sms = isset($sms->phonecode)?$sms->phonecode:'';
        if($phone_sms['0'] == '0') {
            $phone_sms = substr($phone_sms,1);
        }
        $suplier_phone = "+$phonecode_sms$phone_sms";
        $content = $sms->content_sms;
        $modelOrderDetail = Model::getInstance('orderdetail');
        $orderDetail = $modelOrderDetail->getItem(reset($order->list_order_detail)->id);
        $orderDetailRate = reset($order->list_rate);

        $modelService = Model::getInstance('service');
        $service = $modelService->getItem($orderDetail->service_id);

        $modelEmployee = Model::getInstance('employee');
        $employee = $modelEmployee->getItem($orderDetail->employee_id);

        if(is_user_logged_in()) {
            $modelUser = Model::getInstance('user');
            $user = $modelUser->getUserInfo();
            $phone_customer = isset($user->data->user_plugin->mobile)?$user->data->user_plugin->mobile:'';
            $phonecode_customer = isset($user->data->user_plugin->phonecode)?$user->data->user_plugin->phonecode:'';
            if($phone_customer['0'] == '0') {
                $phone_customer = substr($phone_customer, 1);
            }
            $phone_customer_apply = "+$phonecode_customer$phone_customer";
        } else {
            $customer = reset($order->customer);
            $phone_customer = isset($customer->mobile)?$customer->mobile:'';
            $phonecode_customer = isset($customer->phonecode)?$customer->phonecode:'';
            if($phone_customer['0'] == '0') {
                $phone_customer = substr($phone_customer, 1);
            }
            $phone_customer_apply = "+$phonecode_customer$phone_customer";
        }



        foreach ($service as $key => $value) {
            if (is_string($value))
                $content = str_replace("{service_$key}", $value, $content);
        }
        foreach ($order as $key => $value) {
            if (is_string($value))
                $content = str_replace("{order_$key}", $value, $content);
        }
        foreach ($orderDetail as $key => $value) {
            if (is_string($value))
                $content = str_replace("{orderdetail_$key}", $value, $content);
        }
        foreach ($orderDetailRate as $key => $value) {
            if (is_string($value))
                $content = str_replace("{orderdetailrate_$key}", $value, $content);
        }
        if(is_user_logged_in()) {
            $modelUser = Model::getInstance('user');
            $user = $modelUser->getUserInfo();
            foreach ($user->data->user_plugin as $key => $value) {
                if (is_string($value))
                    $content = str_replace("{customer_$key}", $value, $content);
            }
        } else {
            $customer = reset($order->customer);
            foreach ($customer as $key => $value) {
                if (is_string($value))
                    $content = str_replace("{customer_$key}", $value, $content);
            }
        }
        $content = str_replace('{location_i}', reset($order->list_rate)->location_address, $content);
        $content = str_replace('{employee_name}', Utility::get_full_name($employee->first_name, $employee->last_name), $content);
        $content = str_replace('{link_request_payment}', Factory::getRootUrl()."/wpbookingpro/?view=payment-paynow&order_id=".$order->id.'&payment_schedule='.$order->payment_schedule.'&day_ordinal='.$day_ordinal, $content);

        $sid = $sms->account_id;
        $token = $sms->auth_token;
        $client = new Client($sid, $token);

        $client->messages->create(
            $phone_customer_apply,
            [
                'from' => $suplier_phone,
                'body' => $content
            ]
        );
    }
    public static function get_sms_info_booking(){
        $db=Factory::getDBO();
        $query=$db->getQuery(true);
        $send_info_booking=static::get_sms_action_info_booking();
        $query->select('sms.*')
            ->from(Utility::getTableName('sms'). ' AS sms')
            ->where('sms.published=1')
        ;
        $sms = $db->setQuery($query)->loadObject();

        $query->clear()
            ->select("smscontent.*")
            ->from(Utility::getTableName('smscontent'). ' AS smscontent')
            ->where('smscontent.action_sms='.$query->quote($send_info_booking))
        ;
        $sms_content=$db->setQuery($query)->loadObject();
        foreach ($sms_content as $key => $value) {
            if($key != 'id') {
                $sms->{$key} = $value;
            }
        }
        return $sms;

    }
    public static function get_sms_action_info_booking(){
        return "request_payment";
    }
    public static function update_sms_status($order_id) {
        $db=Factory::getDBO();
        $query = $db->getQuery(true);
        $query->update(Utility::getTableName('order'))
            ->set('is_send_sms=1')
            ->where('id='.(int)$order_id)
            ;
        $db->setQuery($query)->execute();
    }
    public static function update_sms_time_send($order_id, $time_stamp, $day_ordinal) {
        $db=Factory::getDBO();
        $query = $db->getQuery(true);
        $query->clear()
            ->update(Utility::getTableName('order'))
            ->set('time_send_sms='.(int)$time_stamp)
            ->set('day_ordinal='.(int)$day_ordinal)
            ->where('id='.(int)$order_id)
        ;
        $db->setQuery($query)->execute();
    }
    function date_sort($a, $b) {
        return strtotime($a) - strtotime($b);
    }

}
