<?php

namespace twa\omnipay\controllers;

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

class PayTabsController
{
    public $data;
    public $provider;

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

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

    public function createSession()
    {
//        $response = Http::withHeaders([
//            'x-client-id' => $this->data['client_id'],
//            'x-api-key' => $this->data['api_key'],
//        ])->post('https://api.mollie.com/v2/payments/tr_WDqYK6vllg', []);

    }

    public function createPayment($id, $value, $currency, $customer_name, $customer_email, $url_success, $url_cancel)
    {

        $attempt = \twa\ecomcart\models\EcomPurchasesAttemptModel::find($id);
        $billing = $attempt['billing_address_details'];
        $response = Http::withHeaders(["authorization" => $this->data['SERVER_KEY']])->post(
            'https://secure.paytabs.com/payment/request',
            ["profile_id" => $this->data['PROFILE_ID'], "tran_type" => "sale", "tran_class" => "ecom", "cart_id" => uniqid(), "cart_description" => "Order #" . $id . " from " . env("APP_NAME"), "cart_currency" =>  $currency, "cart_amount" => $value, "hide_shipping" => true, "customer_details" => [
                "name" => $billing['first_name'] . ' ' . $billing['last_name'], "email" => "", "phone" => $billing['phone'], "street1" => $billing['street'], "city" => $billing['city'], "state" => $billing['state'], "country" => $billing['country']['code'], "zip" => $billing['postal_code'], "ip" => "",
            ],  "return" => $url_success, "callback" => ""]
        );
        if($response->getStatusCode() != 400){
            $response = twaJsonDecode($response->body());
            if(isset($response['redirect_url'])){
                Cache::store('file')->put('paytabs_id_'.$id,$response['tran_ref'],3600);
                return collect(['redirect' => ['link' => $response['redirect_url'] ], "reference" => $response['tran_ref'] ]);
            }else{
                return collect(['status' => 'fail', 'response' => $response]);
            }
        }else{
            return collect(['status' => 'fail', 'response' => "failed" ]);
        }


    }

    public function checkPayment($attemptID)
    {
        $id = Cache::store('file')->get('paytabs_id_'.$attemptID);
//        Cache::forget('mollie_id_'.$attemptID);
        $response = Http::withHeaders([ "authorization" => $this->data['SERVER_KEY'] ])->post('https://secure.paytabs.com/payment/query',
        [ "profile_id" => $this->data['PROFILE_ID'], "tran_ref" => $id ]);
        if($response->getStatusCode() != 400){
            $response = twaJsonDecode($response->body());
            if(isset($response['payment_result']) && isset($response['payment_result']['response_message']) && ($response['payment_result']['response_message'] == "Authorised" || $response['payment_result']['response_message'] == "Captured")){
                return response(['status' => 'success', 'response' => $response], 200);
            }
        }
        return response(['status' => 'fail', 'response' => $response->body()], 400);
    }
}
