<?php

namespace App\Adapters\Payments;

class Monri extends AdapterAbstract
{

    // define gateway
    const GATEWAY = "Pikpay";

    public static function isAvailable()
    {
        return true;
    }

    // gateway url
    protected $_gatewayUrl = "https://ipgtest.monri.com/v2/form";

    // pikpay unique key
    protected $_key = "ru*B1";

    // pikpay authenticity token
    //protected $_authenticityToken;
    protected $_authenticityToken = "25c0655832df9f8cbd1e85e71ad3daf86c76d8fe";
    // gateway language
    protected $_language = 'HR';

    // mapping language frontend interface
    protected $_language_maps = [
        'HR' => "hr",
    ];

    // mapping to transfrom parameter from gateway
    protected $_defaults_params = [];

    // @var mapping currency
    protected $_currency_maps = [
        'USD' => "USD",
        'BAM' => "BAM",
        'EUR' => "EUR",
    ];
    protected $code  = 'pik_pay';

    protected $_order;

    // mapping payment methods
    protected $_method_maps = [
        'authorize' => "authorize",
        'purchase' => "purchase",
    ];

    // order items
    protected $_items = [];

    // construct the payment adapter
    public function __construct($params = [])
    {
        // parent::__construct($params);
        //load config values
        //$this->_key = config('app.pikpay_key');
        //  $this->_authenticityToken = config('app.pikpay_token');
        // set default values
        $this->_order = $params;
        $this->_defaults_params['authenticity_token'] = $this->_authenticityToken;
        $this->_defaults_params['currency'] = $this->_currency;
        $this->_defaults_params['language'] = $this->_language_maps[$this->_language];
        $this->_defaults_params['transaction_type'] = $this->_method_maps['purchase'];
    }

    // set to enable sandbox mode
    public function setSandboxMode($val)
    {
        $this->_sandbox = $val;
        if ($val === true) {
            $this->_gatewayUrl = str_replace("ipg.pikpay.ba", "ipgtest.monri.com", $this->_gatewayUrl);
        }
        return $this;
    }

    // get sandbox enable
    public function getSandboxMode()
    {
        return $this->_sandbox;
    }
    public function getRedirectUrl()
    {
        return route('shop.checkout.check');
    }

    // make initial payment request.
    public function initPayment($passed_extends = [])
    {
        // request data
        $extends = [
            'order_info' => $this->getItems(),
            'order_number' => $this->_order->id,
            'amount' => str_replace('.', '', $this->getAmount()),
            'digest' => $this->calculateDigest(),
            'ch_country' => 'BA',
            'ch_full_name' => $this->_order->customer_first_name.' '.$this->_order->customer_last_name,
            'ch_address' => $this->_order->customer_address .' '. $this->_order->customer_city ,
            'ch_zip' => $this->_order->customer_zip,
            'ch_phone' => $this->_order->customer_phone,
            'ch_email' => $this->_order->customer_email
        ];

        $extends = array_merge($extends, $passed_extends);
        $postdata = $this->build($extends);
        $form = $this->_makeFormPayment($postdata);
        $response['form'] = $form;

        echo $response['form'];
        // validate form data
        /*if ($this->getAmount() > 0 && is_array($this->_order)) {
            $response['status'] = true;
           // $response['token'] = $this->calculateResponseDigest();
            $response['form'] = $form;
        } else {
            $response['status'] = false;
        }*/

        return $response;
    }

    // make verification request and return status
    public function verifyPayment($passed_extends = [])
    {
        // check response url parameters status
        $digest = $this->calculateResponseDigest($_GET['order_number']);
        $response['raw_response'] = $_SERVER['REQUEST_URI'];
        if ($digest == $_GET['digest'] && $_GET['response_code'] === '0000') {
            $response['status'] = true;
        } else {
            $response['status'] = false;
        }
        return $response;
    }

    // complete payment request.
    public function completePayment($passed_extends = [])
    {
        // request data
        $response['status'] = true;
        return $response;
    }

    // generate link and redirect to payment gateway page
    public function redirectToPaymentGateway($response)
    {
        return null;
    }

    // set payment order items
    public function setItems()
    {
        $this->_items = "";
        $this->_items = 'SHOPKO';
    }

    // get payment order items
    public function getItems()
    {
        // due description length limit substr items list
        if (strlen($this->_items) > 95) {
            $this->_items = trim(substr($this->_items, 0, 95));
        }
        return strip_tags($this->_items);
    }

    // build array data and mapping from API.
    public function build($extends = [])
    {
        $build_data = array_merge($this->_defaults_params, $extends);
        $build_data = array_change_key_case($build_data, CASE_LOWER);
        return $build_data;
    }

    // calculate digest
    public function calculateDigest()
    {
        $amount = str_replace('.', '', $this->getAmount());
        return $this->digestV2($this->_key, $this->_order->id, $amount, $this->_currency);
    }

    // calculate response digest
    // its digest returned by payment gateway
    // this will be used as transaction token as well
    public function calculateResponseDigest($order_id = null)
    {


        // initial order id or passed value
        if (is_null($order_id)) {
            $order_id = $this->_order->id;
        }
        return sha512($this->_key . $order_id);
    }

    // render from data with hidden fields.
    public function render($attrs = [])
    {
        $data = $this->build($attrs);
        return $this->_makeFormPayment($data);
    }

    public function digestV2($key, $orderNumber, $amount, $currency)
    {
        return hash('sha512', $key . $orderNumber . $amount . $currency);
    }
}
