<?php

namespace WpBookingProFrontend\app\controllers;

use WpBookingPro\Factory;
use WpBookingPro\Filesystem\Support\StringController;
use WpBookingPro\Mvc\Controller\ControllerFrontend;
use WpBookingPro\Mvc\Model\Model;
use WpBookingPro\Utilities\Utility;
use WpBookingPro\Wordpress\ECommerce\ECommerce;
use WpBookingProFrontend\app\helpers\ConfigHelper as ConfigHelperAlias;
use WpBookingProFrontend\app\helpers\EmailHelper;
use WpBookingProFrontend\app\helpers\FrontendHelper;

defined('_WPBOOKINGPRO_EXEC') or die;

/**
 * Class BlockController
 */
class BookingController extends ControllerFrontend
{

    function create_woocommoerce_order() {
        $input=Factory::getInput();
        $data=$input->getData();
        $order_id=$data['order_id'];
        $modelOrder=Model::getInstance('order');
        $order=$modelOrder->getItem($order_id);
        $rate = isset($order->list_rate)?reset($order->list_rate):array();
        $modelService = Model::getInstance('service');
        $service = $modelService->getItem($order->list_order_detail[0]->service_id);

        $user_id = $data['user_id'];
        $payment_method = isset($order->open_source_payment_id)?$order->open_source_payment_id:'';
        $wc_order=wc_create_order();
        if(is_user_logged_in()) {
            $modelUser = Model::getInstance('user');
            $user=$modelUser->getUserInfo();
            $customer = $user->data->user_plugin;
            $mobile = isset($customer->mobile)?$customer->mobile:'';
            $phonecode = isset($customer->phonecode)?$customer->phonecode:'';
            if($mobile['0'] == '0') {
                $mobile = substr($mobile, 1);
            }
            $phone_customer = "+$phonecode$mobile";
            $address = array(
                'first_name' => $customer->first_name,
                'last_name'  => $customer->last_name,
                'email'      => $customer->email,
                'phone'      => $phone_customer,
                'address_1'  => $customer->address,
                'address_2'  => $customer->address_bill,
                'city'       => $customer->city,
            );
        } else {
            $customer=$order->customer[0];
            $mobile = isset($customer->mobile)?$customer->mobile:'';
            $phonecode = isset($customer->phonecode)?$customer->phonecode:'';
            if($mobile['0'] == '0') {
                $mobile = substr($mobile, 1);
            }
            $phone_customer = "+$phonecode$mobile";
            $address = array(
                'first_name' => $customer->first_name,
                'last_name'  => $customer->last_name,
                'email'      => $customer->email,
                'phone'      => $phone_customer,
                'address_1'  => $customer->address_1,
                'address_2'  => $customer->address_2,
                'city'       => $customer->city,
            );
        }

        $open_source_product_id = $service->open_source_link_id;
        if($order->payment_schedule === 'pay-later') {
            if($order->day_ordinal == 0) {
                $subtotal=$order->deposit_payment;
                $total=$order->deposit_payment;
            } else {
                $subtotal= $order->day_ordinal * $rate->price - $rate->payment_paid;
                $total= $order->day_ordinal * $rate->price - $rate->payment_paid;
            }
        } else {
            $subtotal=$order->total;
            $total=$order->total;
        }


        $wc_order->add_product( get_product($open_source_product_id),$order->quantity,[
            'subtotal'     => $subtotal, // e.g. 32.95
            'total'        => $total, // e.g. 32.95
        ]);


        $wc_order->set_address( $address, 'billing' );
        $wc_order->set_customer_id((int)$user_id);
        $wc_order->set_payment_method( \WC()->payment_gateways->payment_gateways()[$payment_method] );
        $wc_order->calculate_totals();
        $wc_order->update_status("on-hold");
        $wc_order->update_meta_data( '_expert', reset($order->list_rate)->employee_fullname );
        $wc_order->save();
        $order->open_source_order_id=$wc_order->id;
        $order->open_source_order_status_id='on-hold';
        $modelOrder->save((array)$order);

    }

