<?php

/**
 * @author   Petr Knap <knap@wpj.cz>
 *
 * @since    2013-03-08
 *
 * @category kupshop
 *
 * @version  1.3
 */
class AutomaticImportCycloConnect
{
    private $BuyersID;
    private $Password;
    private $SaveTo;
    private $UserAgent = 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0; chromeframe/11.0.696.57)';
    private $N = 3;
    private $TotalCount;
    private $TransactionID;
    private $data;
    private $BaseUrl;
    private $InitUrl = '?RequestName=CreateTextSearchRequest&SearchString=';
    private $NextUrl = '?RequestName=SearchResultRequest&ResultFormat=ITEM_DETAIL';
    private $StepSize = 200;

    public function __construct($BuyersID = null, $Password = null)
    {
        $this->BuyersID = $BuyersID;
        $this->Password = $Password;
    }

    public function Run()
    {
        self::initCommunication();
        self::getItemsDetails();
        self::saveXML();
    }

    public function __set($name, $value)
    {
        switch ($name) {
            case 'BuyersID':
                $this->BuyersID = $value;
                break;
            case 'Password':
                $this->Password = $value;
                break;
            case 'SaveTo':
                $this->SaveTo = $value;
                break;
            case 'UserAgent':
                $this->UserAgent = $value;
                break;
            case 'N':
                $this->N = $value;
                break;
            case 'BaseUrl':
                $this->BaseUrl = $value;
                break;
            case 'stepSize':
                $this->StepSize = $value;
                break;
            default:
                throw new Exception('Variable '.$name.' not found.');
        }
    }

    public function __get($name)
    {
        switch ($name) {
            case 'BuyersID':
                return $this->BuyersID;
                break;
            case 'Password':
                return $this->Password;
                break;
            case 'SaveTo':
                return $this->SaveTo;
                break;
            case 'UserAgent':
                return $this->UserAgent;
                break;
            case 'N':
                return $this->N;
                break;
            case 'BaseUrl':
                return $this->BaseUrl;
                break;
            case 'stepSize':
                return $this->StepSize;
                break;
            default:
                throw new Exception('Variable '.$name.' not found.');
        }
    }

    private function downloadXmlFile($url)
    {
        $stop = $this->N;
        do {
            $curl = curl_init();

            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 600);
            curl_setopt($curl, CURLOPT_USERAGENT, $this->UserAgent);
            curl_setopt($curl, CURLOPT_FAILONERROR, true);
            // curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($curl, CURLOPT_AUTOREFERER, true);
            curl_setopt($curl, CURLOPT_TIMEOUT, 1200);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

            $data = curl_exec($curl);
            curl_close($curl);

            $stop--;
        } while ($data == '' && $stop > 0);
        if ($data == '') {
            throw new Exception('Blank file was downloaded from '.$url.'.');
        }

        return $data;
    }

    private function saveXML($SaveTo = null)
    {
        if ($SaveTo === null) {
            $SaveTo = $this->SaveTo;
        }
        file_put_contents($SaveTo, $this->data);
    }

    private function initCommunication()
    {
        $this->data = self::downloadXmlFile($this->BaseUrl.$this->InitUrl.'&BuyersID='.$this->BuyersID.'&Password='.$this->Password);
        $this->data = new SimpleXMLElement($this->data);
        $responseCode = $this->data->xpath('vct:ResponseCode');
        $responseCode = $responseCode[0];
        if ($responseCode != 200) {
            throw new Exception('Response code: '.$responseCode);
        }
        $transactionID = $this->data->xpath('vct:TransactionID');
        $this->TransactionID = $transactionID[0];
        $totalCount = $this->data->xpath('vcc:TotalCount');
        $this->TotalCount = $totalCount[0];
    }

    private function getItemsDetails()
    {
        $start = 0;
        $this->data = '<?xml version="1.0" encoding="utf-8"?><xml>';
        do {
            try {
                $data = self::downloadXmlFile($this->BaseUrl.$this->NextUrl.'&BuyersID='.$this->BuyersID.'&Password='.$this->Password.'&TransactionID='.$this->TransactionID.'&StartIndex='.$start.'&Count='.$this->StepSize);
                $ns = new SimpleXMLElement($data);
                $ns = $ns->getNamespaces(true);
                foreach ($ns as $prefix => $name) {
                    $data = str_replace('<'.$prefix.':', '<', $data);
                    $data = str_replace('</'.$prefix.':', '</', $data);
                }
                $data = str_replace('<?', '<!-- ?', $data);
                $data = str_replace('?>', '? -->', $data);
                $this->data = $this->data.$data;
            } catch (Exception $e) {
                print_r($e->getMessage()."\n");
            }
            // sleep(90);
            $start += $this->stepSize;
        } while ($start < $this->TotalCount);
        $this->data = $this->data.'</xml>';
    }
}
