<?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 Robokassa extends PaymentSystem
{

    public $login;
    public $password1;
    public $password2;
    public $incCurrLabel;
    public $mode;
    public $text;
    public $useAtol;
    public $atolCmsLogin;
    public $atolCmsPass;
    public $orgGroupCode;
    public $orgInn;
    public $orgAddress;
    public $taxSystem;
    public $taxNumber;

    public static function workWithCurrency()
    {
        return array('RUR');
    }

//    public function init(){
//        $this->name = 'robokassa';
//        return parent::init();
//    }

    public function rules()
    {
        return array(
            array('login, password1, incCurrLabel, mode', 'required'),
            array('password2, useAtol, atolCmsLogin, atolCmsPass, orgGroupCode, orgInn, orgAddress, taxSystem, taxNumber', 'safe'),
        );
    }

    public function attributeLabels()
    {
        return array(
            'login' => tt('Login', 'payment'),
            'password1' => tt('Password 1', 'payment'),
            'password2' => tt('Password 2', 'payment'),
            'text' => tt('Description of the system', 'payment'),
            'mode' => tt('Mode', 'payment'),
            'incCurrLabel' => tt('Available payment methods', 'payment'),
            'useAtol' => tt('Use ATOL', 'payment'),
            'atolCmsLogin' => tt('ATOL CMS Login', 'payment'),
            'atolCmsPass' => tt('ATOL CMS Password', 'payment'),
            'orgGroupCode' => tt('Organization code', 'payment'),
            'orgInn' => tt('Organization INN', 'payment'),
            'orgAddress' => tt('Organization address', 'payment'),
            'taxSystem' => tt('Tax system', 'payment'),
            'taxNumber' => tt('Tax number', 'payment'),
        );
    }

    public function processRequest()
    {
        $return = array(
            'id' => 0,
        );
        $payment = (isset($_REQUEST["payment"])) ? $_REQUEST["payment"] : null;
        $outSum = (isset($_REQUEST["OutSum"])) ? $_REQUEST["OutSum"] : null;
        $invId = (isset($_REQUEST["InvId"])) ? $_REQUEST["InvId"] : null;
        $crc = isset($_REQUEST["SignatureValue"]) ? strtoupper($_REQUEST["SignatureValue"]) : '';

        if ($payment == "result") {
            $myCrc = strtoupper(md5("$outSum:$invId:$this->password2"));
        } else
            $myCrc = strtoupper(md5("$outSum:$invId:$this->password1"));

        if ($crc != $myCrc || $_REQUEST['payment'] == 'fail') {
            $return['result'] = 'fail';
            //if($_REQUEST['payment'] == 'fail' && $crc == $myCrc){
            $return['id'] = $invId;
            //}
        } else {
            $return['id'] = $invId;
            $return['result'] = 'success';
        }
        return $return;
    }

    public function echoSuccess()
    {
        if ($_REQUEST["payment"] == 'result') {
            echo("OK" . $_REQUEST["InvId"] . "\n");
            Yii::app()->end();
        }
    }

    public function processPayment(Payments $payment)
    {

        $workWithCurrency = self::workWithCurrency();
        if (!in_array($payment->currency_charcode, $workWithCurrency)) {
            $currency = $workWithCurrency[0];
            $amount = round(Currency::convert($payment->amount, $payment->currency_charcode, $currency), 0);
        } else {
            $amount = $payment->amount;
            //$currency = $payment->currency_charcode;
        }

        if ($payment->booking_id) {
            $description = tt('Purchase booking', 'booking');
            if ($payment->apartment_id && isset($payment->ad) && $payment->ad) {
                $description .= ' ' . $payment->ad->getStrByLang('title');
            }
        } elseif ($payment->paid_id && !is_null($payment->paid_id) && isset($payment->paidservice) && $payment->paidservice->name) {
            $description = Yii::t('module_payment', 'Paid service #{id} ({name}) with the price {price}', array('{id}' => $payment->id, '{name}' => $payment->paidservice->name, '{price}' => $payment->amount . ' ' . $payment->currency_charcode));
        } elseif (issetModule('tariffPlans') && $payment->tariff_id && isset($payment->tariffInfo) && $payment->tariffInfo->name) {
            $description = Yii::t('module_payment', 'Paid service #{id} ({name}) with the price {price}', array('{id}' => $payment->id, '{name}' => $payment->tariffInfo->name, '{price}' => $payment->amount . ' ' . $payment->currency_charcode));
        } else {
            $description = Yii::t('module_payment', 'Paid service #{id} ({name}) with the price {price}', array('{id}' => $payment->id, '{name}' => 'Add to balance', '{price}' => $payment->amount . ' ' . $payment->currency_charcode));
        }

        // https://docs.robokassa.ru/#6865
        /*$dataReceipt = array(
            'sno' => 'usn_income',
            'items' => array(
                array(
                    'name' => $description,
                    'quantity' => 1,
                    'sum' => $amount,
                    'tax' => 'none',
                ),
            )
        );
        $dataReceiptJsonEncode = urlencode(json_encode($dataReceipt));*/

        $sign = array(
            $this->login,
            $amount,
            $payment->id,
            //$dataReceiptJsonEncode,
            $this->password1,
        );

        $sign = md5(implode(':', $sign));

        $url = 'https://auth.robokassa.ru/Merchant/Index.aspx?';

        $data = array(
            'MrchLogin' => $this->login,
            'OutSum' => $amount,
            'InvId' => $payment->id,
            'Desc' => $description,
            'SignatureValue' => $sign,
            //'IncCurrLabel' => $this->incCurrLabel, # вроде как местами не работает при $this->incCurrLabel - all точно работает
            'IncCurrLabel' => 'all',
            'Email' => Yii::app()->user->email,
            'Culture' => Yii::app()->language, //'ru'
            //'Receipt' => $dataReceiptJsonEncode
            'IsTest' => $this->mode ? 0 : 1
        );

        //$form = $this->renderForm($url, $data);
        //echo $form;
        //exit;

        $url .= http_build_query($data);
        Yii::app()->controller->redirect($url);
    }

    public function printInfo()
    {

        ?>
        <br/>
        <ul>
            <li><?php
                echo Yii::t('module_payment', 'Result URL: ') .
                    (Yii::app()->controller->createAbsoluteUrl('/payment/main/income', array(
                        'sys' => 'robokassa',
                        'payment' => 'result',
                    ))
                    );

                ?>
            </li>
            <li><?php
                echo Yii::t('module_payment', 'Success URL: ') .
                    (Yii::app()->controller->createAbsoluteUrl('/payment/main/income', array(
                        'sys' => 'robokassa',
                        'payment' => 'success',
                    ))
                    );

                ?>
            </li>
            <li><?php
                echo Yii::t('module_payment', 'Fail URL: ') .
                    (Yii::app()->controller->createAbsoluteUrl('/payment/main/income', array(
                        'sys' => 'robokassa',
                        'payment' => 'fail',
                    ))
                    );

                ?>
            </li>
        </ul>
        <?php
    }

    private function renderForm($formUrl, array $formData) {
        $form = "<form action=\"$formUrl\" method=\"POST\">";

        foreach ($formData as $inputName => $inputValue) {
            $value = htmlspecialchars($inputValue, ENT_COMPAT, 'UTF-8');

            $form .= "<input type=\"hidden\" name=\"$inputName\" value=\"$value\">";
        }

        $form .= "<input type=\"submit\" value=\"Оплатить\"></form>";

        return $form;
    }
}
