<?php
namespace WpBookingHotelFrontend\app\models;
defined('_WPBOOKINGHOTEL_EXEC') or die;

use WpBookingHotelFrontend\app\helpers\EmailHelper;
use WpBookingHotelFrontend\app\helpers\FrontendHelper;
use Twilio\Rest\Client;
use WpBookingHotel\Factory;
use WpBookingHotel\Mvc\Model\Model;
use WpBookingHotel\Mvc\Model\ModelForm;
use WpBookingHotel\Form\Form;
use WpBookingHotel\Mvc\Model\ModelList;
use WpBookingHotel\Registry\Registry;
use WpBookingHotelAdmin\app\helpers\AdminHelper;
use WpBookingHotelFrontend\app\helpers\ConfigHelper;
use WpBookingHotelFrontend\app\helpers\SmsHelper;

class CheckoutModel extends ModelForm
{
    /**
     * @var string
     */
    public $context = "checkout";
    /**
     * @var string
     */
    public $table_name = "cart";
    public function checkout_model($data){
        $now = Factory::getDate();
        $customerModel = Model::getInstance('customer');
        $data_customer = array(
            'first_name' => $data['first_name'],
            'last_name' => $data['last_name'],
            'phonecode' => $data['phonecode'],
            'mobile' => $data['mobile'],
            'email' => $data['email'],
            "address_1"=>$data['address_line1'],
            "address_2"=>$data['address_line2'],
            "countryname"=>$data['country'],
            "city"=>$data['city'],
            'country_code' => $data['country'],
            'note_internal' => $data['description'],
            'created_date' => $now->tosql(),
            'zip_code' => $data['zip_code'],
            'state' => $data['province']
        );
        $customer = $customerModel->save($data_customer);
        $hotel_id = $data['hotel_id'];
        $hotelModel = Model::getInstance('hotel');
        $hotel = $hotelModel->getItem($hotel_id);
        $coupon_id = isset($data['coupon_id'])?$data['coupon_id']:0;
        $couponModel = Model::getInstance('coupon');
        $coupon = $couponModel->getItem($coupon_id);
        $adult = $data['adult'];
        $children = $data['children'];
        $infant = $data['infant'];
        $total = $data['total'];
        $orderModel = Model::getInstance('order');
        $data_order = array(
            "customer_id" => $customer->id,
            "total" => $total,
            "type" => 'hotel'
        );
        $order = $orderModel->save($data_order);
        $orderDetailModel = Model::getInstance('orderdetail');
        $start_date = isset($data['start_date'])?$data['start_date']:'';
        $start_date = Factory::getDate($start_date);
        $data_order_detail = array(
            "order_id" => $order->id,
            "hotel_id" => $hotel_id,
            'coupon_id' =>$coupon_id,
            "adult" => $adult,
            "children" => $children,
            "infant" => $infant,
            "start_date" => $start_date->toSql(),
            "price" => $hotel->price,
            "quantity" => 1,
            "total" => $total
        );
        $orderDetail = $orderDetailModel->save($data_order_detail);
        $modelOrder = Model::getInstance('order');
        $order = $modelOrder->getItem($order->id);
        $modelOrderDetail = Model::getInstance('orderdetail');
        $orderDetail = $modelOrderDetail->getItem(reset($order->list_order_detail)->id);
        $email = EmailHelper::get_email_info_hotel();
        $mail = EmailHelper::connect_mail_SMTP();
        $content = $email->content;
        $list_location = $hotel->destination;
        $list_location_name = [];
        foreach ($list_location as $location) {
            foreach ($location as $key => $value) {
                if ($key == 'name') {
                    array_push($list_location_name, $value);
                }
            }
        }
        foreach ($order->hotel as $key => $value) {
            if ($value)
                $content = str_replace("{hotel_$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 ($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);
        $mail->IsHTML(true);
        $mail->AddAddress($customer->email, $customer->email);
        $mail->SetFrom($mail->Username, $email->name);
        $mail->AddReplyTo($email->Username, $email->Username);
        $mail->Subject = $email->subject;
        $content1 = $content;
        $mail->AltBody = $content;
        $mail->MsgHTML($content1);
        $mail->Send();
        return $order;
    }

    public function send_sms_after_booking($order_id){
        $input = Factory::getInput();
        $data = $input->getData();
        $modelOrder = Model::getInstance('order');
        $order = $modelOrder->getItem($order_id);
        $sms = SmsHelper::get_sms_info_booking();
        $hotel_id = $data['hotel_id'];
        $hotelModel = Model::getInstance('hotel');
        $hotel = $hotelModel->getItem($hotel_id);
        $phone_sms = isset($sms->sms_phone_register)?$sms->sms_phone_register:"";
        $phonecode_sms = isset($sms->sms_phonecode)?$sms->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);
        $customer = reset($order->customer);
        $phone_customer = isset($customer->mobile)?$customer->mobile:"";
        $phonecode_customer = isset($customer->phonecode)?$customer->phonecode:'';
        $phone_customer_apply = "+$phonecode_customer$phone_customer";
        foreach ($hotel as $key => $value) {
            if (is_string($value))
                $content = str_replace("{hotel_$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 ($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);
        $sid = $sms->sms_account_id;
        $token = $sms->sms_auth_token;
        $client = new Client($sid, $token);
        $client->messages->create(
            $phone_customer_apply,
            [
                'from' => $suplier_phone,
                'body' => $content
            ]
        );
    }

    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(WPBOOKINGHOTEL_PATH_ROOT.DS.$file_client_secret)) {
            $client->setAuthConfig(WPBOOKINGHOTEL_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 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();
        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);
                }

            }
        }
        $customer = isset($order->customer)?reset($order->customer):array();
        $list_order_detail = isset($order->list_order_detail)?reset($order->list_order_detail):array();
        $hotel = isset($order->hotel)?$order->hotel:array();
        $event = new \Google_Service_Calendar_Event(array(
            'summary' => "$customer->first_name ". "$customer->last_name".' '.$oder_id,
            'location' => " $customer->address_1 $customer->address_2 $customer->countryname ",
            'description' =>" 'hotel Name': $hotel->name \n 'Mobile':$customer->mobile \n 'Duration': $hotel->duration \n 'adult':$list_order_detail->adult \n 'children':$list_order_detail->children \n 'infant':$list_order_detail->infant \n 'Note by customer': $customer->note_internal ",
            '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);
        return $event;
    }

}
