<?php
require_once "./config/db_config.php";

class MPGSPaymentGateway
{
    public $domainUrl;
    private $authHeader;
    public function __construct()
    {
        $this->domainUrl = domainURL;
    }

    private function getAuthHeader($merchantKey, $password)
    {
        return 'Authorization: Basic ' . base64_encode("$merchantKey:$password");
    }

    public function createOrder($data)
    {
        $gatewayJson = json_decode($data['gatewayConfig'], true);
        $merchantID  = $gatewayJson['merchantID'];
        $merchantKey = $gatewayJson['merchantKey'];
        $password    = $gatewayJson['password'];
        $currency    = $gatewayJson['currency'];
        $environment = $gatewayJson['environment'];
        $orderId     = $data['txnId'];
        $amount      = $data['amount'];
        $authHeader  = $this->getAuthHeader($merchantKey, $password);        
        $curl        = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL            => $environment . '/api/rest/version/100/merchant/'.$merchantID.'/session',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING       => '',
            CURLOPT_MAXREDIRS      => 10,
            CURLOPT_TIMEOUT        => 30, // Increased timeout for reliability
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST  => 'POST',
            CURLOPT_POSTFIELDS     => json_encode([
                "apiOperation" => "INITIATE_CHECKOUT",
                "interaction"  => [
                    "operation"           => "PURCHASE",
                    "merchant"            => [
                        "name" => "SeyLan",
                        "url"  => "https://www.mastercard.com",
                    ],
                    "returnUrl"           => $this->domainUrl . "/paymentResponse.php?ord=" . $orderId,
                    "displayControl"      => [
                        "billingAddress" => "HIDE",
                    ],
                    "redirectMerchantUrl" => $this->domainUrl . "/paymentResponse.php?ord=" . $orderId,
                    "retryAttemptCount"   => 1,
                ],
                "order"        => [
                    "currency"    => $currency,
                    "amount"      => $amount,
                    "id"          => $orderId,
                    "description" => "Fee Payment",
                ],
            ]),
            CURLOPT_HTTPHEADER     => [
                'Content-Type: application/json',
                $authHeader,
            ],
        ]);

        $response = curl_exec($curl);

        if (curl_errno($curl)) {
            echo 'Error: ' . curl_error($curl);
        }
        curl_close($curl);
        $responseDecode = json_decode($response, true);
        $sessionId      = $responseDecode['session']['id'] ?? '';

        return [
            'status'       => $sessionId ? 'SUCCESS' : 'FAILED',
            'sessionId'    => $sessionId,
            'jsonResponse' => $response,
        ];

    }

    public function fetchOrder($data)
    {
        $gatewayJson = json_decode($data['gatewayConfig'], true);
        $merchantID  = $gatewayJson['merchantID'];
        $merchantKey = $gatewayJson['merchantKey'];
        $password    = $gatewayJson['password'];
        $environment = $gatewayJson['environment'];
        $orderId     = $data['txnId'];
        $authHeader = $this->getAuthHeader($merchantKey, $password);

        $curl = curl_init();

        curl_setopt_array($curl, [
            CURLOPT_URL            => $environment.'/api/rest/version/100/merchant/' . $merchantID . '/order/' . $orderId,
            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',
            CURLOPT_HTTPHEADER     => [
                'Content-Type: application/json',                
                $authHeader,
            ],
        ]);

        $response = curl_exec($curl);
        curl_close($curl);
        $responseDecode = json_decode($response , true);      
        if (isset($responseDecode['transaction'][0]['order']['status']) && $responseDecode['transaction'][0]['order']['status'] === 'CAPTURED') {
            return [
                'status' => 'SUCCESS',
                'txnId' => $responseDecode['transaction'][0]['order']['id'],
                'response' => $responseDecode,
            ];
        } elseif (isset($responseDecode['error'])) {           
            return [
                'status' => $responseDecode['error']['cause'], 
                'txnId' => isset($responseDecode['transaction'][0]['order']['id']) ? $responseDecode['transaction'][0]['order']['id'] : 'N/A',
                'response' => $responseDecode,
            ];
        } else {
            return [
                'status' => isset($responseDecode['transaction'][0]['order']['status']) ? $responseDecode['transaction'][0]['order']['status'] : 'FAILED',
                'txnId' => isset($responseDecode['transaction'][0]['order']['id']) ? $responseDecode['transaction'][0]['order']['id'] : 'N/A',
                'response' => $responseDecode,
            ];
        }
        

    }
}
