<?php
/**
 * Backend exportu na Nehnutelnosti.sk.
 */
class Dalten_Export_Api_Backend_NehnutelnostiSk implements Dalten_Export_Api_Backend_LoggableBackendInterface
{
	protected $_login = '';
	protected $_apiKey = '';
	protected $_ico = '';

	/** @var  Dalten_Http_ClientInterface  */
	protected $_http;
	/** @var   Dalten_AddressConverter_NehnutelnostiSk_Interface Převodník adres. */
	protected $_addresConverter;
	/** @var Dalten_Export_NehnutelnostiSk */
	protected $_export;
	/** @var Serenity_Config_Config */
	protected $_config;
	/** @var Dalten_Export_Api_Backend_Logger_LoggerInterface */
	protected $_logger;

	function __construct(
		Dalten_Export_NehnutelnostiSk $export,
		Dalten_AddressConverter_NehnutelnostiSk_Interface $adressConverter,
		Serenity_Config_Config $config,
		Dalten_Http_ClientInterface $httpClient
	)
	{
		$this->_export = $export;
		$this->_addresConverter = $adressConverter;
		$this->_config = $config;
		$this->_http = $httpClient;
	}

	/**
	 * Nastaví přihlašovací údaje.
	 *
	 * @param string $login  Login
	 * @param string $apiKey API klíč.
	 * @param string $ico    IČO kanceláře.
	 */
	public function setLogin($login, $apiKey, $ico)
	{
		$this->_login = $login;
		$this->_apiKey = $apiKey;
		$this->_ico = $ico;
	}

	/**
	 * Odešle XML na
	 *
	 * @param string $xml  Data ve formátu XML.
	 * @param string $type Typ dat - brokers nebo advertisements.
	 *
	 * @return string Odpověď serveru (formátovaná jako XML).
	 */
	protected function _uploadXml($xml, $type)
	{
		$uploadUrl = sprintf('http://www.nehnutelnosti.sk/api/import/%s/',$this->_apiKey);

		return $this->_http->post(
			$uploadUrl,
			array(
				'data'=>$xml,
				'type'=>$type,
				'ico'=>$this->_ico,
				'username'=>$this->_login,
				'source'=>2
			)
		);
	}

	/**
	 * Přidá nebo smaže nemovitost na Nehnutelnosti.sk.
	 *
	 * To zda mažeme pozná server podle $listingData['delete'].
	 *
	 * @param array $listingData      Data nabídky.
	 * @param array $userData         Data makléře.
	 * @param array $images           Informace o obrázcích.
	 * @param array $additionalParams Další informace (nepoužívá se).
	 *
	 * @return Dalten_Xml_SimpleXml Odpověď serveru načtená do SimpleXML.
	 */
	public function addListing(array $listingData, array $userData, array $images = array(), array $additionalParams = array())
	{

		$listingData = $this->_addresConverter->convertAddress($listingData);
		$listingData['id_makler'] = $userData['id'];
		$data = $this->_export->convertEntityValues('nemovitost', $listingData, $this->_config->nemovitost);

		$xml = $this->_createXml($data, $images);
		if ($this->_logger) {
			$this->_logger->logRemoteCall('createXml', $xml);
		}

		$response =  $this->_uploadXml($xml, 'advertisements');
		$responseXml = simplexml_load_string($response, 'Dalten_Xml_SimpleXml');
		return $responseXml;
	}

	/**
	 * Přidá uživatele.
	 *
	 * @param array $userData Data makléře.
	 *
	 * @return string Odpověď serveru.
	 */
	public function addUser(array $userData)
	{
		$xml = new Dalten_Xml_SimpleXml('<makleri/>');
		$makler = $xml->addChild('makler');
		$makler->addChild('id', $userData['id']);
		$makler->addChild('meno', $userData['jmeno_cele']);
		$makler->addChild('fotka', $userData['foto_url']);
		$makler->addChild('telefon', $userData['telefon']);
		$makler->addChild('email', $userData['email']);
		if ($this->_logger) {
			$this->_logger->logRemoteCall('addUser.xml', $xml->getMultilineXml());
		}

		return $this->_uploadXml($xml->getMultilineXml(), 'brokers');
	}

	/**
	 * Vytvoří XML nabídky.
	 *
	 * @param array $data   Převedená data nabídky.
	 * @param array $images Data obrázků.
	 *
	 * @return string Hotové XML nabídky.
	 */
	protected function _createXml($data, $images=array())
	{
		$youtube = $data['youtube'];
		$lat = floatval($data['latitude']);
		$lon = floatval($data['longitude']);
		unset($data['youtube'], $data['latitude'], $data['longitude']);
		$xml = new Dalten_Xml_SimpleXml('<advertisements/>');
		$ad = $xml->addChild('advertisement');
		foreach ($data as $key=>$value) {
			if (is_string($value)) {
				$ad->addChild($key)->addCData($value);
			} else {
				$ad->addChild($key, $value);
			}
		}
		if (!empty($lat) && !empty($lon)) {
		    $gps = $ad->addChild('gps');
		    $gps->addChild('latitude', $data['latitude']);
		    $gps->addChild('longitude', $data['longitude']);
        }
		$photos = $ad->addChild('photos');
		foreach ($images as $ord=>$image) {
			// Nehnutelnosti.sk si nedokáží stáhnout fotky z HTTPS.
			$photos->addChild('photo', str_replace('https://skmaxis.remax-czech.cz/', 'http://skmaxis.remax-czech.cz/data_app/', $image['url']));
		}
		$videos = $ad->addChild('videos');
		if (!empty($youtube)) {
			$videos->addChild('youtube', $youtube);
		}
		return $xml->getMultilineXml();
	}

	/**
	 * Nastaví logger pro backend.
	 *
	 * Logger bude použit pouze pokud to backend dovoluje.
	 *
	 * @param \Dalten_Export_Api_Backend_Logger_LoggerInterface $logger Instance loggeru.
	 *
	 * @return Dalten_Export_Api_LoggableApiInterface Fluent interface.
	 */
	public function setLogger(Dalten_Export_Api_Backend_Logger_LoggerInterface $logger)
	{
		if ($this->_http instanceof Dalten_Export_Api_Backend_LoggableBackendInterface) {
			$this->_http->setLogger($logger);
		}
		$this->_logger = $logger;
		return $this;
	}

	/**
	 * Odstraní nastavený logger pro backend.
	 *
	 * @return Dalten_Export_Api_LoggableApiInterface Fluent interface.
	 */
	public function removeLogger()
	{
		if ($this->_http instanceof Dalten_Export_Api_Backend_LoggableBackendInterface) {
			$this->_http->removeLogger();
		}
		$this->_logger = null;
		return $this;
	}


}