<?php
if (!defined( 'ABSPATH' ) ) {
	exit;
}

use Automattic\WooCommerce\StoreApi\StoreApi;
use Automattic\WooCommerce\StoreApi\Schemas\ExtendSchema;
use Automattic\WooCommerce\StoreApi\Exceptions\RouteException;
require plugin_dir_path( __FILE__ ) . '/class-epaka-extend-checkout-store-endpoint.php';

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       Epaka.pl
 * @since      1.0.0
 *
 * @package    Epaka
 * @subpackage Epaka/admin
 */

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    Epaka
 * @subpackage Epaka/admin
 * @author     Epaka <bok@epaka.pl>
 */


class Epaka_Api {

    /**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
    private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
    private $version;

    private $api_controller;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @param      string    $plugin_name       The name of this plugin.
	 * @param      string    $version    The version of this plugin.
	 */
    public function __construct( $plugin_name, $version ) {
		$this->plugin_name = $plugin_name;
        $this->version = $version;
        $this->api_controller = new Epaka_Api_Controller();
    }
    
    public function  rest_api_routes(){
        $this->defineAdminRoutes();
        $this->definePublicRoutes();
    }

    private function definePublicRoutes(){

        register_rest_route('epaka-public','/map',[
            'methods' => 'POST',
            'callback' => [$this->api_controller,'getMap'],
            'permission_callback' => '__return_true',
        ]);

        register_rest_route('epaka-public','/map',[
            'methods' => 'GET',
            'callback' => [$this->api_controller,'getMap'],
            'permission_callback' => '__return_true',
        ]);

        register_rest_route('epaka-public','/get-points-files-indexes',[
            'methods' => 'GET',
            'callback' => [$this->api_controller,'getPointsFilesIndexes'],
            'permission_callback' => '__return_true',
        ]);

        register_rest_route('epaka-public','/get-nominatim-search',[
            'methods' => 'GET',
            'callback' => [$this->api_controller,'getNominatimSearch'],
            'permission_callback' => '__return_true',
        ]);

        register_rest_route('epaka-public','/get-points-file',[
            'methods' => 'GET',
            'callback' => [$this->api_controller,'getPointsFile'],
            'permission_callback' => '__return_true',
        ]);

        register_rest_route('epaka-public','/get-full-points-data-by-lat-lng-proximity',[
            'methods' => 'POST',
            'callback' => [$this->api_controller,'getFullPointsDataByLatLngProximity'],
            'permission_callback' => '__return_true',
        ]);

        register_rest_route('epaka-public','/get-points-autocomplete',[
            'methods' => 'GET',
            'callback' => [$this->api_controller,'getPointsAutocomplete'],
            'permission_callback' => '__return_true',
        ]);
    } 

