<?php
if (!defined('_PS_VERSION_'))
    exit;

const _PAXY_API_URL = 'https://api.paxy.pl';
const _PAXY_WIDGET_API_URL = 'https://iai-bridge.paxy.pl/api/v1';

class Paxypresta extends Module
{
    public function __construct()
    {
        $this->name = 'paxypresta';
        $this->tab = 'shipping_logistics';
        $this->tableName = 'paxypresta';
        $this->version = '1.5.3';
        $this->author = 'Paxy';
        $this->need_instance = 0;
        $this->ps_versions_compliancy = array('min' => '1.7.5', 'max' => _PS_VERSION_);
        $this->bootstrap = true;

        parent::__construct();

        $this->displayName = $this->l('Paxy');
        $this->description = $this->l('Paxy for presta 1.7.5 or higher');

        $this->confirmUninstall = $this->l('Are you sure you want to uninstall?');

        if (!Configuration::get('paxypresta'))
            $this->warning = $this->l('No name provided');

    }

    public function install()
    {
        if (Shop::isFeatureActive()) {
            Shop::setContext(Shop::CONTEXT_ALL);
        }

        $tab = new Tab();
        $lang = Language::getLanguages();
        $tab->active = 1;
        $tab->class_name = "AdminPaxypresta";
        $tab->module = $this->name;
        $tab->name = array();
        $tab->id_parent = (int)Tab::getIdFromClassName('AdminParentShipping');
        $tab->position = 3;
        foreach ($lang as $l) {
            $tab->name[$l['id_lang']] = $this->l('Paxy carriers');
        }

        $tab->save();

        $tab2 = new Tab();
        $tab2->active = 0;
        $tab2->class_name = 'AdminPaxyprestacreate';
        $tab2->name = array();
        foreach (Language::getLanguages(true) as $l)
            $tab2->name[$l['id_lang']] = 'AdminPaxyprestaCreate';
        $tab2->id_parent = -1;
        $tab2->module = $this->name;

        $tab2->save();

        $tab3 = new Tab();
        $tab3->active = 0;
        $tab3->class_name = 'AdminPaxyprestadelete';
        $tab3->name = array();
        foreach (Language::getLanguages(true) as $l)
            $tab3->name[$l['id_lang']] = 'AdminPaxyprestaCreate';
        $tab3->id_parent = -1;
        $tab3->module = $this->name;

        $tab3->save();

        $this->updateDatabase();

        if (!parent::install() ||
            !$this->registerHook("actionValidateOrder") ||
            !$this->registerHook("displayHeader") ||
            !$this->registerHook("displayAfterCarrier") ||
            !$this->registerHook("displayAdminOrder")
        ) {
            return false;
        }

        return true;
    }

    private function findPaxyCourierByReference($id_carrier) {
        $sql = new DbQuery();
        $sql->select('pp.*');
        $sql->from('paxy_presta_couriers', 'pp');
        $sql->innerJoin('carrier', 'c', 'pp.id_reference = c.id_reference');
        $sql->where('c.active = 1');
        $sql->where('c.deleted = 0');
        $sql->where("c.id_carrier = $id_carrier");
        return Db::getInstance()->executeS($sql);
    }

