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

class Epaka_Api_Controller {

    private static $ApiUrl = EPAKA_DOMAIN."api/";

    public function __construct() {

    }

    public static function getInstance(){
        return new Epaka_Api_Controller;
    }

    public static function authorize($email, $password){
        $args = [
            'method' => 'POST',
            'redirection' => 5,
            'sslVerify' => EPAKA_ENABLE_SSL_CHECKS,
            'blocking' => true,
            'body' => [
                'email' => sanitize_email($email),
                'password' => $password
            ]
        ];

        $response = wp_remote_request(Epaka_Api_Controller::$ApiUrl."login.xml", $args);

        if(!is_wp_error($response)) {
            $response = simplexml_load_string($response["body"]);

            if ($response->status == "OK") {
                if (empty(get_option('epakaSession'))) {
                    add_option('epakaSession', $response->session->__toString());
                } else {
                    update_option('epakaSession', $response->session->__toString());
                }
                if (empty(get_option('epakaE')) && empty(get_option('epakaP'))) {
                    add_option('epakaE', $email);
                    add_option('epakaP', $password);
                } else {
                    update_option('epakaE', $email);
                    update_option('epakaP', $password);
                }
                return rest_ensure_response($response);
            } else {
                delete_option('epakaE');
                delete_option('epakaP');
                return rest_ensure_response($response);
            }
        }else{
            return rest_ensure_response($response);
        }
    }

    public function getProfile(){
        return Epaka_Api_Controller::sendRequest("profile.xml");
    }

    public function saveProfile($request){
        if(!Epaka_Api_Controller::isAuthorized()) wp_redirect(admin_url('admin.php?page=epaka_admin_panel_login_page'));
        $profile = $this->getProfile()->data;

        if(empty($profile)) wp_redirect(admin_url('admin.php?page=epaka_admin_panel_login_page'));;

        $profileDataToSave = [
            "name" => $profile->name->__toString(),
            "lastName" => $profile->lastName->__toString(),
            "company" => $profile->company->__toString(),
            "tin" => $profile->tin->__toString(),
            "street" => $profile->street->__toString(),
            "houseNumber" => $profile->houseNumber->__toString(),
            "flatNumber" => $profile->flatNumber->__toString(),
            "postCode" => $profile->postCode->__toString(),
            "city" => $profile->city->__toString(),
            "country" => $profile->country->__toString(),
            "bankAccount" => $profile->bankAccount->__toString(),
            "phone" => $profile->phone->__toString(),
            "senderName" => $profile->senderName->__toString(),
            "senderLastName" => $profile->senderLastName->__toString(),
            "senderCompany" => $profile->senderCompany->__toString(),
            "senderStreet" => $profile->senderStreet->__toString(),
            "senderHouseNumber" => $profile->senderHouseNumber->__toString(),
            "senderFlatNumber" => $profile->senderFlatNumber->__toString(),
            "senderPostCode" => $profile->senderPostCode->__toString(),
            "senderCity" => $profile->senderCity->__toString(),
            "senderCountry" => $profile->senderCountry->__toString(),
            "senderPhone" => $profile->senderPhone->__toString(),
            "invoices" => intval($profile->invoices->__toString()),
            "zebra" => intval($profile->zebra->__toString()),
            "newsletter" => intval($profile->newsletter->__toString()),
            "defaultPaczkomat" => $profile->defaultPaczkomat->__toString(),
            "defaultPaczkomatDescription" => $profile->defaultPaczkomatDescription->__toString(),
            "defaultPunktRuchu" => $profile->defaultPunktRuchu->__toString(),
            "defaultPunktRuchuDescription" => $profile->defaultPunktRuchuDescription->__toString(),
            "defaultPunktPaczka48" => $profile->defaultPunktPaczka48->__toString(),
            "defaultPunktPaczka48Description" => $profile->defaultPaczka48Description->__toString(),
        ];

        foreach($request->get_body_params()['profile'] as $key=>$value){
            $profileDataToSave[$key] = sanitize_text_field($value);
        }

        $response = Epaka_Api_Controller::sendRequest("saveProfile.xml",$profileDataToSave);


        return rest_ensure_response($response);
    }

