<?php
namespace Leadlion\PersoanaJuridica\Model;

use Leadlion\PersoanaJuridica\Helper\Data;
use Magento\Directory\Model\ResourceModel\Region\CollectionFactory;
use Magento\Framework\Api\AbstractSimpleObject;
use Magento\Framework\App\CacheInterface;
use \Magento\Framework\Serialize\Serializer\Json;
use Leadlion\PersoanaJuridica\Helper\Tools;

class Mfinante extends AbstractSimpleObject
{
    const CACHE_KEY= "leadlion_mfinante/";
    const SERVER = 'https://api.openapi.ro/api/companies/';
    const FIELD_MAP = [
        'adresa' => 'street.0',
        'denumire' => 'company',
        'judet' => 'region_id',
        'numar_reg_com' => 'fax',

    ];
    /**
     * @var string
     */
    protected $_endpoint;

    /**
     * @var array
     */
    protected $_params;

    /**
     * @var string
     */
    protected $logFileName = 'api_call.log';

    protected $_serializer;
    protected $_regCollectionFactory;
    protected $_cache;

    protected $_helper;
    public $_config;

    public function __construct(
        Json $serializer,
        Data $helper,
        CollectionFactory $regCollectionFactory,
        CacheInterface $cache,
        array $data = []
    ) {
        $this->_data = $data;
        $this->_helper= $helper;
        $this->_serializer = $serializer;
        $this->_regCollectionFactory = $regCollectionFactory;
        $this->_cache = $cache;
        $this->_setConfigVars();
        $this->_setDefaultData();
        $this->_setAuth();
    }
    public function _apiCall()
    {

        $this->_setEndpoint();
        $this->_setCurlOptions();

        if (!$this->_get('endpoint')) {
            return false;
        }
        $response='';
        if ($this->_get('endpoint')) {
            $curl = curl_init();
            curl_setopt_array(
                $curl,
                $this->_get('curl_options')
            );
            $response = curl_exec($curl);
            curl_close($curl);
        }
        $this->setData('response', $response);
    }

    protected function _setCurlOptions()
    {

        $this->setData('curl_options', [
            CURLOPT_URL =>$this->_get('endpoint'),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST =>  $this->_get('method'),
            CURLOPT_HTTPHEADER => $this->_get('headers'),
        ]);
    }

    protected function _setDefaultData()
    {
        if (!$this->_get('method')) {
            $this->setData('method', "GET");
        }
        if (!$this->_get('params')) {
            $this->setData('params', []);
        }
        if (!$this->_get('headers')) {
            $this->setData('headers', []);
        }
    }
    public function _getResponse()
    {
        $companyInfo =$this->loadDataFromCache();

        if(!$companyInfo){
            $this->_apiCall();
            $parsedResponse= $this->_serializer->unserialize($this->_get('response'));
            if(isset($parsedResponse['error'])){
                return [];
            }

            $regions = $this->_getRegionList();
            foreach (self::FIELD_MAP as $api_code => $mage_code){
                if(isset($parsedResponse[$api_code])){

                    if($mage_code == 'region_id'){
                        $companyInfo['region'] =Tools::remove_accents($parsedResponse[$api_code]);
                        if($parsedResponse[$api_code]=="Municipiul București"){
                            $parsedResponse[$api_code] ="Bucuresti";
                        }
                        $key = array_search(Tools::remove_accents($parsedResponse[$api_code]), $regions);
                        if($key === FALSE)
                        {
                            $parsedResponse[$api_code]='';
                        }
                        else
                        {
                            $parsedResponse[$api_code] =$key;
                        }


                    }
                    if($api_code == 'adresa'){
                        $splitAdresa=explode( ',',$parsedResponse[$api_code]);
                        $city=trim(end($splitAdresa));
                        $companyInfo['city'] =$city;
                    }


                    $companyInfo[$mage_code] = $parsedResponse[$api_code];
                }

            }
            $this->cacheData($companyInfo);
        }

        return $companyInfo;

    }
    protected function loadDataFromCache(){
        $data = $this->_cache->load(self::CACHE_KEY.$this->_get('cui'));
        if ($data) {
            $companyInfo = $this->_serializer->unserialize($data);
            return $companyInfo;
        }

        return [];
    }
    protected function cacheData($companyInfo){

        $data = $this->_serializer->serialize($companyInfo);
        $this->_cache->save($data, (self::CACHE_KEY.$this->_get('cui')));
    }

    protected function _getRegionList(){
        $regionCollection = $this->_regCollectionFactory->create();
        $regionCollection->addCountryFilter('RO')->load();
        foreach ($regionCollection as $region) {
            /** @var $region \Magento\Directory\Model\Region */
            if (!$region->getRegionId()) {
                continue;
            }
            $regions[$region->getRegionId()] =Tools::remove_accents((string)__($region->getName()));
        }
        return $regions;
    }
    protected function _setEndpoint()
    {
        $this->setData('endpoint', self::SERVER . $this->_get('cui'));
    }

    protected function _setAuth()
    {
        $this->setData('headers', ['x-api-key: '. $this->_config['api_key']]);
    }

    protected function _setConfigVars()
    {
        $this->_config['api_key'] =$this->_helper->getFieldConfig('/mfinante/api_key');
    }
}
