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

use Twilio\Rest\Client;
use WpBookingPro\Factory;
use WpBookingPro\Mvc\Model\ModelForm;
use WpBookingPro\Filesystem\File as FileAlias;
use WpBookingPro\Mvc\Model\Model;
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 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('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 = 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;
                    $rate->day_recurring_register = array();
                } 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);
                            }
                        }
                        $rate->day_recurring_register = AdminHelper::getDateOfWeekDayInMonth($rate->date_start_recurring,$rate->date_end_recurring, $item->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;
            $item->number_day_recurring = $number_day_recurring;
        }
        $item->list_rate = $list_rate;

        return $item;
    }
    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;
    }

    public function editOrderbyOrderId($data = array()) {
        $order_id = isset($data['order_id'])?$data['order_id']:0;
        $order_detail_id = isset($data['order_detail_id'])?$data['order_detail_id']:0;
        $employee_id = isset($data['employee_id'])?$data['employee_id']:0;
        $event_id = isset($data['event_id'])?$data['event_id']:0;
        $is_recurring = isset($data['is_recurring'])?$data['is_recurring']:0;
        $type_recurring = isset($data['type_recurring'])?$data['type_recurring']:0;
        $day_of_week = isset($data['day_of_week'])?$data['day_of_week']:array();
        $number_week_recurring = isset($data['number_week_recurring'])?$data['number_week_recurring']:0;
        $number_month_recurring = isset($data['number_month_recurring'])?$data['number_month_recurring']:0;
        $date_start_recurring = isset($data['date_start_recurring'])?$data['date_start_recurring']:'';
        $time_start_recurring = isset($data['time_start_recurring'])?$data['time_start_recurring']:'';
        $date_end_recurring = isset($data['date_end_recurring'])?$data['date_end_recurring']:'';
        $time_end_recurring = isset($data['time_end_recurring'])?$data['time_end_recurring']:'';
        $comment_addition = isset($data['comment_addition'])?$data['comment_addition']:'';
        $allday_or_specificday = isset($data['allday_or_specificday'])?$data['allday_or_specificday']:'';
        $day_recurring_in_month = isset($data['day_recurring_in_month'])?$data['day_recurring_in_month']:array();
        $event=array();
        if($event_id > 0) {
            $eventModel = Model::getInstance('event');
            $event = $eventModel->getItem($event_id);
        }

        $service_id = $data['service_id'];
        $serviceModel = Model::getInstance('service');
        $service = $serviceModel->getItem($service_id);
        $deposit_percent = isset($service->deposit_percent)?$service->deposit_percent:0;
        $list_employee = isset($service->list_employee)?$service->list_employee:array();
        foreach ($list_employee as $key => $employee_item) {
            if($employee_item->id != $employee_id) {
                unset($list_employee[$key]);
            }
        }
        $number_person = isset($data['number_person'])?$data['number_person']:1;
        $start_date = isset($data['calendar'])?$data['calendar']:'';
        $time_start_not_recurring = explode(' ', $start_date);
        $time_start_not_recurring = end($time_start_not_recurring);
        $newtimestamp = strtotime($start_date.'+'. ($service->duration * 60).' minutes');
        $end_date = date('Y-m-d H:i:s', $newtimestamp);
        $multiply_number = $service->multiply_number;
        $quantity = $number_person;
        $start_recurring = strtotime($date_start_recurring);
        $end_recurring = strtotime($date_end_recurring);
        $number_day_recurring = 0;
        if($type_recurring == 'weekly' || $type_recurring == 'monthly') {
            if($type_recurring == 'monthly' && $allday_or_specificday == 'specific-day') {
                $number_day_recurring = count((array)$day_recurring_in_month);
            } else {
                while($start_recurring <= $end_recurring) {
                    $day = date('l', $start_recurring);
                    if(in_array(strtolower($day),$day_of_week)) {
                        $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);
            }
        }
        $modelOrder = Model::getInstance('order');
        $order = $modelOrder->getItem($order_id);
        $payment_schedule  = $order->payment_schedule;
        $payment_paid  = $order->payment_paid;
        if($is_recurring) {
            if ($multiply_number == 1) {
                if($event) {
                    $price = $event->price;
                    $total = (int)$number_person * $event->price * $number_day_recurring;
                    $deposit_payment = 0;
                    $balance_payment = 0;
                    if($payment_schedule == 'pay-later') {
                        $deposit_payment = $total * $deposit_percent / 100;
                        $balance_payment = $total - $payment_paid;
                    }
                } else {
                    $price = $service->price;
                    $total = (int)$number_person * $service->price * $number_day_recurring;
                    $deposit_payment = 0;
                    $balance_payment = 0;
                    if($payment_schedule == 'pay-later') {
                        $deposit_payment = $total * $deposit_percent / 100;
                        $balance_payment = $total - $payment_paid;
                    }
                }
                foreach ($list_employee as $employee) {
                    if(strtotime($time_start_recurring) >= strtotime($employee->start_time) && strtotime($time_start_recurring) <= strtotime($employee->end_time)) {
                        $price = $employee->price;
                        $total = (int)$number_person * $employee->price * $number_day_recurring;
                        $deposit_payment = 0;
                        $balance_payment = 0;
                        if($payment_schedule == 'pay-later') {
                            $deposit_payment = $total * $deposit_percent / 100;
                            $balance_payment = $total - $payment_paid;
                        }
                    }
                }


            } else {
                if($event) {
                    $price = $event->price;
                    $total = $event->price * $number_day_recurring;
                    $deposit_payment = 0;
                    $balance_payment = 0;
                    if($payment_schedule == 'pay-later') {
                        $deposit_payment = $total * $deposit_percent / 100;
                        $balance_payment = $total - $payment_paid;
                    }
                } else {
                    $price = $service->price;
                    $total = $service->price * $number_day_recurring;
                    $deposit_payment = 0;
                    $balance_payment = 0;
                    if($payment_schedule == 'pay-later') {
                        $deposit_payment = $total * $deposit_percent / 100;
                        $balance_payment = $total - $payment_paid;
                    }
                }
                foreach ($list_employee as $employee) {
                    if(strtotime($time_start_recurring) >= strtotime($employee->start_time) && strtotime($time_start_recurring) <= strtotime($employee->end_time)) {
                        $price = $employee->price;
                        $total = $employee->price * $number_day_recurring;
                        $deposit_payment = 0;
                        $balance_payment = 0;
                        if($payment_schedule == 'pay-later') {
                            $deposit_payment = $total * $deposit_percent / 100;
                            $balance_payment = $total - $payment_paid;
                        }
                    }
                }

            }
        } else {
            if ($multiply_number == 1) {
                if($event) {
                    $price = $event->price;
                    $total = (int)$number_person * $event->price;
                    $deposit_payment = 0;
                    $balance_payment = 0;
                } else {
                    $price = $service->price;
                    $total = (int)$number_person * $service->price ;
                    $deposit_payment = 0;
                    $balance_payment = 0;
                }
                foreach ($list_employee as $employee) {
                    if(strtotime($time_start_not_recurring) >= strtotime($employee->start_time) && strtotime($time_start_not_recurring) <= strtotime($employee->end_time)) {
                        $price = $employee->price;
                        $total = (int)$number_person * $employee->price ;
                        $deposit_payment = 0;
                        $balance_payment = 0;
                    }
                }

            } else {
                if($event) {
                    $price = $event->price;
                    $total = $event->price;
                    $deposit_payment = 0;
                    $balance_payment = 0;
                } else {
                    $price = $service->price;
                    $total = $service->price;
                    $deposit_payment = 0;
                    $balance_payment = 0;
                }
                foreach ($list_employee as $employee) {
                    if(strtotime($time_start_not_recurring) >= strtotime($employee->start_time) && strtotime($time_start_not_recurring) <= strtotime($employee->end_time)) {
                        $price = $employee->price;
                        $total = $employee->price;
                        $deposit_payment = 0;
                        $balance_payment = 0;
                    }
                }

            }
        }
        $db = Factory::getDBO();
        $query = $db->getQuery(true);
        $now = Factory::getDate();
        $query->clear()
            ->update($this->getTableName('order'))
            ->set('is_recurring='.(int)$is_recurring)
            ->set('type_recurring='.$query->quote($type_recurring))
            ->set('number_month_recurring='.(int)$number_month_recurring)
            ->set('number_week_recurring='.(int)$number_week_recurring)
            ->set('comment_addition='.$query->quote($comment_addition))
            ->set('total='.$total)
            ->set('modify_date='.$query->quote($now->toSql()))
            ->set('deposit_payment='.(float)$deposit_payment)
            ->set('balance_payment='.(float)$balance_payment)
            ->set('all_or_specific='.$query->quote($allday_or_specificday))
            ->set('specific_day='.$query->quote(json_encode($day_recurring_in_month)))
            ->where('id='.(int)$order_id)
        ;
        $db->setQuery($query)->execute();

        $query->clear()
            ->select('*')
            ->from($this->getTableName('order_day_recurring'))
            ->where('order_id='.(int)$order_id)
        ;
        $order_day_recurring = $db->setQuery($query)->loadObject();
        if(!empty((array)$order_day_recurring) && $is_recurring == 1) {
            $query->clear()
                ->update($this->getTableName('order_day_recurring'))
                ->set('monday='.(in_array('monday', $day_of_week)?1:0))
                ->set('tuesday='.(in_array('tuesday', $day_of_week)?1:0))
                ->set('wednesday='.(in_array('wednesday', $day_of_week)?1:0))
                ->set('thursday='.(in_array('thursday', $day_of_week)?1:0))
                ->set('friday='.(in_array('friday', $day_of_week)?1:0))
                ->set('saturday='.(in_array('saturday', $day_of_week)?1:0))
                ->set('sunday='.(in_array('sunday', $day_of_week)?1:0))
                ->where('order_id='.(int)$order_id)
            ;
            $db->setQuery($query)->execute();
        } elseif(empty((array)$order_day_recurring) && $is_recurring == 1) {
            $query->clear()
                ->insert($this->getTableName('order_day_recurring'))
                ->set('monday='.(in_array('monday', $day_of_week)?1:0))
                ->set('tuesday='.(in_array('tuesday', $day_of_week)?1:0))
                ->set('wednesday='.(in_array('wednesday', $day_of_week)?1:0))
                ->set('thursday='.(in_array('thursday', $day_of_week)?1:0))
                ->set('friday='.(in_array('friday', $day_of_week)?1:0))
                ->set('saturday='.(in_array('saturday', $day_of_week)?1:0))
                ->set('sunday='.(in_array('sunday', $day_of_week)?1:0))
                ->set('order_id='.(int)$order_id)
            ;
            $db->setQuery($query)->execute();
        }

        $query->clear()
            ->update($this->getTableName('order_detail'))
            ->set('total='.$total)
            ->set('price='.$price)
            ->set('deposit_payment='.(float)$deposit_payment)
            ->set('balance_payment='.(float)$balance_payment)
            ->where('order_id='.(int)$order_id)
        ;
        $db->setQuery($query)->execute();

        $query->clear()
            ->update($this->getTableName('order_detail_rate'))
            ->set('start_date='.$query->quote($start_date))
            ->set('end_date='.$query->quote($end_date))
            ->set('date_start_recurring='.$query->quote($date_start_recurring))
            ->set('time_start_recurring='.$query->quote($time_start_recurring))
            ->set('date_end_recurring='.$query->quote($date_end_recurring))
            ->set('time_end_recurring='.$query->quote($time_end_recurring))
            ->set('total='.$total)
            ->set('price='.$price)
            ->set('subtotal='.$total)
            ->set('deposit_payment='.(float)$deposit_payment)
            ->set('balance_payment='.(float)$balance_payment)
            ->where('order_detail_id='.(int)$order_detail_id)
        ;
        $db->setQuery($query)->execute();
    }
    public function removeOrderbyOrderId($data = array()) {
        $order_id = isset($data['order_id'])?$data['order_id']:0;
        $order_detail_id = isset($data['order_detail_id'])?$data['order_detail_id']:0;
        $is_recurring = isset($data['is_recurring'])?$data['is_recurring']:0;
        $db = Factory::getDBO();
        $query = $db->getQuery(true);
        $query->clear()
            ->delete($this->getTableName('order'))
            ->where('id='.(int)$order_id)
        ;
        $db->setQuery($query)->execute();

        $query->clear()
            ->select('*')
            ->from($this->getTableName('order_day_recurring'))
            ->where('order_id='.(int)$order_id)
        ;
        $order_day_recurring = $db->setQuery($query)->loadObject();
        if(!empty((array)$order_day_recurring) && $is_recurring == 1) {
            $query->clear()
                ->delete($this->getTableName('order_day_recurring'))
                ->where('order_id='.(int)$order_id)
            ;
            $db->setQuery($query)->execute();
        }

        $query->clear()
            ->delete($this->getTableName('order_detail'))
            ->where('order_id='.(int)$order_id)
        ;
        $db->setQuery($query)->execute();

        $query->clear()
            ->delete($this->getTableName('order_detail_rate'))
            ->where('order_detail_id='.(int)$order_detail_id)
        ;
        $db->setQuery($query)->execute();
    }
    public function sendRequestPayment($data = array()) {
        $order_id = isset($data['order_id'])?$data['order_id']:0;
        $modelOrder = Model::getInstance('order');
        $order = $modelOrder->getItem($order_id);
        $rate = isset($order->list_rate)?reset($order->list_rate):array();
        $appConfig = Factory::getAppConfig();
        $timezone = $appConfig->get('timezone','');
        date_default_timezone_set("$timezone");
        $now = date("Y-m-d H:i:s");

        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;
                        }
                        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->clear()
            ->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_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);
    }


}
