<?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 WpBookingPro\Utilities\Utility;
use WpBookingProAdmin\app\helpers\AdminHelper;
use WpBookingProFrontend\app\helpers\FrontendHelper;
use WpBookingProFrontend\app\helpers\SmsHelper;
use WpBookingProFrontend\app\Html\HtmlFrontend;
use Twilio\Rest\Client;

class BookingModel extends ModelForm
{
    /**
     * @var string
     */
    public $context = "booking";
    /**
     * @var string
     */
    public $table_name = "booking";
    public function book_service($data)
    {

        $employee_id = isset($data['employee_id']) ? sanitize_text_field($data['employee_id']) : 0;
        $event_id = isset($data['event_id']) ? sanitize_text_field($data['event_id']) : 0;
        $number_person = isset($data['number_person']) ? sanitize_text_field($data['number_person']) : 1;
        $first_name = isset($data['first_name']) ? sanitize_text_field($data['first_name']) : '';
        $last_name = isset($data['last_name']) ? sanitize_text_field($data['last_name']) : '';
        $email = isset($data['email']) ? sanitize_text_field($data['email']) : '';
        $phonecode = isset($data['phonecode']) ? sanitize_text_field($data['phonecode']) : '';
        $countrycode = isset($data['countrycode']) ? sanitize_text_field($data['countrycode']) : '';
        $phone = isset($data['phone']) ? sanitize_text_field($data['phone']) : '';
        $is_recurring = isset($data['is_recurring']) ? sanitize_text_field($data['is_recurring']) : 0;
        $type_recurring = isset($data['type_recurring']) ? sanitize_text_field($data['type_recurring']) : 0;
        $day_of_week = isset($data['day_of_week']) ? sanitize_text_field($data['day_of_week']) : array();
        $number_week_recurring = isset($data['number_week_recurring']) ? sanitize_text_field($data['number_week_recurring']) : 0;
        $number_month_recurring = isset($data['number_month_recurring']) ? sanitize_text_field($data['number_month_recurring']) : 0;
        $date_start_recurring = isset($data['date_start_recurring']) ? sanitize_text_field($data['date_start_recurring']) : '';
        $time_start_recurring = isset($data['time_start_recurring']) ? sanitize_text_field($data['time_start_recurring']) : '';
        $date_end_recurring = isset($data['date_end_recurring']) ? sanitize_text_field($data['date_end_recurring']) : '';
        $time_end_recurring = isset($data['time_end_recurring']) ? sanitize_text_field($data['time_end_recurring']) : '';
        $comment_addition = isset($data['comment_addition']) ? sanitize_text_field($data['comment_addition']) : '';
        $payment_schedule = isset($data['payment_schedule']) ? sanitize_text_field($data['payment_schedule']) : '';
        $deposit_percent = isset($data['deposit_percent']) ? sanitize_text_field($data['deposit_percent']) : 0;
        $allday_or_specificday = isset($data['allday_or_specificday']) ? sanitize_text_field($data['allday_or_specificday']) : '';
        $day_recurring_in_month = isset($data['day_recurring_in_month']) ? $data['day_recurring_in_month'] : array();
        $coupon_id = isset($data['coupon_id']) ? sanitize_text_field($data['coupon_id']) : 0;
        $modelCoupon = Model::getInstance('coupon');
        $coupon_item = $modelCoupon->getItem($coupon_id);

        if($phone['0'] == '0') {
            $phone = substr($phone, 1);
        }
        $payment_id = isset($data['open_source_payment_id']) ? sanitize_text_field($data['open_source_payment_id']) : '';
        $created_date = Factory::getDate();

        if(!is_user_logged_in()) {
            $customerModel = Model::getInstance('customer');
            $data_customer = [
                "first_name" => $first_name,
                "last_name" => $last_name,
                "phonecode"=>$phonecode,
                "countrycode"=>$countrycode,
                "mobile" => $phone,
                "email" => $email,
                "address_1"=>isset($data['address_1']) ? sanitize_text_field($data['address_1']) : '',
                "address_2"=>isset($data['address_2'])? sanitize_text_field($data['address_2']) : '',
                "city"=>isset($data['city'])?$data['city']:'',

            ];
            $customer = $customerModel->save($data_customer);
            $user_id=0;
        } else {
            $modelUser = Model::getInstance('user');
            $user = $modelUser->getUserInfo();
            $customerModel = Model::getInstance('customer');
            $data_customer = [
                "first_name" => $first_name,
                "last_name" => $last_name,
                "phonecode"=>$phonecode,
                "countrycode"=>$countrycode,
                "mobile" => $phone,
                "email" => $email,
                "address_1"=>isset($data['address_1']) ? sanitize_text_field($data['address_1']) : '',
                "address_2"=>isset($data['address_2']) ? sanitize_text_field($data['address_2']) : '',
                "city"=>isset($data['city']) ? sanitize_text_field($data['city']) : '',
                "user_id"=>$user->data->user_plugin->id,
                "opensource_user_id"=> isset($_SESSION['user_id']) ? sanitize_text_field($_SESSION['user_id']) : ''

            ];
            $customer = $customerModel->save($data_customer);
            $user_id = $user->data->user_plugin->id;
        }




        $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);
        $list_employee = $service->list_employee;
        foreach ($list_employee as $key => $employee_item) {
            if($employee_item->id != $employee_id) {
                unset($list_employee[$key]);
            }
        }

