<?php

namespace Mnv\Modules\Payment\Paybox\Form;


use Mnv\Modules\Payment\Paybox\PayBoxApi;
use Mnv\Modules\Payment\Paybox\PG_Signature;
use Mnv\Modules\Payment\PaymentMethodInterface;
use Mnv\Modules\Payment\PaymentMethodService;

class PayboxGenerationForm implements PaymentMethodInterface
{

    private $paybox;
    private $ACCOUNT;
    private $SERVICE;

    public function __construct()
    {
        $payment = new PaymentMethodService('paybox');
        $this->ACCOUNT = $payment->payment_method['settings']['merchant'];
        $this->SERVICE = $payment->payment_method['settings']['service'];


        $this->paybox = new PayBoxApi();
        $this->paybox->getDefaultCurrency();
    }

    public function form($payment): ?string
    {
        if (!$payment['order_id']) return null;

        $button = '<button type="submit" class="send">Перейти к оплате</button>';
        if ($payment['auto']) {
            $button = '';
            $auto = '<script type="text/javascript">payboxPayment.submit()</script>';
        }

        $fields = $this->fields($payment);

        return <<<HTML
<form action='https://api.paybox.money/payment.php' name="payboxPayment" method="POST" target="_blank">

{$fields}
{$button}
</form>
{$auto}
HTML;
    }

    public function fields($payment): ?string
    {

// TODO: 2 конвертировать `$amount` в валюту
        $amount = $this->paybox->convertMoney($payment['amount']);

//        print_r($amount);
//        print_r($this->paybox->currency);

        $success_url = GLOBAL_URL.'/callback_success/'; // пока не известно
        $failure_url = GLOBAL_URL.'/callback_failure/';
        $server_url = GLOBAL_URL.'/payments/paybox/index.php';

        $arrFields = array(
            'pg_merchant_id'		=> PayBoxApi::MERCHANTID,
            'pg_order_id'			=> $payment['order_id'],
            'pg_currency'			=> $this->paybox->currency,
            'pg_amount'				=> number_format($amount, 2, '.', ''), // intval($amount),
            'pg_lifetime'			=> (PayBoxApi::TRANSACTION_LIFETIME) ? PayBoxApi::TRANSACTION_LIFETIME*60 : 0,
            'pg_testing_mode'		=> (PayBoxApi::MODE  == 'sandbox') ? 1 : 0 ,
            'pg_description'		=> 'Покупка в интернет магазине "PowerGym". Номер заказа #'.$payment['order_id'],  //$strDescription,
            'pg_user_ip'			=> $_SERVER['REMOTE_ADDR'],
            'pg_language'			=> $payment['lang'],
            'pg_check_url'			=> $server_url,
            'pg_result_url'			=> $server_url,
            'pg_success_url'		=> $success_url,
            'pg_failure_url'		=> $failure_url,
            'pg_request_method'		=> 'GET',
            'cms_payment_module'	=> 'LS',
            'pg_salt'				=> rand(21,43433), // Параметры безопасности сообщения. Необходима генерация pg_salt и подписи сообщения.
        );

        if (!empty($payment['user_phone'])) {
            $arrFields['pg_user_phone'] = $payment['user_phone'];
        }

        if (!empty($payment['user_email'])) {
            $arrFields['pg_user_email'] = $payment['user_email'];
            $arrFields['pg_user_contact_email'] = $payment['user_email'];
        }
        if (!empty($this->paybox->payment_system))
            $arrFields['pg_payment_system'] = $this->paybox->payment_system;

        // подпись
        $arrFields['pg_sig'] = PG_Signature::make('payment.php', $arrFields, PayBoxApi::SECTETKEY);


//        print_r($arrFields);

        $html = '';
        foreach ($arrFields as $strParamName => $strParamValue) {
            $html .= "<input type=hidden name='$strParamName' value='$strParamValue'>";
        }

        return $html;
    }
}