<?php

namespace modules\yandexkassa\classes\payment;

use payment\PaymentAPI;
use System\Exception;
use System\Logger;

class YandexKassaAPI extends PaymentAPI
{
    private $test_mode = 0;

    public function setFormAction(){
        if($this->test_mode) {
            $this->_form_action = 'https://demomoney.yandex.ru/eshop.xml';
        } else {
            $this->_form_action = 'https://money.yandex.ru/eshop.xml';
        }
    }

    public function getFormValues()
    {
        $fields            = $this->getFields();
        return $fields;
    }

    public function getFields()
    {

        $fields = array(
            'shopId'          => $this->_shop['shopId'],
            'scid'            => $this->_shop['scid'],
            'sum'             => $this->getAmount(),
            'orderNumber'     => $this->getId(),
            'customerNumber'  => $this->getId(),
            'shopSuccessURL'  => $this->getSuccessUrl(),
            'shopFailURL'     => $this->getFailUrl(),
            'paymentType'     => ''
        );

        return $fields;
    }

    public function getSign($fields)
    {
        $action                     = $fields['action'];
        $orderSumAmount             = $fields['orderSumAmount'];
        $orderSumCurrencyPaycash    = $fields['orderSumCurrencyPaycash'];
        $orderSumBankPaycash        = $fields['orderSumBankPaycash'];
        $shopId                     = $this->_shop['shopId'];
        $invoiceId                  = $fields['invoiceId'];
        $customerNumber             = $fields['customerNumber'];
        $shopPassword               = $this->_shop['password'];

        $sign = "$action;$orderSumAmount;$orderSumCurrencyPaycash;$orderSumBankPaycash;$shopId;$invoiceId;$customerNumber;$shopPassword";
       // Logger::log('Yandexkassa sign str:'.$sign);
        return strtoupper(md5($sign));

    }

    public function createPayment(array $options)
    {
        if(isset($options['test_mode']) && $options['test_mode']){
            $this->test_mode = 1;
        }

        return parent::createPayment($options); // TODO: Change the autogenerated stub
    }

    final protected function _checkSignature(array $source)
    {
        Logger::log('YandexKassa _checkSignature result '.($source['md5'] .'  ||=||  '. $this->getSign($source)));
        return $source['md5'] === $this->getSign($source);
    }

    public function getPayment()
    {
        $source = $_REQUEST;
        if ($this->_checkSignature($source))
            $this->verified = true;
        else {
            throw new Exception('Signature does not match the data');
        }

        $this->_id     = $source['orderNumber'];
        $this->_amount = $source['orderSumAmount'];

        return $this;

    }


}