<?php
/*
* 2007-2016 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author PrestaShop SA <contact@prestashop.com>
*  @copyright  2007-2016 PrestaShop SA
*  @license    http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/

/**
 * @since 1.6.0
 */
class AdminPaxyprestacreateController extends ModuleAdminController
{
    public function __construct()
    {
        $this->display = 'view';
        $this->bootstrap = true;
        parent::__construct();

        $this->addJs('modules/paxypresta/js/paxyCreateAdmin.js');

        $router = \PrestaShop\PrestaShop\Adapter\SymfonyContainer::getInstance()->get('router');

        Media::addJsDef(['paxyCarriersUrl' => $router->generate('paxy_carriers')]);
        Media::addJsDef(['paxyDimensionsUrl' => $router->generate('paxy_parcel_types')]);
    }

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

    private function loadCountries()
    {
        $apiKey = Configuration::get('paxy_api_key');;
        $apiSecret = Configuration::get('paxy_api_secret');
        $ch = curl_init(_PAXY_API_URL . "/country/");
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "CL-API-KEY: $apiKey",
            "CL-API-TOKEN: $apiSecret",
            '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) {
            $response = json_decode($apiResponse, true);
            $countries = [];
            $countries[] = [
                "id" => null,
                "code" => null,
                "name" => ""
            ];
            $countries = array_merge($countries, $response['countries']);
            return $countries;
        }

        return [];
    }

    private function loadPickupPointTypes()
    {
        $apiKey = Configuration::get('paxy_widget_api_key');
        $ch = curl_init(_PAXY_WIDGET_API_URL . "/paxyWidget/carriers");
        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) {
            $response = json_decode($apiResponse, true);
            $data = [];
            $data[] = [
                'value' => null,
                'label' => null,
            ];
            foreach ($response['body'] as $item) {
                $data[] = [
                    'label' => $this->mapPointValueToLabel($item),
                    'value' => $item
                ];
            }
            return $data;
        }

        return [];
    }

    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;
        }
    }

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

    public function renderView()
    {
        $isError = false;
        $paxyDescription = '';
        if (!empty($_GET["paxyError"]) && $_GET["paxyError"] === "1") {
            $isError = true;
            $paxyDescription = $_GET['paxyDescription'];
        }

        $this->tpl_view_vars = array(
            'clCarriers' => $this->getActiveCarriers(),
            'submitLink' => $this->context->link->getAdminLink('AdminPaxyprestacreate'),
            'success' => false,
            'countries' => $this->loadCountries(),
            'points' => $this->loadPickupPointTypes(),
            'isError' => $isError,
            'errorDesc' => $paxyDescription
        );


        $this->base_tpl_view = 'create.tpl';

        return parent::renderView();
    }

    public function postProcess()
    {
        if (Tools::isSubmit('saveCourier'))
        {
            $carrierId = (int) Tools::getValue('id_reference');
            $isPickupPoint = Tools::getValue("isPickupPoint") === "on";
            $paxyCountryId = Tools::getValue("paxy_country_id");
            $paxyCourierId = Tools::getValue("paxy_courier_id");
            $paxyParcelType = Tools::getValue("paxy_parcel_type");
            $isPickupPoint = $isPickupPoint ? 1 : 0;
            $paxyWidgetPoint = Tools::getValue("paxy_point") ? Tools::getValue("paxy_point") : null;

            if (empty($carrierId) || empty($paxyCountryId) || empty($paxyCourierId) || empty($paxyParcelType)) {
                $link = $this->context->link->getAdminLink('AdminPaxyprestacreate', true, [], ['paxyError' => true, 'paxyDescription' => 'Błędnie wypełniony formularz']);
                Tools::redirectAdmin($link);
                return;
            }

            $activeCarriers = $this->getPickupPointsCarriers();
            $exists = false;
            if (!empty($activeCarriers)) {
                foreach ($activeCarriers as $carrier) {
                    if ((int) $carrier['id_reference'] === $carrierId) {
                        $exists = true;
                        $link = $this->context->link->getAdminLink('AdminPaxyprestacreate', true, [], ['paxyError' => true, 'paxyDescription' => 'Powiązanie dla tego kuriera już istnieje']);
                        Tools::redirectAdmin($link);
                        return;
                    }
                }
            }

            $courierName = $this->findCourierName($paxyCourierId);
            $countryName = $this->findCountryName($paxyCountryId);


            if ($exists === false) {
                $SQL = "INSERT INTO "._DB_PREFIX_."paxy_presta_couriers (id_reference, is_pickup_point, widget_pickup_point, id_paxy_courier, id_paxy_country, paxy_parcel_type, paxy_courier_name
,paxy_country_name) VALUES  (".$carrierId.", ".$isPickupPoint.", '".$paxyWidgetPoint."', ".$paxyCourierId.", ".$paxyCountryId.", '".$paxyParcelType."', '".$courierName."', '".$countryName."')";
                $result = DB::getInstance()->execute($SQL);
            }

            $link = $this->context->link->getAdminLink('AdminPaxypresta');
            Tools::redirectAdmin($link);
        }
    }

    public function findCourierName($courierId)
    {
        return $this->findCourier($courierId)['name'] ?? null;
    }

    public function findCountryName($countryId)
    {
        return $this->findCountry($countryId)['name'] ?? null;
    }

    public function findCourier($courierId)
    {
        $apiKey = Configuration::get('paxy_api_key');;
        $apiSecret = Configuration::get('paxy_api_secret');
        $ch = curl_init();
        $endpoint = _PAXY_API_URL . '/carrier/'.$courierId;
        $params = array();
        $url = $endpoint;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "CL-API-KEY: $apiKey",
            "CL-API-TOKEN: $apiSecret",
            '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) {
            $response = json_decode($apiResponse, true);
            return $response['carrier'];
        }

        return false;
    }

    public function findCountry($countryId)
    {
        $apiKey = Configuration::get('paxy_api_key');;
        $apiSecret = Configuration::get('paxy_api_secret');
        $ch = curl_init();
        $endpoint = _PAXY_API_URL . '/country/'.$countryId;
        $params = array();
        $url = $endpoint;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "CL-API-KEY: $apiKey",
            "CL-API-TOKEN: $apiSecret",
            '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) {
            $response = json_decode($apiResponse, true);
            return $response['country'];
        }

        return false;
    }


}
