<?php
/* * ********************************************************************************************
 * 								Open Real Estate
 * 								----------------
 * 	version				:	V1.36.0
 * 	copyright			:	(c) 2016 Monoray
 * 							http://monoray.net
 * 							http://monoray.ru
 *
 * 	website				:	http://open-real-estate.info/en
 *
 * 	contact us			:	http://open-real-estate.info/en/contact-us
 *
 * 	license:			:	http://open-real-estate.info/en/license
 * 							http://open-real-estate.info/ru/license
 *
 * This file is part of Open Real Estate
 *
 * ********************************************************************************************* */

class AtolApi
{

    protected $config = array();
    protected $isTest = 0;
    protected $apiVersion = 'v4';

    public function __construct($params = array())
    {
        if ($this->isTest) {
            // тестовый режим
            $this->config = array(
                'atolCmsLogin' => 'atoltest1',
                'atolCmsPass' => 'IOtiThGTL',
                'orgGroupCode' => 'ATOL-ProdTest-1',
                'orgInn' => '112233445573',
                'orgAddress' => 'г. Москва, ул. Оранжевая, д.22 к.11',
                'taxSystem' => 'osn',
                'taxNumber' => 'none',
            );
        } else {
            // боевой режим
            if (empty($params)) {
                throw new CHttpException(403, 'Невозможно инициализировать АТОЛ из указанных параметров');
                exit;
            }

            $this->config = $params;
        }
    }

    public function sendOperation($token, $id, $name, $amount, $clientEmail, $clientPhone = '')
    {

        // ограничить Name до 64 символов
        $name = mb_substr($name, 0, 64);
        if (!$name) {
            $name = tt('Платеж за услуги', 'payment');
        }
        $amount = floatval($amount);


        $groupCode = $this->config['orgGroupCode'];
        $inn = $this->config['orgInn'];
        $address = $this->config['orgAddress'];

        $sno = $this->config['taxSystem'];
        $taxNum = $this->config['taxNumber'];

        $url = 'https://online.atol.ru/possystem/' . $this->apiVersion . '/' . $groupCode . '/sell';

        $data = array(
            'external_id' => strval($id) . '_ore',
            'receipt' => array(
                'client' => array(
                    'email' => $clientEmail,
                    'phone' => $clientPhone,
                ),
                'company' => array(
                    'email' => param('adminEmail'),
                    'sno' => $sno,
                    'inn' => $inn . '_ore',
                    'payment_address' => $address,
                ),
                'items' => array(
                    array(
                        'name' => $name,
                        'price' => $amount,
                        'quantity' => 1,
                        'sum' => $amount,
                        'payment_method' => 'advance',
                        'payment_object' => 'service',
                        'vat' => array(
                            'type' => $taxNum,
                        ),
                    ),
                ),
                'payments' => array(
                    array(
                        'type' => 1,
                        'sum' => $amount,
                    ),
                ),
                'total' => $amount,
            ),
            'timestamp' => date('d.m.Y H:i:s'),
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $headers = array(
            'Content-type: application/json; charset=utf-8',
            'Token: ' . $token,
        );
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        curl_setopt($ch, CURLOPT_POSTFIELDS,  str_replace('_ore', '', json_encode($data, JSON_NUMERIC_CHECK)));
        $result = curl_exec($ch);

        $info = curl_getinfo($ch);

        curl_close($ch);
        $result = (array)json_decode($result);

        //print_r($result);

        $uuid = null;

        if (isset($result['uuid']) && $result['uuid'] && isset($result['status']) && $result['status'] == 'wait') {
            $uuid = $result['uuid'];
        } else {
            // logs
            logs('АТОЛ: не получен uuid');
            //logs($data);
            //logs($info);
            //logs($result);
        }
        return $uuid;
    }

    public function getToken()
    {

        $login = $this->config['atolCmsLogin'];
        $password = $this->config['atolCmsPass'];

        $ch = curl_init();
        $url = 'https://online.atol.ru/possystem/' . $this->apiVersion . '/getToken';
        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, 1);

        $post = array(
            'login' => $login,
            'pass' => $password,
        );

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $headers = array(
            'Content-type: application/json; charset=utf-8',
        );
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));

        $result = curl_exec($ch);
        $info = curl_getinfo($ch);

        curl_close($ch);
        $token = null;

        $result = (array)json_decode($result);
        if (isset($result['token']) && $result['token']) {
            $token = $result['token'];
        } else {
            logs('АТОЛ: не получен токен');
        }

        return $token;
    }

    public function getInfo($uuid, $token)
    {
        $groupCode = $this->config['orgGroupCode'];
        $url = 'https://online.atol.ru/possystem/' . $this->apiVersion . '/' . $groupCode . '/report/' . $uuid . '?token=' . $token;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $result = curl_exec($ch);
        $info = curl_getinfo($ch);

        print_r($url);
        print_r($result);
        print_r($info);

        curl_close($ch);

        $result = (array)json_decode($result);

        print_r($result);

        if (isset($result['status'])) {
            if ($result['status'] == 'error') {
                return 0;
            }
            if ($result['status'] == 'done') {
                return 1;
            }
        }
        return null;
    }

    public static function getTaxSystems()
    {
        return array(
            'osn' => tt('Common system', 'payment'),
            'usn_income' => tt('Simplified system (income)', 'payment'),
            'usn_income_outcome' => tt('Simplified system (income minus charges)', 'payment'),
            'envd' => tt('A single tax on imputed income', 'payment'),
            'esn' => tt('Unified agricultural tax', 'payment'),
            'patent' => tt('Patent system', 'payment'),
        );
    }

    public static function getTaxNumber()
    {
        return array(
            'none' => tt('Without VAT', 'payment'),
            'vat0' => tt('VAT 0%', 'payment'),
            'vat10' => tt('VAT 10%', 'payment'),
            'vat18' => tt('VAT 18%', 'payment'),
            'vat20' => tt('VAT 20%', 'payment'),
            'vat110' => tt('VAT 10/110', 'payment'),
            'vat118' => tt('VAT 18/118', 'payment'),
            'vat120' => tt('VAT 20/120', 'payment'),
        );

        # https://confluence.rficb.ru/pages/viewpage.action?pageId=11763807
        # https://github.com/mygento/kkm
    }

    public function getStatus($uuid = '')
    {
        $token = $this->atolApi->getToken();
        $this->atolApi->getInfo($uuid, $token);
    }
}
