<?php

namespace twa\omnipay\controllers;

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

class TabbyController
{
    public $data;

    public $provider;

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

        $required_data = ['public_key', 'secret_key', 'merchant_code', 'endpoint', 'product'];
        \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)
    {

        $login = session('login');
        $phone = isset($login['phone']) ? $login['phone'] : '';

        $mdata = [
            'payment' => [
                'amount' => number_format(ceil($value * 100) / 100, 2, '.', ''),
                'currency' => $currency,
                'description' => 'Order REF# '.$id,
                'buyer' => [
                    "phone" => $phone,
                    'email' => $customer_email,
                    'name' => $customer_name,
                ],
                // "buyer_history" => [ "registered_since" => now() ],
                'order' => [
                    // "tax_amount" => "0.00",
                    // "shipping_amount" => "0.00",
                    // "discount_amount" => "0.00",
                    // "updated_at" => now(),
                    'reference_id' => (string) $id,
                    // "items" =>  [
                    //     [
                    //         "title" => "string",
                    //         "description" => "string",
                    //         "quantity" => 1,
                    //         "unit_price" => "0.00",
                    //         "discount_amount" => "0.00",
                    //         "reference_id" => "string",
                    //         "image_url" => "http://example.com",
                    //         "product_url" => "http://example.com",
                    //         "gender" => "Male",
                    //         "category" => "string",
                    //         "color" => "string",
                    //         "product_material" => "string",
                    //         "size_type" => "string",
                    //         "size" => "string",
                    //         "brand" => "string"
                    //     ]
                    // ]
                ],
                // "order_history" => null,
                // "shipping_address" => null,
                'meta' => ['order_id' => $id, 'customer' => $customer_email],
                'lang' => 'en',
            ],
            'merchant_code' => $this->data['merchant_code'],
            'merchant_urls' => [
                'success' => $url_success,
                'cancel' => $url_cancel,
                'failure' => $url_cancel,
            ],
        ];


        $response = Http::withHeaders([
            'Authorization' => 'Bearer '.$this->data['public_key'],
            'content-type' => 'application/json',
        ])->post($this->data['endpoint'].'/checkout', $mdata);
        if ($response->status() != '200' && $response->status() != '201') {
            dd('Unexpected Error: TabbyController createPayment() : unable to create order');
        }



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

        $redirect_url = null;
        switch ($this->data['product']) {
            case 'pay_later':
                $redirect_url = isset($response->configuration->available_products->pay_later[0]->web_url) ? $response->configuration->available_products->pay_later[0]->web_url : null;
                break;
            case 'installments':
                $redirect_url = isset($response->configuration->available_products->installments[0]->web_url) ? $response->configuration->available_products->installments[0]->web_url : null;
                break;
            default:
                dd('Unexpected Error: TabbyController createPayment() : provider product not found');
                break;
        }

        if (is_null($redirect_url) || empty($redirect_url)) {
            // dd('Your account does not support the current product');
        }

        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->payment->id) ? $gatewayInit->response->payment->id : null;

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

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

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

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

        if ($response['status'] != 'AUTHORIZED' && $response['status'] != 'CLOSED') {
            return response(['status' => 'fail', 'response' => $response], 400);
        }



        try {
            $captured =  $this->capturePayment($response['id'] , $response['amount']);
        }catch(\Throwable $th){
            $captured = false;
        }

        if(!$captured){
            return response(['status' => 'fail', 'response' => $response], 400);
        }

        return response(['status' => 'success', 'response' => $response], 200);
    }

    public function capturePayment($paymentId , $total){

        $mdata = [
            'amount' => $total,
        ];


        $response = Http::withHeaders([
            'Authorization' => 'Bearer '.$this->data['secret_key'],
            'content-type' => 'application/json',
        ])->post(str_replace( "/v2" , "/v1" ,  $this->data['endpoint']).'/payments/'.$paymentId.'/captures' , $mdata);


        if ($response->status() != '200' && $response->status() != '201') {
            return false;
        }
        $response = collect(json_decode($response->body(), 1));


        if(!is_array($response['captures'])){
            return false;
        }


        if(count($response['captures']) == 0){
            return false;
        }

        return true;

    }

    public function webhook(){

        $json_original =request()->getContent();
        $json = json_decode($json_original, 1);

        \Illuminate\Support\Facades\DB::table('webhook_payloads')->insertGetId([
            'json' => $json_original
        ]);

        if($json['status'] == "authorized"){
            $attempt = EcomPurchasesAttemptModel::where('id', $json['order']['reference_id'])->where('cancelled', 0)->first();
            if ($attempt->completed != 1) {
                $response = \twa\omnipay\facades\OmniPayFacade::responseCallback(null, $json['order']['reference_id'] , true);
            }
        }
    }
}
