<?php

namespace twa\omnipay\controllers;

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

class PaystackController
{
    public $data;

    public $provider;

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

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

    public function createPayment($id, $value, $currency, $customer_name, $customer_email, $url_success, $url_cancel)
    {
        $mdata = [
            'amount' => (int) ceil($value * 100),
            'email' => $customer_email,
            'ref' => $id,
            'callback_url' => $url_success,
        ];

        $response = Http::withHeaders([
            'Authorization' => 'Bearer '.$this->data['secret_key'],
            'content-type' => 'application/json',
        ])->post($this->data['endpoint'].'/transaction/initialize', $mdata);

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

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

        if ($response->status == false || ! isset($response->data->authorization_url)) {
            dd('Unexpected Error: PaystackController createPayment() : '.$response->message);
        }

        $redirect_url = $response->data->authorization_url;

        return collect(['redirect' => ['link' => $redirect_url], 'response' => $response]);
    }

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

        if (is_null($reference)) {
            dd('Unexpected Error: PaystackController checkPayment() : Invalid reference');
        }

        $response = Http::withHeaders([
            'Authorization' => 'Bearer '.$this->data['secret_key'],
            'content-type' => 'application/json',
        ])->get($this->data['endpoint'].'/transaction/verify/'.$reference);

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

        $response = collect(json_decode($response->body(), 1));

        if (isset($response['data']['paidAt']) && ! is_null($response['data']['paidAt'])) {
            return response(['status' => 'success', 'response' => $response], 200);
        } else {
            return response(['status' => 'fail', 'response' => $response], 400);
        }
    }
}
