<?php

namespace twa\omnipay\controllers;

use twa\omnipay\repositories\axepta;

class BNPController
{
    private $data;

    public function __construct($data, $provider)
    {
        $required_data = ['merchant_identification', 'hmac_key', 'blowfish'];
        \twa\omnipay\controllers\GeneralFunctions::checkRequiredData($data, $required_data);
        $this->data = collect($data);
    }

    public function createPayment($id, $value, $currency, $customer_name = null, $customer_email = null, $url_success = null, $url_cancel = null, $url_fail = null)
    {

        $success_url = env('APP_URL').'/omnipay/response/success/'.$id.'/'.md5('success'.env('APP_KEY').$id);

        $fail_url = env('APP_URL').'/omnipay/response/fail/'.$id.'/'.md5('fail'.env('APP_KEY').$id);

        $axepta = new axepta();
        $axepta->set_merchant_id($this->data['merchant_identification']);
        $axepta->set_hmac_key($this->data['hmac_key']);
        $axepta->set_blowfish_key($this->data['blowfish']);
        $axepta->set_transaction_id($id);
        $axepta->set_reference_number($id);
        $axepta->set_amount($value);
        $axepta->set_currency($currency);
        $axepta->set_url_notify(env('APP_URL').'/omnipay/webhook/'.$id.'/');
        $axepta->set_url_back(env('APP_URL'));
        $axepta->set_url_success($success_url);
        $axepta->set_url_failure($fail_url);
        $axepta->set_language(app()->getLocale());
        $axepta->process_request();
        $link = $axepta->get_form_action();

        return collect(['redirect' => ['link' => $link] , 'response' => [
            'successToken' => md5('success'.env('APP_KEY').$id) ]]);

    }

    public function checkPayment($id)
    {

        $parms = request()->all();

        try{
            $axepta = new axepta();
            $axepta->set_merchant_id($this->data['merchant_identification']);
            $axepta->set_hmac_key($this->data['hmac_key']);
            $axepta->set_blowfish_key($this->data['blowfish']);
            $axepta->process_response($parms);

            $res = $axepta->get_response_parameters();

            if($axepta->response_is_valid() && $axepta->response_is_successful()){
                return response(['status' => 'success', 'response' => $parms], 200);
            }else{
                return response(['status' => 'fail', 'response' => $parms], 400);
            }

        }catch(\Throwable $th){
            return response(['status' => 'fail', 'response' => $parms], 400);
        }


    }
}
