<?php
require_once("./config/db_config.php");
require_once('Logger.php');

class GrayquestPaymentGateway
{
    public $domainURL;
    public $clientId;
    public $clientSecret;
    public $apiKey;
    public $environment;
    public $url;
    public $slug;

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

    /**
     * Initialize Grayquest SDK and return the form to render the EMI popup
     *
     * @param array $paymentDetails Payment details (amount, email, etc.)
     * @param array $gatewayDetails Grayquest gateway configuration (clientId, clientSecret, etc.)
     * @return string HTML form with SDK initialization
     */
    public function createOrder($paymentDetails, $gatewayDetails)
    {
        $this->clientId = $gatewayDetails['client_id'];
        $this->clientSecret = $gatewayDetails['client_secret'];
        $this->apiKey = $gatewayDetails['api_key'];
        $this->environment = $gatewayDetails['environment'];
        $this->slug = $gatewayDetails['slug'];
        $this->url =  $gatewayDetails['url'];
        $amount = $paymentDetails['amount']; // Grayquest uses amount in base currency
            
        return $this->generateCheckoutForm(
            $paymentDetails,            
            $amount,            
            $this->clientId,
            $this->clientSecret,
            $this->apiKey,
            $this->environment,
            $this->slug,
            $this->url,           
            
        );
    }

    /**
     * Generates the HTML form for Grayquest checkout
     *
     * @param array $paymentDetails
     * @param int $amount
     * @param string $url
     * @param string $clientId
     * @param string $clientSecret
     * @param string $apiKey
     * @param string $environment
     * @param string $slug
     * @return string HTML form
     */
    private function generateCheckoutForm($paymentDetails, $amount, $clientId, $clientSecret, $apiKey, $environment , $slug , $url)
    {
        $studentId = isset($paymentDetails['studentId']) ? $paymentDetails['studentId'] : $paymentDetails['code'];
        $customerMobile = $paymentDetails['phoneNo'];        
        $feeHead = $paymentDetails['feeHead'];      
        $feeHeadArray = is_string($feeHead) ? json_decode($feeHead, true) : $feeHead;       
        $aggregatedFees = [];      
        foreach ($feeHeadArray as $item) {    
            $feeHeadName = $item['feeHeadName'];
            if (isset($aggregatedFees[$feeHeadName])) {
                $aggregatedFees[$feeHeadName] += $item['balanceAmount'];
            } else {
                $aggregatedFees[$feeHeadName] = $item['balanceAmount'];
            }
        }        
        $feeHeadersJson = json_encode($aggregatedFees);
        $returnUrl = $this->domainURL . '/paymentResponse.php';        
        $sdkUrl = $url . "/v1.1/gqerp-sdk.min.js?v=latest";
        $txnId = $paymentDetails['txnId'];
        // phpcs: ignore      
        $form = <<<HTML
            <div id="gq-checkout"></div>
            <script src="{$sdkUrl}"></script>
            <script>
                document.addEventListener("DOMContentLoaded", function() {
                    GqErpSDK.setOptions({
                        env: "{$environment}",
                        auth: {
                            client_id: "{$clientId}",
                            client_secret: "{$clientSecret}",
                            api_key: "{$apiKey}"
                        },
                        student_id: "{$studentId}",
                        customer_mobile: "{$customerMobile}",
                        reference_id : "{$txnId}",
                        pp_config: {
                            slug: "{$slug}"
                        },
                       fee_headers: {$feeHeadersJson},
                        redirection: {
                            success_url: "{$returnUrl}",
                            error_url: "{$returnUrl}"
                        },
                        customizations: {
                            logo_url: "https://logo-url.com",
                            theme: {
                                theme_color: "#5667FF"
                            }
                        }
                    });

                    GqErpSDK.render();

                    // Event Listeners
                    document.addEventListener("onGqPopupClose", (e) => {
                        window.location.href = "{$returnUrl}"+ '?type=invalid';
                    });                   
                });
            </script>            
HTML;

        return $form;
    }

    /**
     * Fetch order details after Grayquest payment
     *
     * @param array $data Payment data
     * @return array Payment response
     */
    public function fetchOrder($data)
{
    $response = $this->initializeResponse();

    try {
        $gatewayJson = json_decode($data['gatewayConfig'], true);
        $clientId = $gatewayJson['client_id'];
        $clientSecret = $gatewayJson['client_secret'];
        $apiKey = $gatewayJson['api_key'];
        $baseUrl = $gatewayJson['paymentStatusUrl'];
        $orderId = $data['txnId'];

        $authString = $clientId . ':' . $clientSecret;
        $authHeader = 'Basic ' . base64_encode($authString);

        $url = $baseUrl . '/v1/payments/fetch?reference_id=' . $orderId;

        $headers = [
            'Content-Type: application/json',
            'GQ-API-Key: ' . $apiKey,
            'Authorization: ' . $authHeader
        ];

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $result = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode === 200 && $result) {
            $orderData = json_decode($result, true);
            if ($orderData['success'] === true) {
                $response['grayquestId'] = $orderData['data']['payment_id'];
                $response['txnId'] = $orderData['data']['reference_id'];
                $response['transactionStatus'] = $orderData['data']['payment_status'];
                $response['orderCode'] = $orderData['data']['order_code'];               
                $response['fullResponse'] = json_encode($orderData);
            } else {
                $response['error'] = $orderData['message'] ?? 'Payment failed';
            }
        } else {
            $response['error'] = 'Unable to fetch payment status';
        }
    } catch (Exception $e) {
        Logger::error("Grayquest payment error: " . $e->getMessage());
        $response['error'] = "Error: " . $e->getMessage();
    }

    return $response;
}
public function fetchEmiStatus($data)
{
    $response = $this->initializeResponse();
     try {
        $gatewayJson = json_decode($data['gatewayConfig'], true);
        $clientId = $gatewayJson['client_id'];
        $clientSecret = $gatewayJson['client_secret'];
        $apiKey = $gatewayJson['api_key'];
        $baseUrl = $gatewayJson['paymentStatusUrl'];
        $orderId = $data['txnId'];

        $authString = $clientId . ':' . $clientSecret;
        $authHeader = 'Basic ' . base64_encode($authString);

        $url = $baseUrl . '/v1/applications/check-status?reference_id=' . $orderId;

        $headers = [
            'Content-Type: application/json',
            'GQ-API-Key: ' . $apiKey,
            'Authorization: ' . $authHeader
        ];

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $result = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode === 200 && $result) {
            $orderData = json_decode($result, true);
            if ($orderData['success'] === true) {
                $response['grayquestId'] = $orderData['data'][0]['application_id'];
                $response['txnId'] = $orderData['data'][0]['reference_id'];
                $response['transactionStatus'] = $orderData['data'][0]['stage'];                
                $response['fullResponse'] = json_encode($orderData);
            } else {
                $response['error'] = $orderData['message'] ?? 'Payment failed';
            }
        } else {
            $response['error'] = 'Unable to fetch payment status';
        }
    } catch (Exception $e) {
        Logger::error("Grayquest payment error: " . $e->getMessage());
        $response['error'] = "Error: " . $e->getMessage();
    }

    return $response;
}
    /**
     * Initialize the response structure
     *
     * @return array
     */
    private function initializeResponse()
    {
        return [
            'grayquestId' => null,
            'transactionStatus' => null,
            'txnId' => null,
            'error' => null
        ];
    }


}
?>