    public function setShippingCourierMapping(){
        if(is_array($_POST['data']['Epaka_Shipping_Mapping'])){
            foreach($_POST['data']['Epaka_Shipping_Mapping'] as &$mapping){
                if(is_array($mapping)) {
                    foreach ($mapping as &$value) {
                        $value['epaka_courier'] = sanitize_text_field($value['epaka_courier']);
                        $value['map_source_url'] = sanitize_text_field($value['map_source_url']);
                        $value['map_source_name'] = sanitize_text_field($value['map_source_name']);
                        $value['map_source_id'] = sanitize_text_field($value['map_source_id']);
                    }
                }else{
                    return rest_ensure_response(["status" => "Error"]);
                }
            }
        }else{
            return rest_ensure_response(["status" => "Error"]);
        }

        $MapInJsonString = json_encode($_POST['data']);

        if(empty(get_option('epakaShippingCourierMapping'))){
            add_option('epakaShippingCourierMapping',$MapInJsonString);
        }else{
            update_option('epakaShippingCourierMapping',$MapInJsonString);
        }

        return rest_ensure_response(["status" => "OK"]);
    }

    public function getPointsFilesIndexes(){
        $endpoint = '/files/map_points/map.json';
        header('Content-Type: application/json');
        $response = wp_remote_get(str_replace('/api/','',Epaka_Api_Controller::$ApiUrl).$endpoint);
        if(!is_wp_error($response)){
            return rest_ensure_response(json_decode($response['body']));
        }
        return new WP_REST_Response($response, 404);
    }

    public function getPointsFile(){
        $endpoint = "/files/map_points/points." . $_GET['filenameWithSuffixes'] . ".json";
        header('Content-Type: application/json');
        $response = wp_remote_get(str_replace('/api/','',Epaka_Api_Controller::$ApiUrl).$endpoint);
        if(!is_wp_error($response)){
            return rest_ensure_response(json_decode($response['body']));
        }

        return new WP_REST_Response($response, 404);
    }

    public function getNominatimSearch(){
        $endpoint = '/map.php';
        header('Content-Type: application/json');
        $response = wp_remote_get(str_replace('/api/','',Epaka_Api_Controller::$ApiUrl).$endpoint.'?'.http_build_query($_GET));
        if(!is_wp_error($response)){
            return rest_ensure_response(json_decode($response['body']));
        }
        return new WP_REST_Response($response, 404);
    }

    public function getFullPointsDataByLatLngProximity($data){
        $endpoint = '/map_popup/findPointsByLatLngProximity';
        header('Content-Type: application/json');
        $response = wp_remote_post(str_replace('/api/', '', Epaka_Api_Controller::$ApiUrl) . $endpoint,["body"=>$data->get_params()]);
        if(!is_wp_error($response)){
            return rest_ensure_response(json_decode($response['body']));
        }
        return new WP_REST_Response($response, 404);
    }

    public function getPointsAutocomplete($data){
        $endpoint = '/map_popup/findPoints';
        header('Content-Type: application/json');
        $response = wp_remote_get(str_replace('/api/','',Epaka_Api_Controller::$ApiUrl).$endpoint.'?'.http_build_query($_GET));
        if(!is_wp_error($response)){
            return rest_ensure_response(json_decode($response['body']));
        }
        return new WP_REST_Response($response, 404);
    }

