<?php

namespace twa\omnipay\controllers;

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

class NoonController
{
    public $data;

    public $provider;

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

        $required_data = ['auth_key', 'api'];
        \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)
    {
        $auth_token = $this->data['auth_key'];

        $mdata = [
            'apiOperation' => 'INITIATE',
            'order' => [
                'name' => 'New Order',
                'channel' => 'web',
                'reference' => (string) $id,
                'amount' => $value,
                'currency' => $currency,
                'category' => 'pay',
            ],
            'configuration' => [
                'locale' => 'en',
                'paymentAction' => 'Sale',
                'returnUrl' => $url_success,
            ],
        ];

        $response = Http::withHeaders(['Authorization' => $auth_token, 'Content-Type' => 'application/json'])->post($this->data['api'], $mdata);

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

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

        $redirect_url = $response->result->checkoutData->postUrl;

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

    public function checkPayment($attemptID)
    {
        $auth_token = $this->data['auth_key'];

        $attempt = EcomPurchasesAttemptModel::where('id', $attemptID)->where('cancelled', 0)->first();
        $gatewayInit = json_decode($attempt->gateway_init);

        $order_id = isset($gatewayInit->response->result->order->id) ? $gatewayInit->response->result->order->id : null;

        if (is_null($order_id)) {
            dd('Unexpected Error: NoonController checkPayment() : Invalid order_id');
        }

        $response = Http::withHeaders(['Authorization' => $auth_token, 'Content-Type' => 'application/json'])->get($this->data['api'].'/'.$order_id, []);

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

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

        if ($response['result']['order']['status'] == 'CAPTURED') {
            return response(['status' => 'success', 'response' => $response], 200);
        } else {
            return response(['status' => 'fail', 'response' => $response], 400);
        }
    }
}