    public function hookActionValidateOrder($params)
    {
        $SQL = "SELECT * FROM "._DB_PREFIX_."paxy_presta_cart WHERE pickup_point_id IS NOT NULL AND cart_id = ". $params['cart']->id;
        $clcartData = DB::getInstance()->executeS($SQL);

        if (!empty($params['cart']->id_carrier)) {
            $idCarrier = $params['cart']->id_carrier;
            $pickupPointId = "NULL";
            $pickupPointDetails = "NULL";
            $pickupPointIdBef = null;
            if (!empty($clcartData[0]['pickup_point_id'])) {
                $pickupPointId = $clcartData[0]['pickup_point_id'];
                $pickupPointIdBef = $pickupPointId;
                $pickupPointId = "'$pickupPointId'";
            }
            $paxyCourier = $this->findPaxyCourierByReference($idCarrier);
            if (!empty($paxyCourier) && count($paxyCourier) > 0) {
                $paxyCourierData = $paxyCourier[0];

                $widgetPickupPoint = "NULL";
                if ($paxyCourierData['widget_pickup_point']) {
                    $widgetPickupPoint = $paxyCourierData['widget_pickup_point'];
                    $widgetPickupPoint = "'$widgetPickupPoint'";
                }
                $rawPointId = "NULL";
                if ($pickupPointIdBef) {
                    $parsedPointId = $this->parsePointId($pickupPointIdBef);
                    $rawPointId = $parsedPointId['body']['id'];
                    $rawPointId = "'$rawPointId'";
                }

                if ($pickupPointId !== "NULL" && $widgetPickupPoint !== "NULL") {
                    $pointDetailsResponse = $this->findPoint(
                        preg_replace(['/^\'/', '/\'$/'], '', $widgetPickupPoint),
                        preg_replace(['/^\'/', '/\'$/'], '', $pickupPointId),
                    );
                    if (!empty($pointDetailsResponse) && isset($pointDetailsResponse['body'])) {
                        $point = $pointDetailsResponse['body'];

                        $pickupPointDetails = implode(', ', [
                            $point['name'],
                            $point['lat'],
                            $point['lng'],
                            $point['address'],
                            $point['postCode'],
                            $point['city'],
                            $point['country'],
                        ]);
                    }
                }

                $SQL = "INSERT INTO "._DB_PREFIX_."paxy_order_point (order_id,pickup_point_id,pickup_point_details,id_paxy_courier,id_paxy_country,paxy_parcel_type,paxy_courier_name, paxy_country_name, widget_pickup_point, raw_point_id) VALUES  (".$params['order']->id . ", ".$pickupPointId.", '".$pickupPointDetails."', ".$paxyCourierData['id_paxy_courier'].", ".$paxyCourierData['id_paxy_country'].", '".$paxyCourierData['paxy_parcel_type']."', '".$paxyCourierData['paxy_courier_name']."', '".$paxyCourierData['paxy_country_name']."', ".$widgetPickupPoint.", ".$rawPointId.")";
                $ret = DB::getInstance()->execute($SQL);
            }
        }
    }