    public function getMap(){
        $mapSearch = false;

        $enpoint = sanitize_text_field($_GET['endpoint']);

        if($_GET['endpoint'] == "mapSearch") {
            $mapSearch = true;
            $_GET['endpoint'] = '/' . sanitize_text_field(urldecode($_GET['payload']));
            if (preg_match('/^\/map.php/', sanitize_text_field($_GET['endpoint'])) == 0) {
                return rest_ensure_response(false);
            }
        }elseif(preg_match('/files/', sanitize_text_field($_GET['endpoint']))){
            wp_redirect(str_replace('/api/','',Epaka_Api_Controller::$ApiUrl).$enpoint.'?v='.wp_generate_uuid4());
            exit;
        }elseif(preg_match('/map_popup/', sanitize_text_field($_GET['endpoint']))) {
            if(preg_match('/searchFromZinc/', sanitize_text_field($_GET['endpoint']))){
                $response = wp_remote_post(str_replace('/api/', '', Epaka_Api_Controller::$ApiUrl) . $enpoint,["body"=>$_POST]);
                return rest_ensure_response($response['body']);
            }
            $mapSearch = true;
        }elseif(preg_match('/punkt/', sanitize_text_field($_GET['endpoint']))){
            $response = wp_remote_get(str_replace('/api/', '', Epaka_Api_Controller::$ApiUrl) . $enpoint
                    . "&courier_id=" . $_GET['courier_id']
                    . "&point_lat=" . $_GET['point_lat']
                    . "&point_lng=" . $_GET['point_lng']);

            return rest_ensure_response($response['body']);
        }elseif(preg_match('/api/',sanitize_text_field($_GET['endpoint'])) == 0){
            return rest_ensure_response(null);
        }

        $response = null;
        if(!empty($_POST)){
            $lat = floatval(sanitize_text_field($_POST['lat']));
            $lon = floatval(sanitize_text_field($_POST['lon']));
            $map = sanitize_text_field($_POST['map']);

            $args = [
                'method' => 'POST',
                'timeout' => 60,
                'redirection' => 5,
                'httpversion' => '1.0',
                'headers' => array(
                    'Expect' => '',
                ),
                'body' => [
                    'lat' => $lat,
                    'lon' => $lon,
                    'map' => $map
                ]
            ];

            $response = wp_remote_request(str_replace('/api/','',Epaka_Api_Controller::$ApiUrl).$enpoint, $args);
        }else{
            $args = [
                'method' => 'GET',
                'redirection' => 5
            ];

            $response = wp_remote_get(str_replace('/api/','',Epaka_Api_Controller::$ApiUrl).$enpoint);
        }

        if(!empty($_POST)){
            $response = simplexml_load_string($response["body"],'SimpleXMLElement',LIBXML_NOCDATA);
        }else{
            $response = $response["body"];
        }

        return rest_ensure_response($response);
    }

    public function getOrderIframe(){

        $args = [
            'method' => 'POST',
            'sslVerfiy' => EPAKA_ENABLE_SSL_CHECKS,
            'timeout' => 60,
            'redirection' => 5,
            'body' => [
                'session' => get_option('epakaSession')
            ]
        ];
        $server_output = wp_remote_request(Epaka_Api_Controller::$ApiUrl.'/getOrderIframe', $args);

        header('Content-Type: text/html');
        echo $server_output['body'];
        exit();
    }

    public function getAvailableCouriers(){
        return rest_ensure_response(Epaka_Api_Controller::sendRequest("getAvailableCouriers.xml"));
    }

    public function cancelEpakaOrder(){
        if(!empty($_POST['epaka_order_id'])){
            $id = intval(sanitize_text_field($_POST['epaka_order_id']));
            if($id == 0){
                return rest_ensure_response(new WP_REST_Response(null, 404));
            }

            $try1 = Epaka_Api_Controller::sendRequest("cancelOrder/".$id.".xml");
            if($try1->data->status->__toString() == "ERROR"){
                $try2 = Epaka_Api_Controller::sendRequest("cancelOrderEmail/".$id.".xml");
                if($try1->data->status->__toString() == "ERROR"){
                    return rest_ensure_response(new WP_REST_Response(null, 404));
                }
                return rest_ensure_response(new WP_REST_Response("OK", 200));
            }
            return rest_ensure_response(new WP_REST_Response("OK", 200));
        }
        return rest_ensure_response(new WP_REST_Response(null, 404));
    }

