<?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 Librapay 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 [
            'merch_name' => $this->merchant_name,
            'merch_url' => $this->merchant_url,
            'email' => $this->email,
            'merchant' => $this->username,
            'key' => $this->password,
            'terminal' => $this->terminal,
//            'postAction' => $this->endpoint_url,
//            'backref' => $this->return_url,
            'backref' => $this->confirm_url,
        ];
    }


    public function generatePurchaseParams()
    {
        $handler = new \Handler($this->basicConfig());
        $handler->order = $this->order_id;
        $handler->amount = $this->amount;
        $handler->desc = "Comanda online #" . $this->order_id;

        $aditional_data = [
//            'ProductsData' => [
//                [
//                    'ItemName' => 'test',
//                    'Quantity' => 3,
//                    'Price' => 10.20,
//                ]
//            ],
            'UserData' => [
                'Email' => $this->details['email'],
                'Name' => "{$this->details['lastName']} {$this->details['firstName']}",
                'Phone' => $this->details['phone'],
            ],

        ];

        $handler->dataProducts = base64_encode(serialize($aditional_data));

        $handler->getParams();
//        dd($handler, $aditional_data, $handler->getParams());

        return $handler->getParams();
    }


    public function response()
    {

        $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');
    }


}
