<?php
namespace App\Http\Helpers;

use Illuminate\Support\Facades\Request;

trait MyFatooraHelper {
    // Check whether die on request fail or not
    private $die= true;
    private $error= false;
    private $errorMessage= '';
    /**
     * Perpare Checkout
     * 
     * @param array $data
     * @return mixed
     */
    public function perpareCheckout(array $data){

        //You can save $paymentMethods information in database to be used later
        $paymentMethodId = $data['payment_method_id'] ?? 2;
        $token = $data['token'] ?? null;
        $amount = $data['amount'] ?? 10;
        $title = $data['title'] ?? '--';
        /* ------------------------ Call ExecutePayment Endpoint -------------------- */

        //Fill invoice item array
        $invoiceItems[] = [
            'ItemName'  => $title, //ISBAN, or SKU
            'Quantity'  => '1', //Item's quantity
            'UnitPrice' => $amount, //Price per item
        ];
        // $url= "http://sehola.net/my_fatoora/";
        $url= $data['url'];
        //Fill POST fields array
        $customerPhone= $data['customer']['phone'];
        $phone= substr($customerPhone, -9, 9);
        $countryCode= substr($customerPhone, 0, strlen($customerPhone)-9);
        // dd( $customerPhone, $phone, $countryCode );
        $postFields = [
            //Fill required data
            'paymentMethodId' => $paymentMethodId ?? 2,
            'InvoiceValue'    => $amount,
            'CallBackUrl'     => $url,
            'ErrorUrl'        => $url, //or 'https://example.com/error.php'    
            'CustomerReference'  => $token,
            'DisplayCurrencyIso' => 'SAR',
            //Fill optional data
            'MobileCountryCode'  => $countryCode,
            'Customer'     => $data['customer']['name'],
            'CustomerName'     => $data['customer']['name'],
            'CustomerMobile'     => $phone,
            'CustomerEmail'      => $data['customer']['email'],
            //'Language'           => 'en', //or 'ar'
            //'CustomerCivilId'    => 'CivilId',
            //'UserDefinedField'   => 'This could be string, number, or array',
            //'ExpiryDate'         => '', //The Invoice expires after 3 days by default. Use 'Y-m-d\TH:i:s' format in the 'Asia/Kuwait' time zone.
            //'SourceInfo'         => 'Pure PHP', //For example: (Laravel/Yii API Ver2.0 integration)
            //'CustomerAddress'    => $customerAddress,
            'InvoiceItems'       => $invoiceItems,
        ];
        // dd($postFields);
        //Call endpoint
        $data = $this->executePayment(env('MY_FATOORA_URL'), env('MY_FATOORA_KEY'), $postFields);
        if (!$data) {
            return ['error' => true, 'message'=> $this->errorMessage];
        }
        // dd($data);
        //You can save payment data in database as per your needs
        $invoiceId   = $data->InvoiceId;
        $paymentLink = $data->PaymentURL;
        return ['invoice_id'=> $invoiceId, 'url'=> $paymentLink];
        //Redirect your customer to the payment page to complete the payment process
        //Display the payment link to your customer
        // echo "Click on <a href='$paymentLink' target='_blank'>$paymentLink</a> to pay with invoiceID $invoiceId.";

    }

    public function getPaymentInfo($paymentId): object {
        //Inquiry using paymentId
        $keyId   = $paymentId;
        $KeyType = 'paymentId';

        //Inquiry using invoiceId 
        /*$keyId   = '613842';
        $KeyType = 'invoiceId';*/

        //Fill POST fields array
        $postFields = [
            'Key'     => $keyId,
            'KeyType' => $KeyType
        ];
        $data = $this->getPaymentStatus(env('MY_FATOORA_URL'), env('MY_FATOORA_KEY'), $postFields);
        if (!$data) {
            return (object)['error' => true, 'message'=> $this->errorMessage];
        }
        //Display the payment result to your customer
        // echo 'Payment status is ' . $data->InvoiceStatus;
        // dd($data);
        return $data;
    }


    /* ------------------------ Functions --------------------------------------- */
    /*
    * Initiate Payment Endpoint Function 
    */

    public function initiatePayment($apiURL, $apiKey, $postFields) {

        $json = $this->callAPI("$apiURL/v2/InitiatePayment", $apiKey, $postFields);
        return $json->Data->PaymentMethods;
    }

    //------------------------------------------------------------------------------
    /*
    * Execute Payment Endpoint Function 
    */

    public function executePayment($apiURL, $apiKey, $postFields) {
        $this->die = false;
        $json = $this->callAPI("$apiURL/v2/ExecutePayment", $apiKey, $postFields);
        if (!$json) {
            return false;
        }
        return $json->Data;
    }


    //------------------------------------------------------------------------------
    /*
    * Get Payment Status Endpoint Function 
    */

    public function getPaymentStatus($apiURL, $apiKey, $postFields) {
        $this->die = false;
        $json = $this->callAPI("$apiURL/v2/getPaymentStatus", $apiKey, $postFields);
        if (!$json) {
            return false;
        }
        return $json->Data;
    }

    //------------------------------------------------------------------------------
    /*
    * Call API Endpoint Function
    */

    public function callAPI($endpointURL, $apiKey, $postFields = [], $requestType = 'POST') {

        $curl = curl_init($endpointURL);
        curl_setopt_array($curl, array(
            CURLOPT_CUSTOMREQUEST  => $requestType,
            CURLOPT_POSTFIELDS     => json_encode($postFields),
            CURLOPT_HTTPHEADER     => array("Authorization: Bearer $apiKey", 'Content-Type: application/json'),
            CURLOPT_RETURNTRANSFER => true,
        ));

        $response = curl_exec($curl);
        $curlErr  = curl_error($curl);

        curl_close($curl);

        if ($curlErr) {
            //Curl is not working in your server
            die("Curl Error: $curlErr");
        }

        $error = $this->handleError($response);
        if ($error) {        
            if (!$this->die) {
                $this->error= true;
                $this->errorMessage= $error;
                return false;
            } else {
                die("Error: $error");
            }
        }

        return json_decode($response);
    }

    //------------------------------------------------------------------------------
    /*
    * Handle Endpoint Errors Function 
    */

    public function handleError($response) {

        $json = json_decode($response);
        if (isset($json->IsSuccess) && $json->IsSuccess == true) {
            return null;
        }

        //Check for the errors
        if (isset($json->ValidationErrors) || isset($json->FieldsErrors)) {
            $errorsObj = isset($json->ValidationErrors) ? $json->ValidationErrors : $json->FieldsErrors;
            $blogDatas = array_column($errorsObj, 'Error', 'Name');

            $error = implode(', ', array_map(function ($k, $v) {
                        return "$k: $v";
                    }, array_keys($blogDatas), array_values($blogDatas)));
        } else if (isset($json->Data->ErrorMessage)) {
            $error = $json->Data->ErrorMessage;
        }

        if (empty($error)) {
            $error = (isset($json->Message)) ? $json->Message : (!empty($response) ? $response : 'API key or API URL is not correct');
        }

        return $error;
    }
}

?>