    private function parsePointId($pointId)
    {
        $apiKey = Configuration::get('paxy_widget_api_key');
        $ch = curl_init(_PAXY_WIDGET_API_URL . "/paxyWidget/parsePointId");
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "token: $apiKey",
            'Accept: application/json'
        ]);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $data_string = json_encode(array("id"=>$pointId));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        $apiResponse = curl_exec($ch);
        curl_close($ch);
        if ($apiResponse) {
            return json_decode($apiResponse,true);
        }

        return [];
    }

    private function findPoint($carrier, $pointId)
    {
        $apiKey = Configuration::get('paxy_widget_api_key');
        $ch = curl_init(_PAXY_WIDGET_API_URL . "/paxyWidget/points/" . $carrier . "/" . $pointId);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "token: $apiKey",
            'Accept: application/json'
        ]);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $apiResponse = curl_exec($ch);
        curl_close($ch);
        if ($apiResponse) {
            return json_decode($apiResponse,true);
        }

        return [];
    }

    public function updateCartData($pickupPointId)
    {
        $context = Context::getContext();
        $cart = $context->cart;

        $deleteSql = "DELETE FROM "._DB_PREFIX_."paxy_presta_cart WHERE cart_id = ". $cart->id;
        DB::getInstance()->execute($deleteSql);

        if (!empty($pickupPointId)) {
            $insertSql = "INSERT INTO " . _DB_PREFIX_ . "paxy_presta_cart (cart_id, pickup_point_id) VALUES  (" . $cart->id . ", '" . $pickupPointId . "')";
            DB::getInstance()->execute($insertSql);
        }

        return true;
    }

    public function getSelectedPickupPointData()
    {
        $context = Context::getContext();
        $cart = $context->cart;

        if ($cart->id && $cart->id_carrier) {
            $paxyCourier = $this->findPaxyCourierByReference($cart->id_carrier);
            if (!empty($paxyCourier)) {
                $selectSql = "SELECT * FROM " . _DB_PREFIX_ . "paxy_presta_cart WHERE cart_id = " . $cart->id;
                $ret = DB::getInstance()->executeS($selectSql);
                if (!empty($ret)) {
                    $pickupPointData = $this->findPoint($paxyCourier[0]['widget_pickup_point'], $ret[0]['pickup_point_id']);
                    if (!empty($pickupPointData['body'])) {
                        return $pickupPointData['body'];
                    }
                }
            }
            $this->updateCartData(null);
        }
        return null;
    }

    public function updateDatabase()
    {
        DB::getInstance()->execute('
            CREATE TABLE IF NOT EXISTS '._DB_PREFIX_.'paxy_presta_couriers (
                id INT NOT NULL AUTO_INCREMENT,
                id_reference int NOT NULL,
                is_pickup_point boolean,
                widget_pickup_point varchar(255),
                id_paxy_courier int NOT NULL,
                id_paxy_country int NOT NULL,
                paxy_parcel_type varchar(255) NOT NULL,
                paxy_courier_name varchar(255),
                paxy_country_name varchar(255),
                primary key (id)
            );
        ');

        DB::getInstance()->execute('
            CREATE TABLE IF NOT EXISTS '._DB_PREFIX_.'paxy_presta_cart (
                cart_id int NOT NULL,
                pickup_point_id varchar(255)
            );
        ');

        DB::getInstance()->execute('
            CREATE TABLE IF NOT EXISTS '._DB_PREFIX_.'paxy_order_point (
                id INT NOT NULL AUTO_INCREMENT,
                order_id int NOT NULL,
                pickup_point_id varchar(255),
                pickup_point_details varchar(1024) NULL DEFAULT NULL,
                id_paxy_courier int NOT NULL,
                id_paxy_country int NOT NULL,
                paxy_parcel_type varchar(255) NOT NULL,
                paxy_courier_name varchar(255),
                paxy_country_name varchar(255),
                widget_pickup_point varchar(255),
                paxy_parcel_number VARCHAR(100),
                paxy_parcel_created DATETIME,
                primary key (id)
            );
        ');

        DB::getInstance()->execute('ALTER TABLE '._DB_PREFIX_.'paxy_order_point ADD COLUMN raw_point_id varchar(255)');
    }

    public function uninstall()
    {
        $tab = new Tab((int)Tab::getIdFromClassName('AdminPaxypresta'));
        $tab->delete();

        $tab2 = new Tab((int)Tab::getIdFromClassName('AdminPaxyprestacreate'));
        $tab2->delete();

        $sql = 'DROP TABLE '._DB_PREFIX_.'paxy_presta_couriers';
        Db::getInstance()->execute($sql);

        $sql = 'DROP TABLE '._DB_PREFIX_.'paxy_presta_cart';
        Db::getInstance()->execute($sql);

        $sql = 'DROP TABLE '._DB_PREFIX_.'paxy_order_point';
        Db::getInstance()->execute($sql);

        if (!parent::uninstall() ||
            !Configuration::deleteByName($this->name)
        ) {
            return false;
        }

        return true;
    }

    public function isUsingNewTranslationSystem()
    {
        return true;
    }

    public function hookDisplayHeader()
    {
        $selectedPickupPointData = $this->getSelectedPickupPointData();
        $this->context->controller->addJquery();
        $this->context->controller->addCss($this->_path.'css/paxywidget.css');
        $this->context->controller->addCss($this->_path.'css/paxypresta.css');
        $this->context->controller->addJS($this->_path.'js/select2.min.js');
        $this->context->controller->addJS($this->_path.'js/paxyShippingFront.js');
        $this->context->controller->addJS($this->_path.'js/paxywidget.js');

        Media::addJsDef([
            'paxy_carriers_ids' => json_encode($this->getIdCarriersWithPickupPoints()),
            'paxy_carriers' => json_encode($this->getCarriersWithPickupPoints()),
            'paxy_widget_token' => Configuration::get('paxy_widget_api_key'),
            'paxy_widget_api_url' => Context::getContext()->link->getModuleLink('paxypresta', 'paxypoints'),
            'paxy_widget_assets_url' => Context::getContext()->link->getModuleLink('paxypresta', 'paxyassets'),
            'paxy_widget_update_cart_url' => Context::getContext()->link->getModuleLink('paxypresta', 'paxyupdatecart'),
            'paxy_widget_postcodes_url' => Context::getContext()->link->getModuleLink('paxypresta', 'paxypostcodes'),
            'paxy_widget_postcodes_allowed_country' => ['ro'],
            'paxy_widget_selected_pickup_point' => !empty($selectedPickupPointData) ? json_encode($selectedPickupPointData) : null,
            'paxy_widget_lang' => !empty($this->context->language->iso_code) ? $this->context->language->iso_code : 'pl',
            'paxy_widget_dictionary' => [
                "selected_pickup_point" => $this->trans("Selected pickup point", [], 'Modules.Paxypresta.Paxypresta'),
                "selected_country" => $this->trans("Selected country", [], 'Modules.Paxypresta.Paxypresta'),
                "show_details" => $this->trans("Show details", [], 'Modules.Paxypresta.Paxypresta'),
                "reset_search" => $this->trans("Reset search", [], 'Modules.Paxypresta.Paxypresta'),
                "search" => $this->trans("Search", [], 'Modules.Paxypresta.Paxypresta'),
                "show_on_map" => $this->trans("Show on map", [], 'Modules.Paxypresta.Paxypresta'),
                "select" => $this->trans("Select", [], 'Modules.Paxypresta.Paxypresta'),
                "opening_hours" => $this->trans("Opening hours", [], 'Modules.Paxypresta.Paxypresta'),
                "courier" => $this->trans("Courier", [], 'Modules.Paxypresta.Paxypresta'),
                "monday" => $this->trans("Monday", [], 'Modules.Paxypresta.Paxypresta'),
                "tuesday" => $this->trans("Tuesday", [], 'Modules.Paxypresta.Paxypresta'),
                "wednesday" => $this->trans("Wednesday", [], 'Modules.Paxypresta.Paxypresta'),
                "thursday" => $this->trans("Thursday", [], 'Modules.Paxypresta.Paxypresta'),
                "friday" => $this->trans("Friday", [], 'Modules.Paxypresta.Paxypresta'),
                "saturday" => $this->trans("Saturday", [], 'Modules.Paxypresta.Paxypresta'),
                "sunday" => $this->trans("Sunday", [], 'Modules.Paxypresta.Paxypresta'),
                "localize_me" => $this->trans("Show my localization", [], 'Modules.Paxypresta.Paxypresta'),
                "search_input" => $this->trans("Search", [], 'Modules.Paxypresta.Paxypresta'),
            ]
        ]);
    }

    public function hookDisplayAfterCarrier() {
        $this->context->smarty->assign([
            'paxy_select_point_title' => $this->trans('Press button to select pickup point', [], 'Modules.Paxypresta.Paxypresta'),
            'paxy_select_point_button' => $this->trans('Select pickup point', [], 'Modules.Paxypresta.Paxypresta'),
        ]);

        return $this->display(__FILE__, 'display_after_carrier.tpl');
    }

    private function getCarriersBaseQuery() {
        $sql = new DbQuery();
        $sql->select('c.id_carrier, pp.id as paxy_id, pp.widget_pickup_point');
        $sql->from('paxy_presta_couriers', 'pp');
        $sql->innerJoin('carrier', 'c', 'pp.id_reference = c.id_reference');
        $sql->where('c.active = 1');
        $sql->where('c.deleted = 0');
        $sql->where('pp.is_pickup_point = 1');
        return Db::getInstance()->executeS($sql);
    }

    private function getCarriersWithPickupPoints() {
        $items = $this->getCarriersBaseQuery();
        $data = [];

        if (!empty($items)) {
            foreach ($items as $i) {
                $data[] = [
                    'id_carrier' => (int) $i['id_carrier'],
                    'widget_pickup_point' => $i['widget_pickup_point'],
                    'paxy_id' => (int) $i['paxy_id'],
                ];
            }
        }

        return $data;
    }

    private function getIdCarriersWithPickupPoints() {
        $items = $this->getCarriersBaseQuery();
        $data = [];

        if (!empty($items)) {
            foreach ($items as $i) {
                $data[] = (int) $i['id_carrier'];
            }
        }

        return $data;
    }


    public function displayForm()
    {
        $defaultLang = (int)Configuration::get('PS_LANG_DEFAULT');

        // Init Fields form array
        $fieldsForm[0]['form'] = [
            'legend' => [
                'title' => $this->l('Settings'),
            ],
            'input' => [
                [
                    'type' => 'text',
                    'label' => $this->l('Paxy - Api key'),
                    'name' => 'paxy_api_key',
                    'size' => 50,
                    'required' => true
                ],
                [
                    'type' => 'text',
                    'label' => $this->l('Paxy - Api secret'),
                    'name' => 'paxy_api_secret',
                    'size' => 50,
                    'required' => true
                ],
                [
                    'type' => 'text',
                    'label' => $this->l('Paxy widget - Api key'),
                    'name' => 'paxy_widget_api_key',
                    'size' => 50,
                    'required' => true
                ],
            ],
            'submit' => [
                'title' => $this->l('Save'),
                'class' => 'btn btn-default pull-right'
            ]
        ];


        $helper = new HelperForm();

        // Module, token and currentIndex
        $helper->module = $this;
        $helper->name_controller = $this->name;
        $helper->token = Tools::getAdminTokenLite('AdminModules');
        $helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;

        // Language
        $helper->default_form_language = $defaultLang;
        $helper->allow_employee_form_lang = $defaultLang;

        // Title and toolbar
        $helper->title = $this->displayName;
        $helper->show_toolbar = true;        // false -> remove toolbar
        $helper->toolbar_scroll = true;      // yes - > Toolbar is always visible on the top of the screen.
        $helper->submit_action = 'submit'.$this->name;
        $helper->toolbar_btn = [
            'save' => [
                'desc' => $this->l('Save'),
                'href' => AdminController::$currentIndex.'&configure='.$this->name.'&save'.$this->name.
                    '&token='.Tools::getAdminTokenLite('AdminModules'),
            ],
            'back' => [
                'href' => AdminController::$currentIndex.'&token='.Tools::getAdminTokenLite('AdminModules'),
                'desc' => $this->l('Back to list')
            ]
        ];

        $helper->fields_value['paxy_api_key'] = Tools::getValue('paxy_api_key', Configuration::get('paxy_api_key'));
        $helper->fields_value['paxy_api_secret'] = Tools::getValue('paxy_api_secret', Configuration::get('paxy_api_secret'));
        $helper->fields_value['paxy_widget_api_key'] = Tools::getValue('paxy_widget_api_key', Configuration::get('paxy_widget_api_key'));

        return $helper->generateForm($fieldsForm);
    }

    public function getContent()
    {
        $output = null;

        if (Tools::isSubmit('submit'.$this->name)) {
            $paxy_api_key = Tools::getValue('paxy_api_key');
            $paxy_api_secret = Tools::getValue('paxy_api_secret');
            $paxy_widget_api_key = Tools::getValue('paxy_widget_api_key');
            if (
                empty($paxy_api_key) || empty($paxy_api_secret) || empty($paxy_widget_api_key)
            ) {
                $output .= $this->displayError($this->l('Invalid Configuration value'));
            } else {
                Configuration::updateValue('paxy_api_key', $paxy_api_key);
                Configuration::updateValue('paxy_api_secret', $paxy_api_secret);
                Configuration::updateValue('paxy_widget_api_key', $paxy_widget_api_key);
                $output .= $this->displayConfirmation($this->l('Settings updated'));
            }
        }

        return $output.$this->displayForm();
    }

    private function mapPointValueToLabel($value)
    {
        switch ($value) {
            case "cp_balikovna":
                return "Balíkovna - Česká pošta";
            case "cp_napostu":
                return "Balík Na poštu - Česká pošta";
            case "sps_parcelshop_":
                return "SPS ParcelShop";
            case "sps_balikomat_":
                return "SPS Balikomat";
            case "econt":
                return "Econt Office";
            case "sameday":
                return "SameDay (RO)";
            case "samedayhu":
                return "SameDay (HU)";
            case "samedaybg_":
                return "SameDay (BG)";
            case "wedo_point_":
                return "WeDo Point";
            case "wedo_box_":
                return "WeDo Box";
            case "sppoczta":
                return "Slovenská pošta";
            case "sppoczta_office_":
                return "Balík na poštu - Slovenská pošta";
            case "sppoczta_point_":
                return "BalíkoBOX - Slovenská pošta";
            case "mpl_office_":
                return "Csomagautomata - Magyar Posta";
            case "mpl_point_":
                return "PostaPont - Magyar Posta";
            case "mpl_postapont_":
                return "PostaPont - Magyar Posta";
            case "mpl_csomagautomata_":
                return "Csomagautomata - Magyar Posta";
            case "lpexpress":
                return "LPExpress Point";
            case "sp_point_":
                return "Balík na poštu - Slovenská pošta";
            case "sp_office_":
                return "BalíkoBOX - Slovenská pošta";
            case "postask_napostu_":
                return "Balík na poštu - Slovenská pošta";
            case "postask_balikobox_":
                return "BalíkoBOX - Slovenská pošta";
            case "ppl_parcelbox_":
                return "PPL ParcelBox";
            case "ppl_parcelshop_":
                return "PPL ParcelShop";
            case "fancourier_fanbox_":
                return "FanCourier FanBOX";
            case "fancourier_point_":
                return "FanCourier Point";
            case "fancourier_collectpoint_":
                return "FanCourier CollectPoint";
            case "venipaklt_locker_":
                return "Venipak Locker (LT)";
            case "venipaklt_pickup_":
                return "Venipak Pickup (LT)";
            case "venipaklv_locker_":
                return "Venipak Locker (LV)";
            case "venipaklv_pickup_":
                return "Venipak Pickup (LV)";
            case "venipakee_locker_":
                return "Venipak Locker (EE)";
            case "venipakee_pickup_":
                return "Venipak Pickup (EE)";
            case "postahr_napostu_":
                return "Post Office - Hrvatska pošta";
            case "postahr_paketomat_":
                return "Paketomat - Hrvatska pošta";
            case "cargus_":
                return "Cargus Locker";
            case "hermes_":
                return "Hermes Paketversand";
            case "posteitaliane_":
                return "Poste Italiane";
            case "postnordse_":
                return "PostNord (SE)";
            case "postnordfi_":
                return "PostNord (FI)";
            case "postnorddk_":
                return "PostNord (DK)";
            default:
                return $value;
        }
    }

    public function hookDisplayAdminOrder($param)
    {
        $idOrder = $param['id_order'];

        $sql2 = new DbQuery();
        $sql2->from('paxy_order_point', 'po');
        $sql2->where('po.order_id = '.$idOrder);
        $paxyOrderData = Db::getInstance()->executeS($sql2);

        $isPaxyOrder = false;
        if (!empty($paxyOrderData[0])) {
            $isPaxyOrder = true;
            if (!empty($paxyOrderData[0]['widget_pickup_point'])) {
                $paxyOrderData[0]['prettyPointName'] = $this->mapPointValueToLabel($paxyOrderData[0]['widget_pickup_point']);
            }
        }

        $order = new Order($idOrder);
        $cod = false;
        if ($order->module === 'cashondelivery') {
            $cod = round((float) $order->total_paid, 2);
        }

        $createPackageLink = null;
        $weight = null;
        $downloadLabelLink = null;

        if ($isPaxyOrder) {
            $createPackageLink = $this->context->link->getAdminLink('AdminPaxyprestacreateparcel').'&paxy_order_point='.$paxyOrderData[0]['order_id'];
            $downloadLabelLink = $this->context->link->getAdminLink('AdminPaxyprestadownloadlabel').'&paxy_order_point='.$paxyOrderData[0]['order_id'];


            $sql = new DbQuery();
            $sql->select('d.weight');
            $sql->from('order_carrier', 'd');
            $sql->where('d.id_order = '.$idOrder);
            $details = Db::getInstance()->executeS($sql);
            if (!empty($details[0]['weight'])) {
                $weight = round((float) $details[0]['weight'], 2);
            }
        }

        $errorMessage = null;
        if (isset($_SESSION["error_czechlogistic_parcel"])) {
            $errorMessage = $_SESSION["error_czechlogistic_parcel"];
            $_SESSION["error_czechlogistic_parcel"] = null;
        }

        $successMessage = null;
        if (isset($_SESSION['error_czechlogistic_parcel_created'])) {
            $successMessage = $_SESSION['error_czechlogistic_parcel_created'];
            $_SESSION['error_czechlogistic_parcel_created'] = null;
        }

        $this->context->smarty->assign([
            'isPaxyOrder' => $isPaxyOrder,
            'paxyOrderData' => isset($paxyOrderData[0]) ? $paxyOrderData[0] : null,
            'cod' => $cod,
            'isGeneratedInPaxy' => !empty($paxyOrderData[0]['paxy_parcel_number']),
            'createPackageLink' => $createPackageLink,
            'weight' => $weight,
            'errorMessage' => $errorMessage,
            'successMessage' => $successMessage,
            'downloadLabelLink' => $downloadLabelLink
        ]);

        return $this->display(__FILE__, 'display_admin_order.tpl');
    }



}
