<?php


namespace App\Http\Controllers\Admin;


use App\Hotel;
use App\Payment;
use App\Reservation;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Validator;

class MyFatoorah
{

    private static $apiURL = 'https://apitest.myfatoorah.com/';
    private static $apiKey = 'rLtt6JWvbUHDDhsZnfpAhpYk4dxYDQkbcPTyGaKp2TYqQgG7FGZ5Th_WD53Oq8Ebz6A53njUoo1w3pjU1D4vs_ZMqFiz_j0urb_BH9Oq9VZoKFoJEDAbRZepGcQanImyYrry7Kt6MnMdgfG5jn4HngWoRdKduNNyP4kzcp3mRv7x00ahkm9LAK7ZRieg7k1PDAnBIOG3EyVSJ5kK4WLMvYr7sCwHbHcu4A5WwelxYK0GMJy37bNAarSJDFQsJ2ZvJjvMDmfWwDVFEVe_5tOomfVNt6bOg9mexbGjMrnHBnKnZR1vQbBtQieDlQepzTZMuQrSuKn-t5XZM7V6fCW7oP-uXGX-sMOajeX65JOf6XVpk29DP6ro8WTAflCDANC193yof8-f5_EYY-3hXhJj7RBXmizDpneEQDSaSz5sFk0sV5qPcARJ9zGG73vuGFyenjPPmtDtXtpx35A-BVcOSBYVIWe9kndG3nclfefjKEuZ3m4jL9Gg1h2JBvmXSMYiZtp9MR5I6pvbvylU_PP5xJFSjVTIz7IQSjcVGO41npnwIxRXNRxFOdIUHn0tjQ-7LwvEcTXyPsHXcMD8WtgBh-wxR8aKX7WPSsT1O8d8reb2aR7K3rkV3K82K_0OgawImEpwSvp9MNKynEAJQS6ZHe_J_l77652xwPNxMRTMASk1ZsJL';
//    private static $apiURL = 'https://api.myfatoorah.com/';
//    private static $apiKey = 'LOf2cHTFvgmx-c2WOC-AZG00Bx1Qca0gd68CLthqlWPc4xOpdeCp2HddFawhRV1WFZNHPzFjbJLSmAW8PFa1BIfLAkOxCCS-8r4WqmaTSP020by5-_etz5TIIXOsc75GgXra9ZIzoGo_zsl04WjIXDijuZAGyYdBvfuKMhfW1TQohhHf_CU52vY9EYzlfcQj5cLeS5r8OvWU3LtwHpdnRK_-ItEKRz3yXw-mOKNm1EDmXd15sjM26-CRkFUaoZhKNuu9Z-1cjyV4R8OyEm6yZmB5496r-Kp0UY5N-ATlS8iMLtG5RMsNtXcbbJT1wyupPtqBlaAS7PF9ReBAc-bA_8j_DK2Cxp0NZIveHp-vzY9KsbwMk28ddzltMW9tpWYu411oXnlMWWu9vwM429Ss3lFYldLeQxDAnOBhveDsStxH-4DVIlcUkJMPpU0M5hzVk7mhtt3DF5OgDvHZlJDOhCAmx0X41Ry-8xHktVN0PTDbrjsI9gPdn79hAZMwSS2wEb4u6Y-zw7Gv329R6VTot7wqiRhMBse3lIrX7ttENmMXGlUA17QCk_Qj6jmOS47NLGWRDR0w8pP0TL9kJKpy3e95VjS7RFbMuJOOxBUj3xgLrQCrX6Z4PL5K5Rjhi7vRKSkHYlLdk-O4EzwOIeXwktQSLwlxxB_hkIg8yh7GqU6-mMbuxh1CdY-tu0xGtflWBBgLzw';


    public static function refund($invoiceId, $amount)
    {
        $postFields = [
            // Fill required Data
            "KeyType" => 'InvoiceId', // [paymentId, InvoiceId]
            "Key"     => $invoiceId,
            "Amount"  => $amount,
            "Comment" => "Refund amount",
            //Fill optional Data
            //"RefundChargeOnCustomer"  => false,
            //"ServiceChargeOnCustomer" => false,
            //"AmountDeductedFromSupplier"=> 0
        ];

        $response  = self::callAPI(self::$apiKey, self::$apiURL."/v2/MakeRefund", $postFields);
        return $response;
    }

    /**
     * Call API endpoint
     * @param $token
     * @param $apiURL
     * @param $postFields
     * @return array
     */
    private static function callAPI($token, $apiURL, $postFields) {
        $curl     = curl_init($apiURL);
        curl_setopt_array($curl, array(
            CURLOPT_CUSTOMREQUEST  => "POST",
            CURLOPT_POSTFIELDS     => json_encode($postFields),
            CURLOPT_HTTPHEADER     => array("Authorization: Bearer $token", 'Content-Type: application/json'),
            CURLOPT_RETURNTRANSFER => true,
        ));
        $response = curl_exec($curl);
        $err      = curl_error($curl);
        curl_close($curl);
        if ($err) {
            // Curl is not working in your server
            return ['errors' => ('ERROR: ' . $err)];
        }

        $response = json_decode($response);
        if ($response->ValidationErrors){
            return ['errors' => $response->Message.': '.$response->ValidationErrors[0]->Error];
        }

        return ['errors' => false, 'response' => $response];
    }

    /**
     * Handle Error function
     * @param $json
     */
    private function handleError($json) {
        //check for the error insde the object Please tell the exact postion and dont use else
        if (isset($json->ValidationErrors) || isset($json->FieldsErrors)) {
            $errorsObj = isset($json->ValidationErrors) ? $json->ValidationErrors : $json->FieldsErrors;
            $blogDatas = array_column($errorsObj, 'Error', 'Name');

            $err = implode(', ', array_map(function ($k, $v) {
                return "$k: $v";
            }, array_keys($blogDatas), array_values($blogDatas)));
        } else if (isset($json->Data->ErrorMessage)) {
            $err = $json->Data->ErrorMessage;
        }
        if (empty($err)) {
            // It may return empty content due to invalid API key
            $err = (isset($json->Message)) ? $json->Message : (!empty($res) ? $res : 'API key Or API URL is not correct');
        }
        echo 'ERROR: ' . $err;
        die;
    }
}
