<?php

class AutomaticImportWinoraConnect
{
    private $loginid;
    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;
    private $TotalCount;
    private $BaseUrl;
    private $StepSize = 1;
    private $xml;

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

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

        return $this->xml;
    }

    public function __set($name, $value)
    {
        switch ($name) {
            case 'loginid':
                $this->loginid = $value;
                break;
            case 'Password':
                $this->Password = $value;
                break;
            case 'TotalCount':
                $this->TotalCount = $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 'loginid':
                return $this->loginid;
                break;
            case 'Password':
                return $this->Password;
                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 = 10;
        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 initCommunication()
    {
        $xml = self::downloadXmlFile($this->BaseUrl."?loginid={$this->loginid}&password={$this->Password}&processtype=searchcatalog&pagesize={$this->N}&page=0");
        $url_xml = new SimpleXMLElement($xml);
        $processstatus = $url_xml->xpath('//processstatus');
        $processmessage = $url_xml->xpath('//processmessage');
        if ($processstatus[0] != 0) {
            throw new Exception('Response code: '.$processmessage[0]);
        }

        if (empty($this->TotalCount)) {
            $this->TotalCount = intval($url_xml->xpath('//ofpages')[0]);
        }
    }

    private function getItemsDetails()
    {
        $start = 1;

        $this->xml = new SimpleXMLElement('<xml></xml>', 0);
        do {
            try {
                $url = $this->BaseUrl."?loginid={$this->loginid}&password={$this->Password}&processtype=searchcatalog&pagesize={$this->N}&page={$start}";
                $data = self::downloadXmlFile($url);
                $url_xml = new SimpleXMLElement($data);

                foreach ($url_xml->item as $url_item) {
                    $item = $this->xml->addChild('SHOPITEM');
                    $item->addChild('CODE', $url_item->number);
                    $item->addChild('PRICE', $url_item->unitprice);
                    $item->addChild('AVAILABILITY', $url_item->availablestatus);
                    $item->addChild('IN_STORE', $url_item->quantity);
                }
            } catch (Exception $e) {
                print_r($e->getMessage()."\n");
            }
            $start += $this->stepSize;
        } while ($start < $this->TotalCount + 1);
    }
}
