<?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'];

        // https://checkout.paycom.uz/ / использовать для теста https://test.paycom.uz

        if ($this->mode === 'live') {
            $this->url = $payment->payment_method['settings']['checkout_url'];
        } else {
            $this->url = $payment->payment_method['settings']['checkout_url_test'];
        }

    }

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

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

        $button = '<button type="submit"></button>';
        $auto = '';
        if ($payment['auto']) {
            $auto   = '<script type="text/javascript">paymentform.submit()</script>';
            $button = '';
        }
return <<<HTML
<form action="{$this->url}" method="post" name="paymentform" target="_blank">
{$fields}
{$button}
</form>
{$auto}
HTML;

	}

    public function fields($payment): ?string
    {

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

		$fields = array(
			'merchant'          => $this->merchant_id,
			'amount'            => $payment['amount'] . '00',
			'account[order_id]' => $payment['order_id'],
            // НЕ ОБЯЗАТЕЛЬНЫЕ ПОЛЯ
			'lang'              => $payment['lang'],
			'callback'          => SITE_URL //$CALLBACK.'?order_id='.$payment['order_id'],
		);

		$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>
*/