    public function unlinkEpakaOrderFromWooOrder(){
        if(!empty($_POST['woo_order_id'])){
            $id = intval(sanitize_text_field($_POST['woo_order_id']));
            if($id == 0){
                return rest_ensure_response(new WP_REST_Response(null, 404));
            }

            $wooOrder = wc_get_order($id);
            $wooOrder->delete_meta_data('_epakaOrderId');
            $wooOrder->save();

            return rest_ensure_response(new WP_REST_Response("OK", 200));
        }
        return rest_ensure_response(new WP_REST_Response(null, 404));
    }

    public function linkEpakaOrderToWooOrder(){
        if(!empty($_POST['woo_order_id'])){
            if(!empty($_POST['epaka_order_id'])){
                $woo_id = intval(sanitize_text_field($_POST['woo_order_id']));
                $epaka_id = intval(sanitize_text_field($_POST['epaka_order_id']));

                if($woo_id == 0 || $epaka_id == 0){
                    return rest_ensure_response(new WP_REST_Response(null, 404));
                }

                $wooOrder = wc_get_order($woo_id);
                $wooOrder->add_meta_data('_epakaOrderId',$epaka_id);
                $wooOrder->save();

                return rest_ensure_response(new WP_REST_Response("OK", 200));
            }
        }
        return rest_ensure_response(new WP_REST_Response(null, 404));
    }

    public static function getEpakaOrderDetails($epakaId){
        $id = intval(sanitize_text_field($epakaId));
        if($id == 0){
            return rest_ensure_response(new WP_REST_Response(null, 404));
        }

        $order = Epaka_Api_Controller::sendRequest("order/".$id.".xml")->data;

        if(!empty($order)){
            if($order->status->__toString() == "OK"){
                $orderData = json_encode($order->orderDetails);
                $orderData = json_decode($orderData,true);

                return rest_ensure_response($orderData);
            }
        }

        return rest_ensure_response(new WP_REST_Response(null, 404));
    }

    public function getEpakaCourierTracking(){
        // $order = Epaka_Api_Controller::sendRequest("order/".$_POST['orderId'].".xml");
        $label = sanitize_text_field($_POST['label']);

        $tracking = Epaka_Api_Controller::sendRequest("getTraceOfParcel.xml",[
            "parcelNumber" => sanitize_text_field($_POST['label'])
        ]);

        if($tracking->data->status->__toString() == "OK"){
            if($tracking->data->error->__toString() != "1"){
                $trace = json_encode($tracking->data->trace);
                $trace = json_decode($trace,true);
                return rest_ensure_response($trace);
            }else{
                return rest_ensure_response(new WP_REST_Response($tracking->data->message->__toString(), 404));
            }
        }

        return rest_ensure_response(new WP_REST_Response(null, 404));
    }

    public function getEpakaOrderLabel(){
        $id = intval(sanitize_text_field($_POST['orderId']));

        $label = Epaka_Api_Controller::sendRequest("label/".$id.".xml");
        if($label->data->status->__toString() == "OK"){
            return rest_ensure_response($label->data->label->__toString());
        }
        return rest_ensure_response(new WP_REST_Response(null, 404));
    }

    public function getEpakaOrderProtocol(){
        $id = intval(sanitize_text_field($_POST['orderId']));

        $protocol = Epaka_Api_Controller::sendRequest("protocol/".$id.".xml");
        if($protocol->data->status->__toString() == "OK"){
            return rest_ensure_response($protocol->data->protocol->__toString());
        }
        return rest_ensure_response(new WP_REST_Response(null, 404));
    }

    public function getEpakaOrderAuthorizationDocument(){
        $id = intval(sanitize_text_field($_POST['orderId']));

        $authorizationDocument = Epaka_Api_Controller::sendRequest("authorizationDocument/".$id.".xml");
        if($authorizationDocument->data->status->__toString() == "OK"){
            return rest_ensure_response($authorizationDocument->data->document->__toString());
        }
        return rest_ensure_response(new WP_REST_Response(null, 404));
    }

    public function getEpakaOrderProforma(){
        $id = intval(sanitize_text_field($_POST['orderId']));

        $proforma = Epaka_Api_Controller::sendRequest("proforma/".$id.".xml");
        if($proforma->data->status->__toString() == "OK"){
            return rest_ensure_response($proforma->data->document->__toString());
        }
        return rest_ensure_response(new WP_REST_Response(null, 404));
    }

