<?php

namespace twa\omnipay\controllers;

use Illuminate\Support\Facades\Http;
use twa\ecomcart\models\EcomPurchasesAttemptModel;

class NGeniusController
{
    public $data;
    public $provider;

    public function __construct($data, $provider)
    {
        $this->provider = $provider;

        $required_data = ['apiKey', 'outletID'];
        \twa\omnipay\controllers\GeneralFunctions::checkRequiredData($data, $required_data);
        $this->data = collect($data);
    }

    public function getSession()
    {
        $curl_post_data = [ "grant_type" => "client_credentials" ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://api-gateway.sandbox.ngenius-payments.com/identity/auth/access-token");
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "accept: application/vnd.ni-identity.v1+json",
            "authorization: Basic ".$this->data['apiKey'],
            "content-type: application/vnd.ni-identity.v1+json"
        ));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,  "{\"realmName\":\"ni\"}");
        $output = json_decode(curl_exec($ch));
        if(isset($output->access_token)){
            return $output->access_token;
        }else{
            return NULL;
        }
    }

    public function createPayment($id, $value, $currency, $customer_name, $customer_email, $url_success, $url_cancel)
    {
        $session = $this->getSession();
        if (! $session) {
            dd('Unexpected Error: AirwallexController createPayment() : Invalid auth token');
        }
        $attempt=EcomPurchasesAttemptModel::find($id);
        if(!$attempt){
            return abort(404);
        }
        $currency = "AED";

        $json = json_encode([
            "action" => "SALE",
            "amount" => [
                "currencyCode" => $currency,
                "value" => $value*100
            ],
            "merchantAttributes"=>[
                "redirectUrl"=>$url_success,
                "skipConfirmationPage"=>true,
            ],
            "emailAddress"=>$customer_email,
            "billingAddress"=>[
                "firstName"=>$attempt['billing_address_details']['first_name'],
                "lastName"=>$attempt['billing_address_details']['last_name'],
                "address1"=>$attempt['billing_address_details']['country']['name'].",".$attempt['billing_address_details']['state'].",".$attempt['billing_address_details']['city'].",".$attempt['billing_address_details']['street'].",".$attempt['billing_address_details']['floor'].",".$attempt['billing_address_details']['building'],
                "city"=>$attempt['billing_address_details']['city'],
                "countryCode"=>$attempt['billing_address_details']['country']['code'],
            ]
        ]);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://api-gateway.sandbox.ngenius-payments.com/transactions/outlets/".$this->data['outletID']."/orders");
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "Authorization: Bearer ".$session,
            "Content-Type: application/vnd.ni-payment.v2+json",
            "Accept: application/vnd.ni-payment.v2+json"));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);

        $output = json_decode(curl_exec($ch));

        if(isset($output->reference) && isset($output->_links->payment->href)){
            return collect(['redirect' => ['link' => $output->_links->payment->href ], "id" => $output->reference ]);
        }else{
            return collect(['status' => 'fail', 'response' => $output]);
        }
    }

    public function checkPayment($attemptID)
    {
        $purchase_attempt = EcomPurchasesAttemptModel::find($attemptID);
        $orderReference = twaJsonDecode($purchase_attempt['gateway_init'])['id'];

        $session = $this->getSession();
        if (! $session) {
            dd('Unexpected Error: AirwallexController createPayment() : Invalid auth token');
        }


        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://api-gateway.sandbox.ngenius-payments.com/transactions/outlets/".$this->data['outletID']."/orders/".$orderReference,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_HTTPHEADER => array(
                "accept: application/vnd.ni-payment.v2+json",
                "Authorization: Bearer $session",
            ),
        ));

        $response = curl_exec($curl);
        $response=json_decode($response,1);



        if (count(collect($response['_embedded']['payment'])->where('state','CAPTURED'))>0) {
            return response(['status' => 'success', 'response' => $response], 200);
        } else {
            return response(['status' => 'fail', 'response' => $response], 400);
        }
    }
}
