<?php

namespace Icetech\Payment\Gateway;


use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;

/**
 * Banca Transilvania Payment Gateway.
 *
 * (c) Draga Sergiu 05/2019
 * (c) Icetech 2018
 *
 */
class Euplatesc extends PaymentGateway
{

    protected $status = [
        'confirmed_pending' => self::STATUS_PENDING, // transaction is pending review. After this is done, a new IPN request will be sent with either confirmation or cancellation
        'paid_pending' => self::STATUS_PENDING, // transaction is pending review. After this is done, a new IPN request will be sent with either confirmation or cancellation
        'paid' => self::STATUS_PREAUTHORIZED, // transaction is pending authorization. After this is done, a new IPN request will be sent with either confirmation or cancellation
        'refunded' => self::STATUS_REFUNDED, // transaction has been refunded

        'DEPOSITED' => self::STATUS_PAID,
        'APPROVED' => self::STATUS_PREAUTHORIZED,

//        0 => self::STATUS_PAID, // transaction is finalized, the money have been captured from the customer's account
        0 => self::STATUS_PAID, // cos we have only 2 steps here.
//        0 => self::STATUS_PREAUTHORIZED,
        1 => self::STATUS_CANCELED,
        2 => self::STATUS_CANCELED,
        3 => self::STATUS_ERROR,
        '00' => self::STATUS_PREAUTHORIZED,
    ];

    protected $errors = [
        0 => 'tranzactie aprobata',
        1 => 'tranzactie duplicata',
        2 => 'tranzatie respinsa',
        3 => 'eroare de procesare',
    ];

    public function __construct()
    {
        parent::__construct();
        require_once 'vendor/Librapay/Handler.php';
    }

    public function getContactKeyMappings()
    {
        return [
            'firstName' => 'firstname',
            'lastName' => 'lastname',
            'address' => 'address',
            'email' => 'email',
            'phone' => 'phone',
            'country' => ['country', 'name'],
            'county' => ['county', 'name'],
            'city' => 'city',
            'zipCode' => 'postalcode',
        ];
    }

    public function getOrderIdParamName()
    {
        return 'order';
    }

    /**
     * Libra requirements:
     * It must contain exactly 2 decimals separated by dot. Thousands
     * must NOT be separated by comma.
     *
     * @param $value
     * @return PaymentGateway
     */
    public function setAmount($value)
    {
        return parent::setAmount(number_format((float)$value, 2, '.', ''));
    }


    public function basicConfig()
    {
        return [
            'curr' => $this->currency,
            'merch_id' => $this->merchant_id,
            'timestamp' => date('YmdHis'),
            'nonce'       => md5(mt_rand().time()),
        ];
    }


    public function generatePurchaseParams()
    {
        $data = [];

        $data['amount'] = $this->amount;
        $data['invoice_id'] = $this->order_id;
        $data['order_desc'] = "Comanda online #" . $this->order_id;

        $data['fp_hash'] = strtoupper($this->generateEuplatescMac($data, $this->key));

       $data['ExtraData'] = [
           'silenturl' => $this->confirm_url,
           'successurl' => $this->return_url,
           'failedurl' => $this->return_url,
           'ep_method' => 'post',
       ];


        $x = $this->connect($data);
        dd($x);
    }


    public function response()
    {

        return 'OK';
        $handler = new \Handler($this->basicConfig());

        $post_data = request()->all();
        $handler->terminal = $post_data["TERMINAL"];
        $handler->trtype = $post_data["TRTYPE"];
        $handler->order = $post_data["ORDER"];
        $handler->amount = $post_data["AMOUNT"];
        $handler->currency = $post_data["CURRENCY"];
        $handler->desc = $post_data["DESC"];
        $handler->action = $post_data["ACTION"];
        $handler->rc = $post_data["RC"];
        $handler->message = $post_data["MESSAGE"];
        $handler->rrn = $post_data["RRN"];
        $handler->int_ref = $post_data["INT_REF"];
        $handler->approval = $post_data["APPROVAL"];
        $handler->timestamp = $post_data["TIMESTAMP"];
        $handler->nonce = $post_data["NONCE"];

        $handler->getString("preAuthResponse");
        $handler->getHexKey();
        $handler->getPsign();

        if (empty($handler->order)) {
            dd($handler);
        }

        // validate psign
        if ($post_data["P_SIGN"] != $handler->psign) {
            dd("Zona interzisa!");
        }

        // 1. set orderId
        $this->setOrderId($handler->order);


        // 2. set responseData.
        $this->setResponseData([
            'error_code' => $handler->action,
            'error_message' => $handler->message,
            'action' => $handler->action,
            'raw' => $post_data,
        ]);


        return $this;
    }

    public function callbackOutput()
    {
        // @quikdamnfix
        if (request()->method() === 'GET') {
            return redirect()->route('payment.status', [
                $this->getOrderIdParamName() => $this->order_id,
            ]);
        }

        if ($this->response->hasError()) {
            Log::info('SITE_ERR', request()->all());
            return response('1');
        } else {
//            Log::info('PAYMENT', [request()->all(), 'method' => request()->method()]);
        }

        return response('1');
    }

    public function connect(array $params)
    {
        $client = new Client([
            'verify' => false
        ]);


        $response = $client->request('POST', $this->endpoint_url,  [
            'form_params' => $this->basicConfig() + $params,
        ]);

        return json_decode($response->getBody()->getContents());
    }

    function generateEuplatescMac($data, $key){
        $str = NULL;
        foreach($data as $d){
            if($d === NULL || strlen($d) == 0){
                $str .= '-';
            }else{
                $str .= strlen($d) . $d;
            }
        }
        return hash_hmac('MD5',$str, pack('H*', $key));
    }


}