    public function getEpakaOrderLabelZebra(){
        $id = intval(sanitize_text_field($_POST['orderId']));

        $labelZebra = Epaka_Api_Controller::sendRequest("labelZebra/".$id.".xml");
        if($labelZebra->data->status->__toString() == "OK"){
            return rest_ensure_response($labelZebra->data->label->__toString());
        }
        return rest_ensure_response(new WP_REST_Response(null, 404));
    }

    public static function getEpakaOrderPaymentInfo($epaka_order_id){
        $id = intval(sanitize_text_field($epaka_order_id));

        if(!empty($id)){
            $payment = Epaka_Api_Controller::sendRequest("getPaymentDataForOrder.xml",[
                "orderId"=>$id
            ])->data;
            if(!empty($payment)){
                if($payment->status->__toString() == "OK"){
                    return rest_ensure_response($payment);
                }
            }
        }
        return rest_ensure_response(null);
    }

    public function sendOrder($data){
        $orderRequestData= $data->get_body_params()['data'];


        $orderPackages = [];
        foreach($orderRequestData['ZamowieniePaczka'] as $paczka){
            array_push($orderPackages,[
                "weight" => sanitize_text_field($paczka['waga']),
                "length" => sanitize_text_field($paczka['dlugosc']),
                "width" => sanitize_text_field($paczka['szerokosc']),
                "height" => sanitize_text_field($paczka['wysokosc']),
                "unsortableShape" => sanitize_text_field($paczka['ksztalt_niestandardowy'])
            ]);
        }

        $content = "";
        $contents = "";
        if(!empty($orderRequestData['ZamowienieZawartosc'][0]['zawartosc'])){
            $contents = (new ArrayObject($orderRequestData['ZamowienieZawartosc']))->getArrayCopy();
            if(!empty($contents[0]['ilosc']) || !empty($contents[0]['wartosc']) || !empty($contents[0]['waga'])){
                foreach($contents as &$contentValue)
                {
                    $contentValue = [
                        "content" => sanitize_text_field($contentValue["zawartosc"]),
                        "value" => sanitize_text_field($contentValue["wartosc"]),
                        "amount" => sanitize_text_field($contentValue["ilosc"]),
                        "weight" => sanitize_text_field($contentValue["waga"]),
                        "itemOrigin" => sanitize_text_field($contentValue["pochodzenie"]),
                        "itemCode" => sanitize_text_field($contentValue["kod"])
                    ];
                    // $value["zawartosc"] = sanitize_text_field($value["zawartosc"]);
                    // $value["pochodzenie"] = sanitize_text_field($value["pochodzenie"]);
                    // $value['kod'] = sanitize_text_field($value["kod"]);
                    // $value['ilosc'] = sanitize_text_field($value["ilosc"]);
                    // $value['wartosc'] = sanitize_text_field($value["wartosc"]);
                    // $value['waga'] = sanitize_text_field($value["waga"]);
                }
            }else{
                $content = sanitize_text_field($contents[0]['zawartosc']);
            }
            
        }else{
            $content = sanitize_text_field($orderRequestData['Zamowienie']['zawartosc']);
        }

        $pickupTimeFrom = "";
        $pickupTimeTo = "";

        if(!empty($orderRequestData['Zamowienie']['odbior_godzina'])){
            $pickupTime = explode("-",sanitize_text_field($orderRequestData['Zamowienie']['odbior_godzina']));
            $pickupTimeFrom = $pickupTime[0];
            $pickupTimeTo = $pickupTime[1];
        }

        $orderData = [
            "isApplication" => 1,
            "appPlatform" => "Woocommerce",
            "paymentType" =>sanitize_text_field($orderRequestData['Zamowienie']['platnosc']),
            "courierId" => sanitize_text_field($orderRequestData['Zamowienie']['kurier_id']),
            "senderName" => sanitize_text_field($orderRequestData['Zamowienie']['nadawca_imie']),
            "senderLastName" => sanitize_text_field($orderRequestData['Zamowienie']['nadawca_nazwisko']),
            "senderCompany" => sanitize_text_field($orderRequestData['Zamowienie']['nadawca_firma']),
            "senderStreet" => sanitize_text_field($orderRequestData['Zamowienie']['nadawca_ulica']),
            "senderHouseNumber" => sanitize_text_field($orderRequestData['Zamowienie']['nadawca_nrdomu']),
            "senderFlatNumber" => sanitize_text_field($orderRequestData['Zamowienie']['nadawca_nrlokalu']),
            "senderPostCode" => sanitize_text_field($orderRequestData['Zamowienie']['nadawca_kod']),
            "senderCity" => sanitize_text_field($orderRequestData['Zamowienie']['nadawca_miasto']),
            "senderCountry" => sanitize_text_field($orderRequestData['Zamowienie']['nadawca_kraj']),
            "senderPhone" => sanitize_text_field($orderRequestData['Zamowienie']['nadawca_telefon']),
            "senderEmail" => sanitize_text_field($orderRequestData['Zamowienie']['nadawca_email']),
            "senderMachineName" => sanitize_text_field($orderRequestData['Zamowienie']['nadawca_paczkomat']),
            "senderMachineDescription" => sanitize_text_field($orderRequestData['Zamowienie']['nadawca_paczkomat_opis']),
            "receiverName" => sanitize_text_field($orderRequestData['Zamowienie']['odbiorca_imie']),
            "receiverLastName" => sanitize_text_field($orderRequestData['Zamowienie']['odbiorca_nazwisko']),
            "receiverCompany" => sanitize_text_field($orderRequestData['Zamowienie']['odbiorca_firma']),
            "receiverStreet" => sanitize_text_field($orderRequestData['Zamowienie']['odbiorca_ulica']),
            "receiverHouseNumber" => sanitize_text_field($orderRequestData['Zamowienie']['odbiorca_nrdomu']),
            "receiverFlatNumber" => sanitize_text_field($orderRequestData['Zamowienie']['odbiorca_nrlokalu']),
            "receiverPostCode" => sanitize_text_field($orderRequestData['Zamowienie']['odbiorca_kod']),
            "receiverCity" => sanitize_text_field($orderRequestData['Zamowienie']['odbiorca_miasto']),
            "receiverCountry" => sanitize_text_field($orderRequestData['Zamowienie']['odbiorca_kraj']),
            "receiverPhone" => sanitize_text_field($orderRequestData['Zamowienie']['odbiorca_telefon']),
            "receiverEmail" => sanitize_text_field($orderRequestData['Zamowienie']['odbiorca_email']),
            "receiverMachineName" => sanitize_text_field($orderRequestData['Zamowienie']['odbiorca_paczkomat']),
            "receiverMachineDescription" => sanitize_text_field($orderRequestData['Zamowienie']['odbiorca_paczkomat_opis']),
            "packageType" => sanitize_text_field($orderRequestData['Zamowienie']['rodzaj_wysylki']),
            "packages" => $orderPackages,
            "content" => $content,
            "contents" => $contents,
            "pickupDate" => sanitize_text_field($orderRequestData['Zamowienie']['odbior_dzien']),
            "pickupTimeFrom" => sanitize_text_field($pickupTimeFrom),
            "pickupTimeTo" =>  sanitize_text_field($pickupTimeTo),
            "comments" => sanitize_text_field($orderRequestData['Zamowienie']['uwagi']),
            "eori" => sanitize_text_field($orderRequestData['Zamowienie']['eori']),
            "pesel" => sanitize_text_field($orderRequestData['Zamowienie']['pesel']),
            "purpose" => sanitize_text_field($orderRequestData['Zamowienie']['przeznaczenie']),
            "insurance" => (!empty($orderRequestData['Zamowienie']['wartosc'])) ? 1 : 0,
            "declaredValue" => sanitize_text_field($orderRequestData['Zamowienie']['wartosc']),
        ];

        if(!empty($orderRequestData['ZamowienieUsluga'])) {
            foreach ($orderRequestData['ZamowienieUsluga'] as $key => $value) {
                if ($key != "on") {
                    if ($value["on"] == "1") {
                        $orderData[$key] = 1;
                    }
                }
            }
        }

        $orderData['cod'] = !empty($orderRequestData['Zamowienie']['pobranie'])?($orderRequestData['Zamowienie']['pobranie'] == "on") ? 1 : 0 : 0;
        $orderData['codType'] = strtoupper(sanitize_text_field($orderRequestData['Zamowienie']['pobranie_typ']));
        $orderData['codAmount'] = sanitize_text_field($orderRequestData['Zamowienie']['pobranie_kwota']);
        $orderData['codBankAccount'] = sanitize_text_field($orderRequestData['Zamowienie']['pobranie_konto']);

        $orderResponse = Epaka_Api_Controller::sendRequest("makeOrder.xml", $orderData);

        if($orderResponse->data->status->__toString() == "OK"){
            Epaka_Api_Controller::updateWooCommerceOrder(sanitize_text_field($orderRequestData['WooCommerceData']['id']),$orderResponse->data->orderId->__toString());
            
            return rest_ensure_response($orderResponse->data);
        }
        return rest_ensure_response(new WP_REST_Response(null, 404));
    }

