<?php

namespace Mnv\Modules\Payment\Click\Form;

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

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

//    const RETURN_URL = SITE_URL.'/api-click.php';

    private $MERCHANTID;
    private $SERVICEID;
    private $SECTETKEY;

    private $url = 'https://my.click.uz/pay/';

    public function __construct()
    {
        $payment = new PaymentMethodService('click');
        $this->MERCHANTID = $payment->payment_method['settings']['merchant_id'];
        $this->SERVICEID  = $payment->payment_method['settings']['service_id'];
        $this->SECTETKEY  = $payment->payment_method['settings']['secret_key'];

        $this->url = 'https://my.click.uz/pay/';
    }

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

		$fields = $this->fields($payment);
        $button = '<button type="submit" class="send">Перейти к оплате</button>';
        $auto = '';
        if ($payment['auto']) {
            $button = '';
            $auto = '<script type="text/javascript">clickuz.submit();</script>';
        }
        return  <<<HTML
<form action="{$this->url}" name="clickuz" method="post" target="_blank">
{$fields}
{$button}
</form>
{$auto}
HTML;


//       $this->pay($orderId, $amount);
	}


	public function fields($payment): string
    {

		$date   = date("Y-m-d h:i:s");
		$amount = number_format($payment['amount'], 2, '.', '');
       
		$fields = array(
			'MERCHANT_ID'           => $this->MERCHANTID,
			'MERCHANT_SERVICE_ID'   => $this->SERVICEID,
			'MERCHANT_TRANS_ID'     => $payment['order_id'],
			'MERCHANT_TRANS_AMOUNT' => $amount,
			'MERCHANT_TRANS_NOTE'   => join(', ', $payment['note']),
			'MERCHANT_USER_PHONE'   => $payment['user_phone'],
			'MERCHANT_USER_EMAIL'   => $payment['user_email'],
			'SIGN_TIME'             => $date,
			'SIGN_STRING'           => md5($date . $this->SECTETKEY . $this->SERVICEID . $payment['order_id'] . $amount),
			'RETURN_URL'            => SITE_URL,
		);
        
		$html = '';

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

		return $html;
	}



    public function pay(int $orderId, float $amount)
    {

        $date   = date("Y-m-d h:i:s");
        $amount = number_format($amount, 2, '.', '');

        $query_vars = array(
            'service_id'        => $this->SERVICEID,
            'merchant_id'       => $this->MERCHANTID,
            'amount'            => $amount,
            'transaction_param' => $orderId,
            'source'            => 'lifestyle',
            'return_url'        => SITE_URL
        );
        $pay_url = 'https://my.click.uz/services/pay?' . http_build_query($query_vars, '', '&');

        header('Location: ' . $pay_url);

        exit;
    }
	
}


