<?php
class Dalten_Export_Api_Backend_CeskerealityThree implements Dalten_Export_Api_Backend_LoggableBackendInterface
{
    /** @var Dalten_Export_Api_Backend_Logger_LoggerInterface|null */
    protected $_logger;

    /** @var Dalten_Http_Client */
    protected $_httpClient;

    public function __construct(Dalten_Http_Client $httpClient)
    {
        $this->_httpClient = $httpClient;
    }

    // viz https://import.ceskereality.cz/specifikace/
    // getAccessToken získá token
    // getCompaniesList napáruje firmy (dle IČO)
    // uploadXml uploaduje soubory
    // importXml zahájí export

    public function getAccessToken($clientId, $clientSecret)
    {
        $this->_httpClient->setHeader('Authorization', null);
        $this->_httpClient->setAuth($clientId, $clientSecret);
        $data = $this->_httpClient->post('https://import.ceskereality.cz/token.php', array('grant_type' => 'client_credentials'));

        if(!$data){
            return false;
        }
        $data = json_decode($data, true);

        if ($data && !empty($data['ceskereality']['code']) && $data['ceskereality']['code']==222) {
            $this->_httpClient->setAuth(null, null); // teď už budeme používat Authorization Bearer token
            return $data['ceskereality']['access_token'];
        }

        return false;
    }

    public function getCompaniesList($accessToken)
    {
        $this->_httpClient->setHeader('Authorization', 'Bearer ' . $accessToken);
        $data = $this->_httpClient->get('https://import.ceskereality.cz/rk.html');

        if(!$data){
            return false;
        }
        $data = json_decode($data, true);

        if ($data && !empty($data['ceskereality'])) {
            if (isset($data['ceskereality']['status']) && $data['ceskereality']['status']=='error') {
                return false;
            }
            return $data['ceskereality'];
        }

        return false;
    }

    public function uploadXml($accessToken, $idFirmy, $file, $rename=null)
    {
        $ext = pathinfo($file, PATHINFO_EXTENSION);
        $postdata=array();

        if ($rename) $ext = pathinfo($rename, PATHINFO_EXTENSION);
        if (!$rename) $rename = pathinfo($file, PATHINFO_BASENAME);

        if ($ext=='jpg') {
            $postdata['s']  = new CURLFile($file,'image/jpeg', $rename);
        } elseif ($ext=='xml') {
            $postdata['s']  = new CURLFile($file,'text/xml', $rename);
            if (isset($this->_logger)) {
                $this->_logger->logRemoteCall($rename, file_get_contents($file));
            }
        } elseif ($ext=='pdf') {
            $postdata['s']  =new CURLFile($file,'application/pdf', $rename);
        } else {
            return false;
        }

        $this->_httpClient->setHeader('Authorization', 'Bearer ' . $accessToken);
        $data = $this->_httpClient->post('https://import.ceskereality.cz/uloz_xml.html?id_firmy='. $idFirmy, array(), $postdata);

        $data = json_decode($data, true);

        if ($data && !empty($data['ceskereality'][0]['status'])) {
            return $data['ceskereality'][0]['status']=='success';
        }

        return false;
    }

    public function importXml($accessToken, $idFirmy)
    {
        $this->_httpClient->setHeader('Authorization', 'Bearer ' . $accessToken);
        $data = $this->_httpClient->get('https://import.ceskereality.cz/import_xml.html?id_firmy=' . $idFirmy);

        $data = json_decode($data, true);

        $errors = [];

        if ($data && is_array($data['ceskereality'])) {
            foreach ($data['ceskereality'] as $message) {
            	if ($message['status']=='error') {
            		$errors[] = $message['details'];
	            }
	            if ($message['status']=='success') {
	            	return [
	            		'status'=>true,
			            'url'=>isset($message['url_inzeratu']) ? $message['url_inzeratu'] : '' // kvůli použití při topování
		            ];
	            }
            }
        }

        if (count($errors)) {
        	return [
        		'status'=>false,
		        'msg'=>$errors
	        ];
        }

        return false;
    }

    public function dailyStats($accessToken, $idFirmy, $datum)
    {
        $this->_httpClient->setHeader('Authorization', 'Bearer ' . $accessToken);
        $data = $this->_httpClient->get('https://import.ceskereality.cz/statistiky/statistiky.html?id_firmy=' . $idFirmy . '&den=' . $datum);

        $data = json_decode($data, true);

        if (!empty($data['ceskereality']) && !empty($data['ceskereality']['nemovitosti'])) {
            return [
                'status'=>true,
                'msg'=>'OK',
                'data'=>$data['ceskereality']['nemovitosti']
            ];
        } else {
            return [
                'status'=>false,
                'msg'=>'Nenanelezeny nemovitosti!',
            ];
        }
    }

    public function dailyEnquiries($accessToken, $idFirmy, $datum)
    {
        $this->_httpClient->setHeader('Authorization', 'Bearer ' . $accessToken);
        $data = $this->_httpClient->get('https://import.ceskereality.cz/statistiky/zadosti_k_nemovitostem.html?id_firmy='.$idFirmy.'&od='.$datum.'&do='.$datum);

        $data = json_decode($data, true);

        if (!empty($data['ceskereality']) && !empty($data['ceskereality']['zadosti'])) {
            return [
                'status' => true,
                'msg' => 'OK',
                'data' => $data['ceskereality']['zadosti']
            ];
        } elseif (!empty($data['ceskereality'])) {
            return [
                'status' => true,
                'msg' => 'Nejsou data.',
                'data' => []
            ];
        } else {
            return [
                'status'=>false,
                'msg'=>'Chyba!',
            ];
        }
    }

    public function listListings($accessToken, $idFirmy)
    {
        $this->_httpClient->setHeader('Authorization', 'Bearer ' . $accessToken);
        $data = $this->_httpClient->get('https://import.ceskereality.cz/vypis_nemovitosti.html?id_firmy='.$idFirmy);

        $data = json_decode($data, true);

        if (!empty($data['ceskereality']) && empty($data['ceskereality'][0]['status'])) {
            return [
                'status' => true,
                'msg' => 'OK',
                'data' => $data['ceskereality']
            ];
        } elseif (!empty($data['ceskereality'][0]['status'])) {
            return [
                'status' => false,
                'msg' => $data['ceskereality'][0]['details'],
                'data' => []
            ];
        } else {
            return [
                'status'=>false,
                'msg'=>'Jiná chyba!',
            ];
        }
    }

    public function setLogger(Dalten_Export_Api_Backend_Logger_LoggerInterface $logger)
    {
        $this->_logger = $logger;
        $this->_httpClient->setLogger($logger);
    }

    public function removeLogger()
    {
        $this->_logger = null;
        $this->_httpClient->removeLogger();
    }
}
