<?php
require_once "./config/db_config.php";
require_once "./config/QueryBuilder.php";
class JncbPaymentGateway
{
    public $domainURL;

    public function __construct()
    {
        $this->domainURL = domainURL;

    }


    public function createOrder($data)
    {
        // Log incoming data
        include 'Logger.php';
        Logger::debug("Incoming Data: " . serialize($data));
        $gatewayJson = json_decode($data['gatewayConfig'], true);
        $powerTranzId = $gatewayJson['powerTranz_id'];
        $powerTranzPass = $gatewayJson['powerTranz_password'];
        $gatewayUrl = $gatewayJson['env'];
        if($data['currency'] == 'JMD')
        {
        $currencyCode = 388;
        }
        else if($data['currency'] == 'USD')
        {
            $currencyCode = 840;
        }else
        {
            $currencyCode = $data['currency'];
        }

        $OrderIdentifier = $data['txnId'];
        $postData = json_encode([
            "AddressMatch" => false,
            "BillingAddress" => [
                "City" => "Boston",
                "CountryCode" => $currencyCode,
                "EmailAddress" => $data['email'],
                "PhoneNumber" => $data['phoneNo'],
            ],
            "ExtendedData" => [
                "ThreeDSecure" => [
                    "ChallengeIndicator" => "01",
                    "ChallengeWindowSize" => 5,
                ],
                "HostedPage" => [
                    "PageSet" => $gatewayJson['pageSet'],
                    "PageName" => $gatewayJson['pageName'],
                ],
                "MerchantResponseUrl" => $this->domainURL . '/paymentResponse.php',
            ],
            "ThreeDSecure" => true,
            "TotalAmount" => $data['amount'],
            "CurrencyCode" => $currencyCode,
            "OrderIdentifier" => $OrderIdentifier,
        ]);

        Logger::debug("Request Payload: " . $postData);

        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $gatewayUrl.'/spi/Auth',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $postData,
            CURLOPT_HTTPHEADER => [
                "PowerTranz-PowerTranzId:".$powerTranzId,
                "PowerTranz-PowerTranzPassword:".$powerTranzPass,
                "accept: application/json",
                "content-type: application/json",
            ],
            CURLOPT_SSL_VERIFYHOST => false, // For debugging SSL issues
            CURLOPT_SSL_VERIFYPEER => false, // For debugging SSL issues
        ]);

        $response = curl_exec($curl);
        $responseDecoded = json_decode($response, true);
        Logger::info(serialize($responseDecoded));
        curl_close($curl);
        if (isset($responseDecoded['RedirectData'])) {
            Logger::debug("RedirectData detected, halting execution for manual handling.");
            return [
                "success" => true,
                "data" => $responseDecoded,
                "redirectHTML" => $responseDecoded['RedirectData'], // Send the HTML for debugging
                "OrderIdentifier" => $responseDecoded['OrderIdentifier'],
            ];
        } else {
            return $responseDecoded;

        }

    }

    public function updatePaymentOnGatewayDashboard($data , $spiToken)
    {

        $gatewayJson = json_decode($data['gatewayConfig'], true);

        // Check if the 'key' exists in the gatewayConfig
        if (isset($gatewayJson['env'])) {
            $gatewayUrl = $gatewayJson['env'];
        } else {
            echo "Gateway URL env not found.<br/>";
            return;
        }

        // Initialize cURL
        $curl = curl_init();

        // Set cURL options
        curl_setopt_array($curl, array(
            CURLOPT_URL => $gatewayUrl.'/spi/Payment', // No double quotes needed
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => '"' . $spiToken . '"', // No double quotes needed
            CURLOPT_HTTPHEADER => array(
                'accept: application/json',
                'content-type: application/json',
            ),
        ));

        // Execute the cURL request and capture the response
        $response = curl_exec($curl);
        // Check if any error occurred with cURL
        if (curl_errno($curl)) {
            $error_msg = curl_error($curl);
            echo "cURL Error: " . $error_msg;
        }

        // Close the cURL session
        curl_close($curl);

        // Return the response
        return json_decode($response, true);
    }

    public function fetchOrder($data)
    {

        $jsonString = stripslashes($data['paymentRequest']);
        $finalJson = json_decode($jsonString , true);
        $spiToken = $finalJson['SpiToken'];
        $orderStatus = $this->updatePaymentOnGatewayDashboard($data ,$spiToken);

        if(isset($orderStatus['IsoResponseCode']) && $orderStatus['IsoResponseCode'] == 00)
        {
            $txnIdentifier = $finalJson['TransactionIdentifier'];
            $gatewayInfo = json_decode($data['gatewayConfig'] , true);
            $powerTranzId = $gatewayInfo['powerTranz_id'];
            $powerTranzPass = $gatewayInfo['powerTranz_password'];
            $gatewayUrl = $gatewayInfo['env'];
            $curl = curl_init();

            curl_setopt_array($curl, array(
                CURLOPT_URL => $gatewayUrl.'/Transactions/'.$txnIdentifier,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'GET',
                CURLINFO_HEADER_OUT => true,
                CURLOPT_HTTPHEADER => array(
                    'PowerTranz-PowerTranzId:'.$powerTranzId,
                    'PowerTranz-PowerTranzPassword:'.$powerTranzPass,
                    'accept: application/json',
                    'content-type: application/json',
                ),
            ));

            $response = curl_exec($curl);
            if (curl_errno($curl)) {
                return $error_msg = curl_error($curl);
            }
            // $requestHeaders = curl_getinfo($curl, CURLINFO_HEADER_OUT);
            // echo "Request Headers:\n$requestHeaders\n";
            curl_close($curl);
            $responseDecoded = json_decode($response, true);
            $tableName = $data['tableName'];
            $notificationResponse =  json_encode($responseDecoded);
            $query = "UPDATE `".$tableName."` SET notificationResponse ='".$notificationResponse."' WHERE id=" . $data['id'];
            $update = mysqli_query($data['conn'], $query);
            return $responseDecoded;
        }
        else
        {
            $jsonString = stripslashes($data['paymentRequest']);
            $finalJson = json_decode($jsonString , true);
            $txnIdentifier = $finalJson['TransactionIdentifier'];
            $gatewayInfo = json_decode($data['gatewayConfig'] , true);
            $powerTranzId = $gatewayInfo['powerTranz_id'];
            $powerTranzPass = $gatewayInfo['powerTranz_password'];
            $gatewayUrl = $gatewayInfo['env'];
            $curl = curl_init();

            curl_setopt_array($curl, array(
                CURLOPT_URL => $gatewayUrl.'/Transactions/'.$txnIdentifier,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'GET',
                CURLINFO_HEADER_OUT => true,
                CURLOPT_HTTPHEADER => array(
                    'PowerTranz-PowerTranzId:'.$powerTranzId,
                    'PowerTranz-PowerTranzPassword:'.$powerTranzPass,
                    'accept: application/json',
                    'content-type: application/json',
                ),
            ));

            $response = curl_exec($curl);
            if (curl_errno($curl)) {
                return $error_msg = curl_error($curl);
            }


            // $requestHeaders = curl_getinfo($curl, CURLINFO_HEADER_OUT);
            // echo "Request Headers:\n$requestHeaders\n";
            curl_close($curl);
            $responseDecoded = json_decode($response, true);
            $tableName = $data['tableName'];
            $notificationResponse =  json_encode($responseDecoded);
            $query = "UPDATE `".$tableName."` SET notificationResponse ='".$notificationResponse."' WHERE id=" . $data['id'];
            $update = mysqli_query($data['conn'], $query);
            return $responseDecoded;
        }
    }

}
