<?php

namespace Eadesigndev\NemoExpress\Model\Carrier;

use Monolog\Logger as MonoLogger;
use Monolog\Handler\StreamHandler;
use Monolog\Level;

#[\AllowDynamicProperties]
class CourierManagerApi
{
    const API_URL = "https://app.nemoexpress.ro/nemo";
    const API_KEY_CONFIG_PATH = "carriers/nemoexpress/password";

    const CREATE_AWB_ENDPOINT = "create_awb";
    const PRICE_AWB_ENDPOINT = "get_price";
    const PRINT_AWB_ENDPOINT = "print";
    const INFO_AWB_ENDPOINT = "get_info";
    const CHANGE_STATUS_ENDPOINT = "change_status";

    const CANCEL_AWB_STATUS = "anulat";

    const OPEN_SERVICE_ID = 1;
    const SATURDAY_SERVICE_ID = 2;

    private $apiUrl = self::API_URL;
    private $apiKey;

    private static $availableAwbStatus = [
        "initial",
        "neridicat",
        "in_curs",
        "livrat",
        "returnat",
        "anulat",
        "exceptie"
    ];
    /**
     * @var \Zend\Log\Logger
     */
    private $logger;

    private \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig;

    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
    )
    {
        $monolog = new MonoLogger('getawbbb');
        $monolog->pushHandler(new StreamHandler(BP . '/var/log/getawb.log', Level::Debug));
        $this->logger = $monolog;

        $this->scopeConfig  = $scopeConfig;
        $this->apiKey = $this->scopeConfig->getValue(
            self::API_KEY_CONFIG_PATH,
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }

    public function getApiKey()
    {
        return $this->apiKey;
    }

    public function createAwb($data)
    {
        $response = $this->callApi(self::CREATE_AWB_ENDPOINT, $data);
        $this->logger->info('createAwb - $response NEMO :  '.$response);
        return json_decode($response);
    }



    public function priceAwb($data)
    {
        $response = $this->callApi(self::PRICE_AWB_ENDPOINT, $data);
        return json_decode($response);
    }

    public function printAwb($awbId)
    {
        return $this->callApi(self::PRINT_AWB_ENDPOINT, array(
            "awbno" => $awbId,
            "pdf" => 'true'
        ));
    }

    public function infoAwb($awbId)
    {
        $response = $this->callApi(self::INFO_AWB_ENDPOINT, array(
            "awbno" => $awbId
        ));
        return json_decode($response);
    }

    public function awbDelete($awbNo)
    {
        return $this->changeStatus($awbNo, self::CANCEL_AWB_STATUS);
    }

    public function changeStatus($awbNo, $status)
    {
        if (!in_array($status, self::$availableAwbStatus)) {
            return false;
        }

        return $this->callApi(self::CHANGE_STATUS_ENDPOINT, [
            "awbno" => $awbNo,
            "status" => $status
        ]);
    }

    private function callApi($endpoint, $params = array())
    {
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $this->apiUrl . "/API/" . $endpoint . "?api_key=" . $this->getApiKey());
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 15);

        if (!empty($params)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params));
        }

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
            error_log($err);
            return false;
        }

        return $response;
    }

    public function setApiKey($apiKey)
    {
        $this->apiKey = $apiKey;
    }
}
