<?php

namespace modules\robokassa\classes\payment;


use payment\PaymentAPI;
use System\Exception;

class RobokassaAPI extends  PaymentAPI
{
    public function setFormAction(){
        $this->_form_action = 'https://auth.robokassa.ru/Merchant/Index.aspx';
    }
  //  protected $_form_action = 'http://test.robokassa.ru/Index.aspx';

    public function getFormValues()
    {
        $fields                   = $this->getFields();
        $fields['SignatureValue'] = $this->getSign($fields);
        return $fields;
    }

    public function getFields()
    {
        $fields = array(
            'MrchLogin' => $this->_shop['merchant'],
            'OutSum'      => $this->getAmountAsString(),
            'InvId'    => $this->getId(),
            'Desc'  => $this->getDescription(),
            'Encoding' => 'utf-8',
            'IsTest' => $this->getTestMode()
        );

        $return_url = $this->getSuccessUrl();
        $status_url = $this->getStatusUrl();
        $curr       = $this->getCurrency();


        /*$fields['ext_details'] = (string)$this->getBaggage();

        if ($return_url) {
            $fields['return_url'] = (string)$return_url;
        }

        if ($status_url) {
            $fields['server_url'] = (string)$status_url;
        }

        if ($curr)
            $fields['ccy'] = (string)$curr;
        */

        return $fields;
    }

    public function getSign($fields)
    {
        $mrh_login  = $this->_shop['merchant'];
        $out_summ   = $this->getAmountAsString();
        $inv_id     = $this->getId();
        $mrh_pass1  = $this->_shop['password1'];

        return md5("$mrh_login:$out_summ:$inv_id:$mrh_pass1");

    }

    public function createPayment(array $options)
    {


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



        return $this;
    }

    final protected function _checkSignature(array $source)
    {

        return strtolower($source['SignatureValue']) === strtolower(md5(
            $source['OutSum'] . ':' .
            $source['InvId'] . ':' .
            $this->_shop['password2']));
    }

    public function getPayment()
    {

        $source = $_POST;

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

        $this->_id     = $source['InvId'];
        $this->_amount = $source['OutSum'];

        return $this;

    }



}