<?php
namespace TourOperatorProFrontend\app\models;
defined('_TOUROPERATOR_EXEC') or die;

use TourOperatorProFrontend\app\helpers\EmailHelper;
use Twilio\Rest\Client;
use TourOperatorPro\Factory;
use TourOperatorPro\Mvc\Model\Model;
use TourOperatorPro\Mvc\Model\ModelForm;
use TourOperatorPro\Form\Form;
use TourOperatorPro\Mvc\Model\ModelList;
use TourOperatorPro\Registry\Registry;
use TourOperatorProAdmin\app\helpers\AdminHelper;
use TourOperatorProFrontend\app\helpers\ConfigHelper;
use TourOperatorProFrontend\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'],
            "city"=>$data['city'],
            'country_code' => $data['countrycode'],
            'note_internal' => $data['description'],
            'created_date' => $now->tosql(),
            'zip_code' => $data['zip_code'],
            'state' => $data['province']
        );
        $customer = $customerModel->save($data_customer);
        $tour_id = $data['tour_id'];
        $tourModel = Model::getInstance('tour');
        $tour = $tourModel->getItem($tour_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'];
        if ($tour->discount->percent > 0) {
                $new_pr= (float)((100 - $tour->discount->percent)/100);
            }else{
            $new_pr =1;
        }
        $total = $new_pr*((int)$adult * (float)$tour->adult_price
            + (int)$children * (float)$tour->children_price
            + (int)$infant * (float)$tour->infant_price);

        $orderModel = Model::getInstance('order');
        $data_order = array(
            "customer_id" => $customer->id,
            "total" => $total,
            "type" => 'tour'
        );
        $order = $orderModel->save($data_order);

        $orderDetailModel = Model::getInstance('orderdetail');
        $start_date = isset($data['start_date'])?$data['start_date']:'';
        $start_date = Factory::getDate($start_date);
        $new_price = $tour ->price;
        if($tour->discount) {
            if($tour->discount->amount > 0) {
                $new_price = $tour->price - $tour->discount->amount;
            } else if ($tour->discount->percent > 0) {
                $new_price= $tour->price - ($tour->price * $tour->discount->percent) / 100 ;
            }
        }
        $data_order_detail = array(
            "order_id" => $order->id,
            "tour_id" => $tour_id,
            "adult" => $adult,
            "children" => $children,
            "infant" => $infant,
            "start_date" => $start_date->toSql(),
            "price" => $new_price,
//            "price" => $tour->price,
            "quantity" => 1,
            "total" => $total
        );
        $orderDetail = $orderDetailModel->save($data_order_detail);

        $email = EmailHelper::get_email_info_tour();
        $content = $email->content;
        $list_location = $tour->destination;
        $list_location_name = [];
        foreach ($list_location as $location) {
            foreach ($location as $key => $value) {
                if ($key == 'name') {
                    array_push($list_location_name, $value);
                }
            }
        }
        foreach ($tour as $key => $value) {
            if (is_string($value))
                $content = str_replace("{tour_$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);
        /*        if(!mail($customer->email, $email->subject, $content)) {

        }*/
        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();
        $tour_id = $data['tour_id'];
        $tourModel = Model::getInstance('tour');
        $tour = $tourModel->getItem($tour_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 ($tour as $key => $value) {
            if (is_string($value))
                $content = str_replace("{tour_$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
            ]
        );


    }

}