        $paymentModel = Model::getInstance('payment');
        $payment = $paymentModel->getItem($payment_id);
        $start_date = isset($data['calendar']) ? sanitize_text_field($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);
            }
        }
        if($is_recurring) {
            if ($multiply_number == 1) {
                if($event) {
                    $price = $event->price;
                    if($coupon_item) {
                        if($coupon_item->amount > 0) {
                            $total = (int)$number_person * $event->price * $number_day_recurring - $coupon_item->amount;
                        } elseif($coupon_item->percent > 0) {
                            $total = (int)$number_person * $event->price * $number_day_recurring * (1 -  $coupon_item->percent / 100);
                        }
                    } else {
                        $total = (int)$number_person * $event->price * $number_day_recurring;
                    }

                    if($payment_schedule == 'pay-later') {
                        $deposit_payment = $total * $deposit_percent / 100;
                        $balance_payment = $total * (1 - $deposit_percent / 100);
                    } else {
                        $deposit_payment = 0;
                        $balance_payment = 0;
                    }
                } else {
                    $price = $service->price;
                    if($coupon_item) {
                        if($coupon_item->amount > 0) {
                            $total = (int)$number_person * $service->price * $number_day_recurring - $coupon_item->amount;
                        } elseif($coupon_item->percent > 0) {
                            $total = (int)$number_person * $service->price * $number_day_recurring * (1 -  $coupon_item->percent / 100);
                        }
                    } else {
                        $total = (int)$number_person * $service->price * $number_day_recurring;
                    }
                    if($payment_schedule == 'pay-later') {
                        $deposit_payment = $total * $deposit_percent / 100;
                        $balance_payment = $total * (1 - $deposit_percent / 100);
                    } else {
                        $deposit_payment = 0;
                        $balance_payment = 0;
                    }
                }
                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;
                        if($coupon_item) {
                            if($coupon_item->amount > 0) {
                                $total = (int)$number_person * $employee->price * $number_day_recurring - $coupon_item->amount;
                            } elseif($coupon_item->percent > 0) {
                                $total = (int)$number_person * $employee->price * $number_day_recurring * (1 -  $coupon_item->percent / 100);
                            }
                        } else {
                            $total = (int)$number_person * $employee->price * $number_day_recurring;
                        }
                        if($payment_schedule == 'pay-later') {
                            $deposit_payment = $total * $deposit_percent / 100;
                            $balance_payment = $total * (1 - $deposit_percent / 100);
                        } else {
                            $deposit_payment = 0;
                            $balance_payment = 0;
                        }
                    }
                }


            } else {
                if($event) {
                    $price = $event->price;
                    if($coupon_item) {
                        if($coupon_item->amount > 0) {
                            $total = $event->price * $number_day_recurring - $coupon_item->amount;
                        } elseif($coupon_item->percent > 0) {
                            $total = $event->price * $number_day_recurring * (1 -  $coupon_item->percent / 100);
                        }
                    } else {
                        $total = $event->price * $number_day_recurring;
                    }
                    if($payment_schedule == 'pay-later') {
                        $deposit_payment = $total * $deposit_percent / 100;
                        $balance_payment = $total * (1 - $deposit_percent / 100);
                    } else {
                        $deposit_payment = 0;
                        $balance_payment = 0;
                    }
                } else {
                    $price = $service->price;
                    if($coupon_item) {
                        if($coupon_item->amount > 0) {
                            $total = $service->price * $number_day_recurring - $coupon_item->amount;
                        } elseif($coupon_item->percent > 0) {
                            $total = $service->price * $number_day_recurring * (1 -  $coupon_item->percent / 100);
                        }
                    } else {
                        $total = $service->price * $number_day_recurring;
                    }
                    if($payment_schedule == 'pay-later') {
                        $deposit_payment = $total * $deposit_percent / 100;
                        $balance_payment = $total * (1 - $deposit_percent / 100);
                    } else {
                        $deposit_payment = 0;
                        $balance_payment = 0;
                    }
                }
                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;
                        if($coupon_item) {
                            if($coupon_item->amount > 0) {
                                $total = $employee->price * $number_day_recurring - $coupon_item->amount;
                            } elseif($coupon_item->percent > 0) {
                                $total = $employee->price * $number_day_recurring * (1 -  $coupon_item->percent / 100);
                            }
                        } else {
                            $total = $employee->price * $number_day_recurring;
                        }
                        if($payment_schedule == 'pay-later') {
                            $deposit_payment = $total * $deposit_percent / 100;
                            $balance_payment = $total * (1 - $deposit_percent / 100);
                        } else {
                            $deposit_payment = 0;
                            $balance_payment = 0;
                        }
                    }
                }

            }
        } else {
            if ($multiply_number == 1) {
                if($event) {
                    $price = $event->price;
                    if($coupon_item) {
                        if($coupon_item->amount > 0) {
                            $total = (int)$number_person * $event->price - $coupon_item->amount;
                        } elseif($coupon_item->percent > 0) {
                            $total = (int)$number_person * $event->price * (1 -  $coupon_item->percent / 100);
                        }
                    } else {
                        $total = (int)$number_person * $event->price;
                    }

                    $deposit_payment = 0;
                    $balance_payment = 0;
                } else {
                    $price = $service->price;
                    if($coupon_item) {
                        if($coupon_item->amount > 0) {
                            $total = (int)$number_person * $service->price - $coupon_item->amount;
                        } elseif($coupon_item->percent > 0) {
                            $total = (int)$number_person * $service->price * (1 -  $coupon_item->percent / 100);
                        }
                    } else {
                        $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;
                        if($coupon_item) {
                            if($coupon_item->amount > 0) {
                                $total = (int)$number_person * $employee->price - $coupon_item->amount;
                            } elseif($coupon_item->percent > 0) {
                                $total = (int)$number_person * $employee->price * (1 -  $coupon_item->percent / 100);
                            }
                        } else {
                            $total = (int)$number_person * $employee->price;
                        }
                        $deposit_payment = 0;
                        $balance_payment = 0;
                    }
                }

            } else {
                if($event) {
                    $price = $event->price;
                    if($coupon_item) {
                        if($coupon_item->amount > 0) {
                            $total = $event->price - $coupon_item->amount;
                        } elseif($coupon_item->percent > 0) {
                            $total = $event->price * (1 -  $coupon_item->percent / 100);
                        }
                    } else {
                        $total =  $event->price;
                    }
                    $deposit_payment = 0;
                    $balance_payment = 0;
                } else {
                    $price = $service->price;
                    if($coupon_item) {
                        if($coupon_item->amount > 0) {
                            $total = $service->price - $coupon_item->amount;
                        } elseif($coupon_item->percent > 0) {
                            $total = $service->price * (1 -  $coupon_item->percent / 100);
                        }
                    } else {
                        $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;
                        if($coupon_item) {
                            if($coupon_item->amount > 0) {
                                $total = $employee->price - $coupon_item->amount;
                            } elseif($coupon_item->percent > 0) {
                                $total = $employee->price * (1 -  $coupon_item->percent / 100);
                            }
                        } else {
                            $total =  $employee->price;
                        }
                        $deposit_payment = 0;
                        $balance_payment = 0;
                    }
                }

            }
        }

        $orderModel = Model::getInstance('order');
        $data_order = [
            "customer_id" => isset($customer->id)?$customer->id:'',
            "user_id" => $user_id,
            "vendor_id" => $service->user_id,
            "coupon_id" => $coupon_id,
            "open_source_payment_id" => $payment_id,
            "payment_schedule"=> $payment_schedule,
            "deposit_payment"=>$deposit_payment,
            "balance_payment"=>$balance_payment,
            "total" => $total,
            "payment_paid" => 0,
            "type" => $event?AdminHelper::getWpBookingEventKey():AdminHelper::getWpBookingServiceKey(),
            "created_date"=>isset($data['create_date'])? sanitize_text_field($data['create_date']) : $created_date->toSql(),
            "open_source_order_id"=>isset($data['open_source_order_id']) ? sanitize_text_field($data['open_source_order_id']) : '',
            "open_source_order_status_id"=>isset($data['open_source_order_status_id']) ? sanitize_text_field($data['open_source_order_status_id']) : '',
            "is_recurring"=>$is_recurring,
            "type_recurring"=>$type_recurring,
            "number_month_recurring"=>$number_month_recurring,
            "number_week_recurring"=>$number_week_recurring,
            "comment_addition"=>$comment_addition,
            "day_ordinal"=>0,
            "all_or_specific"=>$allday_or_specificday,
            "specific_day"=>json_encode($day_recurring_in_month),
        ];
        $order = $orderModel->save($data_order);
        if($is_recurring) {
            $orderDayRecurringModel = Model::getInstance('orderdayrecurring');
            $dataOrderDayRecurring = [
                "order_id"=>$order->id,
                "monday"=> in_array('monday', $day_of_week)?1:0,
                "tuesday"=>in_array('tuesday', $day_of_week)?1:0,
                "wednesday"=>in_array('wednesday', $day_of_week)?1:0,
                "thursday"=>in_array('thursday', $day_of_week)?1:0,
                "friday"=>in_array('friday', $day_of_week)?1:0,
                "saturday"=>in_array('saturday', $day_of_week)?1:0,
                "sunday"=>in_array('sunday', $day_of_week)?1:0,
            ];
            $orderDayRecurring = $orderDayRecurringModel->save($dataOrderDayRecurring);
        }

        $orderDetailModel = Model::getInstance('orderdetail');
        $data_order_detail = [
            "id" => 0,
            "order_id" => $order->id,
            "quantity" => $quantity,
            "deposit_payment"=>$deposit_payment,
            "balance_payment"=>$balance_payment,
            "total" => $total,
            "payment_paid" => 0,
            "employee_id" => $employee_id,
            "service_id" => $service_id,
            "location_id" => $event?$event->location_id:$service->location_id,
            "price" => $price
        ];
        $oder_detail = $orderDetailModel->save($data_order_detail);
        $orderDetailRateModel = Model::getInstance('orderdetailrate');
        $data_order_detail_rate = [
            "id" => 0,
            "order_detail_id" => $oder_detail->id,
            "start_date" => $start_date,
            "end_date" => $end_date,
            "employee_id" => $employee_id,
            "service_id" => $service_id,
            "location_id" => $event?$event->location_id:$service->location_id,
            "total" => $total,
            "price" => $price,
            "deposit_payment"=>$deposit_payment,
            "balance_payment"=>$balance_payment,
            "subtotal" => $total,
            "payment_paid" => 0,
            "quantity" => $quantity,
            "date_start_recurring"=>$date_start_recurring,
            "time_start_recurring"=>$time_start_recurring,
            "date_end_recurring"=>$date_end_recurring,
            "time_end_recurring"=>$time_end_recurring,
        ];
        $order_detail_rate = $orderDetailRateModel->save($data_order_detail_rate);
        return $order;
    }
    public function add_google_calendar($oder_id){

        $client = self::getClient($oder_id);
        $service = new \Google_Service_Calendar($client);
        $modelOrder = Model::getInstance('order');
        $order = $modelOrder->getItem($oder_id);
        $appConfig = Factory::getAppConfig();
        $timezone = $appConfig->get('timezone','');
        $rate = isset($order->list_rate)?reset($order->list_rate):array();
        $customer = isset($order->customer)?reset($order->customer):array();
        if($order->is_recurring == 0) {
            $start = new \DateTime($rate->start_date, new \DateTimeZone($timezone));
            $end = new \DateTime($rate->end_date, new \DateTimeZone($timezone));
            $recurrence = array('RRULE:FREQ=DAILY;COUNT=1');
        } else {
            $start = new \DateTime($rate->date_start_recurring.' '.$rate->time_start_recurring, new \DateTimeZone($timezone));
            $end = new \DateTime($rate->date_start_recurring.' '.$rate->time_end_recurring, new \DateTimeZone($timezone));
            if($order->type_recurring === 'daily') {
                $recurrence = array('RRULE:FREQ=DAILY;COUNT='.$order->number_day_recurring);
            } elseif ($order->type_recurring === 'weekly') {
                $order_day_recurring = isset($order->order_day_recurring)?$order->order_day_recurring:array();
                $byday = implode(',', array_map(
                    function ($v) {
                        return strtoupper(substr($v,0,2));
                    },$order_day_recurring
                ));
                $recurrence = array('RRULE:FREQ=WEEKLY;COUNT='.$order->number_day_recurring.';BYDAY='.$byday);
            }elseif ($order->type_recurring === 'monthly') {
                $order_day_recurring = isset($order->order_day_recurring)?$order->order_day_recurring:array();
                $byday = implode(',', array_map(
                    function ($v) {
                        return strtoupper(substr($v,0,2));
                    },$order_day_recurring
                ));
                if($order->all_or_specific == 'specific-day') {
                    $day_register = FrontendHelper::getDateOfWeekDayInMonth($rate->date_start_recurring,$rate->date_end_recurring, $order->order_day_recurring);
                    $day_register = call_user_func_array("array_merge", $day_register);
                    $specific_day = isset($order->specific_day)?json_decode($order->specific_day):array();
                    $ex_date = array_diff($day_register,$specific_day);
                    
                    foreach ($ex_date as &$ex_date_item) {
                        $ex_date_item = str_replace('-','',$ex_date_item).'T'.str_replace(':','',$rate->time_start_recurring);
                    }
                    $recurrence = array(
                        'EXDATE;TZID='.$timezone.':'.implode(',',$ex_date),
                        'RRULE:FREQ=WEEKLY;UNTIL='.str_replace('-','',$rate->date_end_recurring).'T'.str_replace(':','',$rate->time_end_recurring).'Z'.';BYDAY='.$byday,
                    );
                } else {
                    $recurrence = array('RRULE:FREQ=WEEKLY;COUNT='.$order->number_day_recurring.';BYDAY='.$byday);
                }

            }
        }

        $expert = $rate->employee_fullname;
        $duration = $rate->duration;
        $description = $rate->service_description;

        $event = new \Google_Service_Calendar_Event(array(
            'summary' => $rate->service_name.' '.$oder_id,
            'location' => $rate->location_address,
            'description' =>"'Expert': $expert \n'Duration': $duration \n'Description': $description",
            'start' => array(
                'dateTime' => $start->format('c'),
                'timeZone' => $timezone
            ),
            'end' => array(
                'dateTime' => $end->format('c'),
                'timeZone' => $timezone
            ),
            'recurrence' => $recurrence,
            'attendees' => array(
                array('email' => $customer->email),
            ),
            'reminders' => array(
                'useDefault' => false,
                'overrides' => array(
                    array('method' => 'email', 'minutes' => 24 * 60),
                    array('method' => 'popup', 'minutes' => 10),
                ),
            ),
        ));
        $calendarId = 'primary';
        $event = $service->events->insert($calendarId, $event);


    }

    function getClient($oder_id)
    {

        $client = new \Google_Client();
        $client->setScopes(\Google_Service_Calendar::CALENDAR);

        $appConfig = Factory::getAppConfig();
        $file_client_secret = $appConfig->get('client_secret_file','');
        if(isset($file_client_secret) && trim($file_client_secret) !== '' && file_exists(WPBOOKINGPRO_PATH_ROOT.DS.$file_client_secret)) {
            $client->setAuthConfig(WPBOOKINGPRO_PATH_ROOT.DS.$file_client_secret);
        } else {
            throw new \Exception("error");
        }

        if(isset($_SESSION['access_token']) && is_array($_SESSION['access_token'])){
            //save event
            $client->setAccessToken($_SESSION['access_token']);

        }else{
            $auth=$client->createAuthUrl();
            $_SESSION['current_oder_id']=$oder_id;
            header("location:$auth");
            die;
        }
        return $client;
    }

    public function send_sms_after_booking($order_id) {
        $modelOrder = Model::getInstance('order');
        $order = $modelOrder->getItem($order_id);
        $sms = SmsHelper::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 function send_sms_notify_employee($order_id) {
        $modelOrder = Model::getInstance('order');
        $order = $modelOrder->getItem($order_id);
        $sms = SmsHelper::get_sms_info_booking('employee_notify');
        $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);


        $phone_employee = isset($employee->mobile)?$employee->mobile:'';
        $phonecode_employee = isset($employee->phonecode)?$employee->phonecode:'';
        if($phone_employee['0'] == '0') {
            $phone_employee = substr($phone_employee, 1);
        }
        $phone_employee_apply = "+$phonecode_employee$phone_employee";



        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_employee_apply,
            [
                'from' => $suplier_phone,
                'body' => $content
            ]
        );
    }


}