    /**
     *  Change order status when scan QR code
     */
    function active_order() {
        $input=Factory::getInput();
        $data=$input->getData();
        $order_id=$data['order_id'];
        $eCommerce = ECommerce::getInstance();
        $eCommerce->change_order_status_when_scan_qr_code((int)$order_id);
        Utility::call_ajax_by_task("booking.update_order_woocommerce",array('order_id'=>$order_id));
        //TODO: Create page success when scan
        echo "Success";
        die;
    }

    function update_order_woocommerce() {
        $input=Factory::getInput();
        $data=$input->getData();
        $order_id=$data['order_id'];
        $appConfig = Factory::getAppConfig();
        $order_status_config_when_scan = $appConfig->get('order_status_config_when_scan', '');
        $order = wc_get_order( $order_id );
        $order->update_status($order_status_config_when_scan);
    }


    public function book_service()
    {
        $appConfig = Factory::getAppConfig();
        $booking_style = $appConfig->get('booking_style', 'in_line');
        $client_secret_file = $appConfig->get('client_secret_file','');
        $is_enable_send_sms = $appConfig->get('is_enable_send_sms','');
        $is_enable_send_sms_employee = $appConfig->get('is_enable_send_sms_employee','');
        $is_enable_add_google_calendar_api = $appConfig->get('is_enable_add_google_calendar_api','');
        include_once(ABSPATH . 'wp-includes/pluggable.php');
        $input = Factory::getInput();
        $data = $input->getData();
        if($booking_style == "in_line") {
            $current_user = wp_get_current_user();
            $modelBooking = Model::getInstance('booking');
            $order = $modelBooking->book_service($data);
            if ( class_exists( 'WooCommerce' ) ) {
                $data_post=array(
                    "order_id"=>$order->id,
                    "user_id"=>$current_user->ID
                );
                Utility::call_ajax_by_task("booking.create_woocommoerce_order",$data_post);
            }
            if($is_enable_send_sms == 1) {
                $modelBooking->send_sms_after_booking($order->id);
                if($is_enable_send_sms_employee == 1) {
                    $modelBooking->send_sms_notify_employee($order->id);
                }
            }
            if($is_enable_add_google_calendar_api == 1) {
                if($client_secret_file !== '' && file_exists(WPBOOKINGPRO_PATH_ROOT.DS.$client_secret_file)) {
                    $modelBooking->add_google_calendar($order->id);
                }
            }
            Utility::redirect(Utility::getFrontendGoToLink("payment.paynow", array("order_id" => $order->id)));
        } else {
            add_action('init', array($this,'customcart'));
        }
    }
    public static function customcart() {
        global $woocommerce;
        $input = Factory::getInput();
        $data = $input->getData();
        $quantity = isset($data['number_person'])?$data['number_person']:1;
        $product_id = isset($data['product_id'])?$data['product_id']:0;

        if ( $product_id ){
            $woocommerce->cart->add_to_cart( $product_id, $quantity ,$variation_id = 0, $variation = array(), $cart_item_data = $data );
            exit( wp_redirect( get_permalink( woocommerce_get_page_id( 'cart' ) ) ) );

        }

    }


    function verify_google_calendar(){
        $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");
        }
        $modelBooking = Model::getInstance('booking');
        $input=Factory::getInput();
       $code=$input->getString('code','');

       if(trim($code)!=""){
           $client->authenticate($code);
           $_SESSION['access_token'] = $client->getAccessToken();
       }
       if(isset($_SESSION['current_oder_id']) && $_SESSION['current_oder_id']!=="")
       {
           $order_id=(int)$_SESSION['current_oder_id'];
           $modelBooking->add_google_calendar($order_id);

           Utility::redirect(Utility::getFrontendGoToLink("payment.paynow", array("order_id" => $order_id)));
           die;

       }else{
           throw new \Exception("error");
       }
    }
}
