<?php

namespace twa\omnipay\controllers;

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

class AirwallexController
{
    public $data;
    public $provider;

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

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

    public function getSession()
    {
        $response = Http::withHeaders([
            'x-client-id' => $this->data['client_id'],
            'x-api-key' => $this->data['api_key'],
        ])->post('https://api.airwallex.com/api/v1/authentication/login', []);

        if ($response->status() != '200' && $response->status() != '201') {
            return null;
        }

        return json_decode($response->body(), 1);
    }

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

        $token = $session['token'];

        $mdata = [
            'amount' => $value,
            'currency' => $currency,
            'merchant_order_id' => $id,
            'metadata.id' => $id,
            'request_id' => uniqid(),
            'return_url' => $url_success,
        ];

        $response = Http::withHeaders([
            'Authorization' => 'Bearer '.$token,
        ])->post('https://api.airwallex.com/api/v1/pa/payment_intents/create', $mdata);

        if ($response->status() != '200' && $response->status() != '201') {
            dd('Unexpected Error: AirwallexController createPayment() : unable to create order');
        }

        $response = json_decode($response->body());

        $intent_id = $response->id;
        $client_secret = $response->client_secret;

        return collect([
            'redirect' => [
                'link' => env('APP_URL').'/omnipay/redirect/airwallex/'.$id.'/'.$this->provider.'/'.$value.'/'.$currency.'/'.$intent_id.'/'.$client_secret.'/'.md5($id.$this->provider.$value.$currency.$intent_id.$client_secret.env('APP_KEY')).'?successUrl='.urlencode($url_success).'&failUrl='.urlencode($url_cancel),
            ],
            'view' => [
                'name' => 'OmniPayViews::airwallex.redirect',
                'parameters' => [
                    'id' => $id,
                    'provider' => $this->provider,
                    'amount' => $value,
                    'currency' => $currency,
                    'intent_id' => $intent_id,
                    'client_secret' => $client_secret,
                    'url_success' => $url_success,
                    'url_cancel' => $url_cancel,

                ],
            ],
            'response' => $response,
        ]);
    }

    public function checkPayment($attemptID)
    {
        $attempt = EcomPurchasesAttemptModel::where('id', $attemptID)->where('cancelled', 0)->first();
        $gatewayInit = json_decode($attempt->gateway_init);
        $session_id = isset($gatewayInit->response->id) ? $gatewayInit->response->id : null;

        if (is_null($session_id)) {
            dd('Unexpected Error: AirwallexController checkPayment() : Invalid intent id');
        }

        $session = $this->getSession();

        if (! $session) {
            dd('Unexpected Error: AirwallexController checkPayment() : Invalid auth token');
        }

        $token = array_key_exists('token', $session) ? $session['token'] : null;

        if (is_null($token)) {
            dd('Unexpected Error: AirwallexController checkPayment() : Invalid auth token');
        }

        $response = Http::withHeaders([
            'Authorization' => 'Bearer '.$token,
        ])->get('https://api.airwallex.com/api/v1/pa/payment_intents/'.$session_id, []);

        if ($response->status() != '200' && $response->status() != '201') {
            dd('Unexpected Error: AirwallexController checkPayment() : unable to check payment');
        }

        $response = collect(json_decode($response->body(), 1));
        if ($response['status'] == 'SUCCEEDED') {
            return response(['status' => 'success', 'response' => $response], 200);
        } else {
            return response(['status' => 'fail', 'response' => $response], 400);
        }
    }
}
