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

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\EmailHelper;
use WpBookingHotelFrontend\app\helpers\SmsHelper;

class BookingModel extends ModelForm
{
    /**
     * @var string
     */
    public $context = "booking";
    /**
     * @var string
     */
    public $table_name = "booking";
    public function book_hotel($data)
    {
        $first_name = isset($data['first_name'])?$data['first_name']:'';
        $last_name = isset($data['last_name'])?$data['last_name']:'';
        $email = isset($data['email'])?$data['email']:'';
        $phone = isset($data['phone'])?$data['phone']:'';
        $city = isset($data['city'])?$data['city']:'';
        $post_code = isset($data['post_code'])?$data['post_code']:'';
        $address = isset($data['address'])?$data['address']:'';
        $country_id = isset($data['country_id'])?$data['country_id']:'';
        $company = isset($data['company'])?$data['company']:'';
        $payment_id = isset($data['payment_id'])?$data['payment_id']:0;
        $check_in = isset($data['check_in'])?$data['check_in']:'';
        $check_out = isset($data['check_out'])?$data['check_out']:'';
        $number_adult = isset($data['number_adult'])?$data['number_adult']:0;
        $number_child = isset($data['number_child'])?$data['number_child']:0;
        $hotel_id = isset($data['hotel_id'])?$data['hotel_id']:0;
        $roomtype_id = isset($data['roomtype_id'])?$data['roomtype_id']:0;
        $nights = isset($data['nights'])?$data['nights']:0;
        $phone_code = isset($data['phonecode'])?$data['phonecode']:0;
        $country_code= isset($data['countrycode'])?$data['countrycode']:'';
        $created_date = Factory::getDate();

        $customerModel = Model::getInstance('customer');
        $data_customer = [
            "first_name" => $first_name,
            "last_name" => $last_name,
            "phone" => $phone,
            "email" => $email,
            "city" =>$city,
            "post_code"=>$post_code,
            "address"=>$address,
            "country_id"=>$country_id,
            "company"=>$company,
            "phonecode"=>$phone_code,
            "countrycode"=>$country_code,
            "created_date"=>$created_date->toSql()
        ];
        $customer = $customerModel->save($data_customer);

        $list_service_id = isset($data['service_id'])?$data['service_id']:array();
        $arr_price_service = array();
        $price_service_total = 0;
        foreach ($list_service_id as $service_id) {
            $serviceModel = Model::getInstance('service');
            $service = $serviceModel->getItem($service_id);
            array_push($arr_price_service,$service->price_service);
            $price_service_total += $service->price_service;
        }
        $roomtypeModel = Model::getInstance('roomtype');
        $roomtype = $roomtypeModel->getItem($roomtype_id);
        $total = $number_child * $roomtype->price_child + $number_adult * $roomtype->price_adult + $price_service_total;


        $orderModel = Model::getInstance('order');
        $data_order = [
            "customer_id" => $customer->id,
            "payment_id" => $payment_id,
            "total" => $total,
            "type" => 'hotel',
            "created_date"=>$created_date->toSql()
        ];
        $order = $orderModel->save($data_order);
        $orderDetailModel = Model::getInstance('orderdetail');
        $data_order_detail = [
            "id" => 0,
            "order_id" => $order->id,
            "total" => $total,
            "service_id" => json_encode($list_service_id),
            "roomtype_id"=> $roomtype_id,
            "hotel_id"=> $hotel_id,
            "number_adult"=>$number_adult,
            "number_child"=> $number_child
        ];
        $oder_detail = $orderDetailModel->save($data_order_detail);
        $orderDetailRateModel = Model::getInstance('orderdetailrate');
        $data_order_detail_rate = [
            "id" => 0,
            "order_detail_id" => $oder_detail->id,
            "check_in" => $check_in,
            "check_out" => $check_out,
            "service_id" => json_encode($list_service_id),
            "hotel_id" => $hotel_id,
            "roomtype_id" => $roomtype_id,
            "total" => $total,
            "price_adult" => $roomtype->price_adult,
            "price_child" => $roomtype->price_child,
            "price_service" => json_encode($arr_price_service),
            "subtotal" => $total,
            "number_adult" => $number_adult,
            "number_child" => $number_child,
            "nights"=>$nights
        ];
        $hotel_id = $data['hotel_id'];

        $hotel_Model = Model::getInstance('hotels');
        $hotel = $hotel_Model->getItem($hotel_id);

        $order_detail_rate = $orderDetailRateModel->save($data_order_detail_rate);
        $emailinfor= EmailHelper::get_email_info_hotel();
        $mail= EmailHelper::connect_mail_SMTP();
        $content=$emailinfor->content;
        foreach ($customer as $key => $value) {
            if (is_string($value))
                $content = str_replace("{customer_$key}", $value, $content);
        }

        $mail->IsHTML(true);
        $mail->AddAddress($customer->email, $customer->email);
        $mail->SetFrom($mail->Username, $emailinfor->name);
        $mail->AddReplyTo($emailinfor->Username, $emailinfor->Username);
        $mail->Subject = $emailinfor->subject;
        $content1 = $content;
        $mail->AltBody = $content;
        $mail->MsgHTML($content1);
        $mail->Send();
        return $order;

    }
    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);
        $modelOrderDetailRate = Model::getInstance('orderdetailrate');

        $list_rate = isset($order->list_rate)?$order->list_rate:array();
        $orderDetailRate = $modelOrderDetailRate->getItem(reset($list_rate)->id);

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


        $modelHotel = Model::getInstance('hotel');
        $hotel = $modelHotel->getItem($orderDetail->hotel_id);

        $list_service = $hotel->list_service;
        foreach ($list_service as $key => $item){
            if(!in_array($item->id,$array_service_id)){
                unset($list_service[$key]);
            }
        }
        $name_service = implode(', ', array_map(
            function ($v){
                return $v->name;
            },$list_service));

        $modelRoomtype = Model::getInstance('roomtype');
        $roomtype = $modelRoomtype->getItem($orderDetail->roomtype_id);



        $list_amenity = $roomtype->list_amenity;
        $name_amenity = implode(', ', array_map(
            function ($v){
                return $v->name;
            },$list_amenity));

        $customer = reset($order->customer);
        $phone_customer = isset($customer->phone)?$customer->phone:'';
        $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 ($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 ($orderDetailRate as $key => $value) {
            if (is_string($value))
                $content = str_replace("{orderdetailrate_$key}", $value, $content);
        }
        foreach ($customer as $key => $value) {
            if (is_string($value))
                $content = str_replace("{customer_$key}", $value, $content);
        }
        $content = str_replace('{location_i}',$hotel->destination->address  , $content);
        $content = str_replace('{service_i}',$name_service  , $content);
        $content = str_replace('{room_type_i}',$roomtype->name  , $content);
        $content = str_replace('{amenities_i}',$name_amenity , $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
            ]
        );
    }

}