    private function defineAdminRoutes(){
        register_rest_route('epaka-admin','/save-profile',[
            'methods' => 'POST',
            'callback' => [$this->api_controller,'saveProfile'],
            'permission_callback' => function () {
                return $_GET['token'] == get_option("epakaAdminToken"); 
            }
        ]);

        register_rest_route('epaka-admin','/set-shipping-courier-mapping',[
            'methods' => 'POST',
            'callback' => [$this->api_controller,'setShippingCourierMapping'],
            'permission_callback' => function () {
                return $_GET['token'] == get_option("epakaAdminToken"); 
            }
        ]);

        register_rest_route('epaka-admin','/get-epaka-order-label',[
            'methods' => 'POST',
            'callback' => [$this->api_controller,'getEpakaOrderLabel'],
            'permission_callback' => function () {
                return $_GET['token'] == get_option("epakaAdminToken"); 
            }
        ]);

        register_rest_route('epaka-admin','/get-epaka-order-protocol',[
            'methods' => 'POST',
            'callback' => [$this->api_controller,'getEpakaOrderProtocol'],
            'permission_callback' => function () {
                return $_GET['token'] == get_option("epakaAdminToken"); 
            }
        ]);
        register_rest_route('epaka-admin','/get-epaka-order-authorization-document',[
            'methods' => 'POST',
            'callback' => [$this->api_controller,'getEpakaOrderAuthorizationDocument'],
            'permission_callback' => function () {
                return $_GET['token'] == get_option("epakaAdminToken"); 
            }
        ]);
        register_rest_route('epaka-admin','/get-epaka-order-proforma',[
            'methods' => 'POST',
            'callback' => [$this->api_controller,'getEpakaOrderProforma'],
            'permission_callback' => function () {
                return $_GET['token'] == get_option("epakaAdminToken"); 
            }
        ]);
        
        register_rest_route('epaka-admin','/unlink-epaka-order-from-woo-order',[
            'methods' => 'POST',
            'callback' => [$this->api_controller,'unlinkEpakaOrderFromWooOrder'],
            'permission_callback' => function () {
                return $_GET['token'] == get_option("epakaAdminToken"); 
            }
        ]);

        register_rest_route('epaka-admin','/link-epaka-order-to-woo-order',[
            'methods' => 'POST',
            'callback' => [$this->api_controller,'linkEpakaOrderToWooOrder'],
            'permission_callback' => function () {
                return $_GET['token'] == get_option("epakaAdminToken"); 
            }
        ]);

        register_rest_route('epaka-admin','/cancel-epaka-order',[
            'methods' => 'POST',
            'callback' => [$this->api_controller,'cancelEpakaOrder'],
            'permission_callback' => function () {
                return $_GET['token'] == get_option("epakaAdminToken"); 
            }
        ]);

        register_rest_route('epaka-admin','/get-epaka-courier-tracking',[
            'methods' => 'POST',
            'callback' => [$this->api_controller,'getEpakaCourierTracking'],
            'permission_callback' => function () {
                return $_GET['token'] == get_option("epakaAdminToken"); 
            }
        ]);

        register_rest_route('epaka-admin','/get-epaka-order-label-zebra',[
            'methods' => 'POST',
            'callback' => [$this->api_controller,'getEpakaOrderLabelZebra'],
            'permission_callback' => function () {
                return $_GET['token'] == get_option("epakaAdminToken"); 
            }
        ]);

        register_rest_route('epaka-admin','/authorize',[
            'methods' => 'POST',
            'callback' => [$this->api_controller,'authorize'],
            'permission_callback' => function () {
                return $_GET['token'] == get_option("epakaAdminToken"); 
            }
        ]);

        register_rest_route('epaka-admin','/get-profile',[
            'methods' => 'GET',
            'callback' => [$this->api_controller,'getProfile'],
            'permission_callback' => function () {
                return $_GET['token'] == get_option("epakaAdminToken"); 
            }
        ]);

        register_rest_route('epaka-admin','/send-order',[
            'methods' => 'POST',
            'callback' => [$this->api_controller,'sendOrder'],
            'permission_callback' => function () {
                return $_GET['token'] == get_option("epakaAdminToken"); 
            }
        ]);

        register_rest_route('epaka-admin','/get-order-iframe',[
            'methods' => 'GET',
            'callback' => [$this->api_controller,'getOrderIframe'],
            'permission_callback' => function () {
                return $_GET['token'] == get_option("epakaAdminToken"); 
            },
            'args' => [
                'context'=>[
                    'default'=>'view'
                ]
            ]
        ]);

//        register_rest_route('epaka-admin','/get-order-template-iframe',[
//            'methods' => 'POST',
//            'callback' => [$this->api_controller,'getOrderTemplateIframe'],
//            'permission_callback' => function () {
//                return $_GET['token'] == get_option("epakaAdminToken");
//            },
//            'args' => [
//                'context'=>[
//                    'default'=>'view'
//                ]
//            ]
//        ]);

        register_rest_route('epaka-admin','/logout',[
            'methods' => 'GET',
            'callback' => [$this->api_controller,'logout'],
            'permission_callback' => function () {
                return $_GET['token'] == get_option("epakaAdminToken"); 
            }
        ]);
    }

    public function extend_checkout_schema(){
        $extend = StoreApi::container()->get( ExtendSchema::class );
        Epaka_Extend_Checkout_Store_Endpoint::init( $extend );
    }

//    public function epaka_wc_prepare_shop_order($response, $object, $request){
//        $order_data = $response->get_data();
//
//        return $response;
//    }

    public function extend_woo_checkout_update_request($order, $request){
        $savedEpakaShippingMapping = json_decode(get_option("epakaShippingCourierMapping"),true);
        $shipping_method = preg_replace("/[^a-zA-Z0-9\']/","", end($order->get_items('shipping'))->get_name());;
        $shipping_zone_id = wc_get_shipping_zone([
           "destination"=>[
               "country"=>$order->get_address()['country'],
               "state"=>$order->get_address()['state'],
               "postcode"=>$order->get_address()['postcode'],
           ]
        ])->get_id();

        if($shipping_zone_id && $shipping_method){
            $shipping_method_mapping = $savedEpakaShippingMapping['Epaka_Shipping_Mapping'][$shipping_zone_id][$shipping_method];
            if(!empty($shipping_method_mapping['map_source_id'])){
                $requestDataExtensions = (array)json_decode($request->get_body())->extensions;
                if(empty($requestDataExtensions['epaka-pl']->epaka_delivery_point) || empty($requestDataExtensions['epaka-pl']->epaka_delivery_point_description)){
                    throw new RouteException( 'woocommerce_rest_checkout_invalid_payment_result', __( 'Musisz wybrać punkt odbioru', 'epaka-pl' ), 500 );
                }
                if(empty($order->get_shipping_phone())){
                    throw new RouteException( 'woocommerce_rest_checkout_invalid_payment_result', __( 'Wybrana opcja wysyłki wymaga podania numeru telefonu', 'epaka-pl' ), 500 );
                }

                $order->add_meta_data('epaka_delivery_point',$requestDataExtensions['epaka-pl']->epaka_delivery_point);
                $order->add_meta_data('epaka_delivery_point_description',$requestDataExtensions['epaka-pl']->epaka_delivery_point_description);
            }
        }
    }
}