    public static function updateWooCommerceOrder($woo_order_id, $epaka_order_id){
        if(!empty($woo_order_id)){
            if(!empty($epaka_order_id)){
                $woo_id = intval(sanitize_text_field($woo_order_id));
                $epaka_id = intval(sanitize_text_field($epaka_order_id));

                if($woo_id == 0 || $epaka_id == 0){
                    return;
                }

                $wooOrder = wc_get_order($woo_id);
                if(!empty($wooOrder)){
                    $wooOrder->add_meta_data('_epakaOrderId',$epaka_order_id);
                    $wooOrder->save();
                }
            }
        }
    }

    public static function logout(){
        delete_option('epakaSession');
        delete_option('epakaE');
        delete_option('epakaP');
    }

    public static function isAuthorized(){
        if(!empty(get_option('epakaSession'))){
            return true;
        }else{
            return false;
        }
    }

    public static function ensureAuthorized(){
        return Epaka_Api_Controller::sendRequest("profile.xml");
    }

    public static function hasAuthMem(){
        if(!empty(get_option('epakaE')) && !empty(get_option('epakaP'))){
            return rest_ensure_response(true);
        }else{
            return rest_ensure_response(false);
        }
    }

    public static function sendRequest($endpoint = "", $postFields = []){
        $args = [
            'method' => 'POST',
            'sslVerify' => EPAKA_ENABLE_SSL_CHECKS,
            'timeout' => 60,
            'redirection' => 5,
            'body' => $postFields
        ];

        $args['body']['session'] = get_option('epakaSession');

        $response = wp_remote_request(Epaka_Api_Controller::$ApiUrl.$endpoint.'?XDEBUG_SESSION_START=1', $args);

        if(!is_wp_error($response)){
            $response = simplexml_load_string($response['body'],'SimpleXMLElement',LIBXML_NOCDATA);

            if($response->status == "OK"){
                return rest_ensure_response($response);
            }else if($response->status == "ERROR" || $response->code == "151" || $response->code == "150"){
                if(!empty(get_option('epakaE')) && !empty(get_option('epakaP'))){
                    $authorizeResponse = Epaka_Api_Controller::authorize(get_option('epakaE'), get_option('epakaP'))->data;
                    if($authorizeResponse->status != "OK"){
                        wp_redirect(admin_url('admin.php?page=epaka_admin_panel_login_page'));
                        return;
                    }

                    $args['body']['session'] = get_option('epakaSession');

                    $response = wp_remote_request(Epaka_Api_Controller::$ApiUrl.$endpoint, $args);

                    $response = simplexml_load_string($response['body'],'SimpleXMLElement',LIBXML_NOCDATA);

                    return rest_ensure_response($response);
                }
            }
        }else{
            Epaka_Api_Controller::logout();
            wp_redirect(admin_url('admin.php?page=epaka_admin_panel_login_page'));
        }
    }
}
