<?php

namespace Mnv\Modules\Payment\Payme\Form;

use Mnv\Modules\Payment\PaymentMethodService;
use Mnv\Modules\Payment\PaymentMethodInterface;

/**
 * Class PayMeGenerationForm
 * @package Mnv\Api\Payment
 */
final class PayMeGenerationForm implements PaymentMethodInterface
{

    const CALLBACK = SITE_URL . '/callback/';
    private $merchant_id;
    private $mode;
    private $url;

    public function __construct()
    {
        $payment = new PaymentMethodService('payme');
        $this->mode     = $payment->payment_method['settings']['mode'];
        $this->merchant_id = $payment->payment_method['settings']['merchant'];

        $this->url = ($this->mode === 'live')
            ? $payment->payment_method['settings']['checkout_url']
            : $payment->payment_method['settings']['checkout_url_test'];

    }

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

		$fields = $this->fields($payment);
return <<<FORM
    <form action="{$this->url}" method="post" id="paymentform">
    {$fields}
    </form>
    <script type="text/javascript">
       document.getElementById("paymentform").submit();
    </script>
FORM;
	}

    public function fields($payment): ?string
    {

//        $currency = $currency_code->row['currency_code'];
//
//        if($currency == 'UZS') $currency = 860;
//        else if($currency == 'USD') $currency = 840;
//        else if($currency == 'RUB') $currency = 643;
//        else if($currency == 'EUR') $currency = 978;
//        else                        $currency = 860;

		$note       = join(', ', $payment['note']);

		$fields = array(
			'merchant'          => $this->merchant_id,
			'amount'            => round(1 * $payment['amount'] * 100),
			'account[order_id]' => $payment['order_id'],
            // НЕ ОБЯЗАТЕЛЬНЫЕ ПОЛЯ
            'currency'			=> 860,
			'lang'              => $payment['lang'],
			'callback'          => SITE_URL . '/user/payment-success/', //$CALLBACK.'?order_id='.$payment['order_id'],
			'callback_timeout'  => 0,
		);

		$html = '';

		foreach ($fields as $field => $val) {
			$html .= '<input type="hidden" name="' . $field . '" value="' . $val . '" />';
		}
		return $html;
	}
}

/*
<form name="payme" method="POST" action="https://checkout.paycom.uz/" id="PaymentPaycom" target="_blank">
    <input type="hidden" name="merchant"          value="5b9c8c32e641de247e63d491">
    <input type="hidden" name="account[order_id]" value="'.$order_id.'">
    <input type="hidden" name="amount"            value="'.$cartsAmount.'00">
    <input type="hidden" name="callback"          value="'.SITE_URL.'/success.htm" />
    <input type="hidden" name="lang"              value="ru">
    <input type="hidden" name="button" data-type="svg" value="colored">
    <button type="submit" class="btn-res hidden"></button>
</form>
<script src="https://cdn.paycom.uz/integration/js/checkout.min.js"></script>
*/




