<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once "header.php";
include "academia/onlinePayment.php";
require_once "./config/QueryBuilder.php";
require_once "./config/gatewayConfig.php";
require_once "./sdk/grayQuest/grayQuestUtils.php";
require_once './config/paymentGatewayLoader.php';
$queryBuilder   = new QueryBuilder($conn);
$gatewayConfig  = new GatewayConfig();
$gatewayLoader = new PaymentGatewayLoader();
$activeGateways = $gatewayConfig->getActiveGateway($_REQUEST['academyLocationIds']); // Get the active gateways
$translationMsg = json_decode(TRANSLATION_MSG, true);
if ((count($_REQUEST) == 0) || (! isset($_REQUEST['id']) || ! isset($_REQUEST['academyLocationIds']))) {
    echo '<div class="col-md-12 text-center alert alert-warning">
                    <h4>' . $translationMsg['TRANSACTION_ERROR'] . '</h4>
                </div>';
} else {
    $tableName = 'online_payment';
    $where     = ['id' => $_REQUEST['id']];
    $result    = $queryBuilder->selectById($tableName, '*', $where);
    if ($result && ($result['gatewayConfig'] == null || empty($result['gatewayConfig']))) {
        // If the form is submitted
        if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['paymentGateway'])) {
            $selectedGatewayValue = $_POST['paymentGateway'];
            $selectedGateway      = null;
            foreach ($activeGateways as $gateway) {
                if ($gateway['value'] == $selectedGatewayValue) {
                    $selectedGateway = $gateway;
                    break;
                }
            }

            if ($selectedGateway) {
                // Proceed with the payment process using the selected gateway
                $gatewayConfig->set_session($selectedGatewayValue);
                $result['academyLocationId'] = $_REQUEST['academyLocationIds'];
                $result['paymentOption']     = $selectedGateway['value']; // Store selected gateway value
                $costCenter = $result['feeHead'];  // Get Cost Center Id From feeHeadField and Pass it to   getStandardMerchantDetailsByAl()  
                $costCenterArr = is_string($costCenter) ? json_decode($costCenter, true) : $costCenter;
                // print_r($costCenterArr);
                $costCenterId = $costCenterArr[0]['costCentreId'];     
                if (isset($result['currency']) && $result['currency'] == 'R' && $selectedGateway['value'] == 'payu' || $selectedGateway['value'] == 'paygate') {
                    $result['currency'] = 'ZAR';
                }                
                $onlinePaymentObj = new OnlinePayment();
                $merchantDetails  = $onlinePaymentObj->getStandardMerchantDetailsByAl($selectedGateway['value'], $result['academyLocationId'], $result['currency'] ,$costCenterId);                            
                if ($merchantDetails == 'ACCESS_TOKEN') {
                    echo '<div class="col-md-12 text-center alert alert-warning">
                            <h4>' . $translationMsg['SERVER_ERROR'] . '</h4>
                            </div>';
                } else if ($merchantDetails == 'No_DATA') {
                    echo '<div class="col-md-12 text-center alert alert-warning">
                        <h4>' . $translationMsg['MERCHANT_DETAILS_NOT_CONFIGURED'] . '</h4>
                        </div>';
                } else {                    
                    try {
                        
                        $gatewayLoader->loadPaymentGateway(strtolower($selectedGateway['value']), $conn, 'online-payment', $result, $tableName, $merchantDetails[strtolower($selectedGateway['value'])]);
                    } catch (Exception $e) {
                        echo '<div class="col-md-12 text-center alert alert-warning">
                            <h4>' . $translationMsg['TRANSACTION_ERROR'].'</h4>
                              </div>';
                    }
                }
                // Now, call the payment gateway loader or other functions to process the payment
            } else {
                echo '<div class="col-md-12 text-center alert alert-warning">
                    <h4>' . $translationMsg['INVALID_PAYMENT_GATEWAY_SELECTED'] . '</h4>
                      </div>';
            }
        } else {

            // Check if there's only one active gateway
         if (count($activeGateways) === 1) {
                $singleGateway = reset($activeGateways); // Get the first (and only) gateway
                if ($singleGateway['activeStatus']) {
                    echo '<form id="autoSubmitForm" method="POST" action="' . $_SERVER['PHP_SELF'] . '?id=' . $_REQUEST['id'] . '&academyLocationIds=' . $_REQUEST['academyLocationIds'] . '">';
                    echo '<input type="hidden" name="paymentGateway" value="' . $singleGateway['value'] . '">';
                    echo '</form>';

                    // Add JavaScript to auto-submit the form
                    echo '<script>document.getElementById("autoSubmitForm").submit();</script>';
                    exit; // End the script to prevent rendering the rest of the form
                }
            }
            // Check if there's only one active gateway
            if (count($activeGateways) > 1) {
                $onlinePaymentObj = new OnlinePayment();
                echo '<div class="container d-flex justify-content-center align-items-center min-vh-100">
                    <div class="card main-card-apyment p-4" style="max-width: 600px;width: 100%;margin:auto;padding: 3rem;margin-top:5%;border:1px solid #eee;">
                    <h3 class="text-center mb-4" style="margin-top:0;">Select Payment Gateway</h3>
                    <form method="POST" action="' . $_SERVER['PHP_SELF'] . '?id=' . $_REQUEST['id'] . '&academyLocationIds=' . $_REQUEST['academyLocationIds'] . '">
                        <div class="row payment-row">';
                foreach ($activeGateways as $gateway) {
                    if ($gateway['activeStatus']) {
                        $emiMessage   = '';
                        $paymentLabel = 'payment-option';
                        if ($gateway['value'] === 'grayquest') {
                            $paymentLabel = 'payment-option2';
                            // Hardcode Grayquest merchant details for testing
                            $merchantDetails = $onlinePaymentObj->getStandardMerchantDetailsByAl(
                                $gateway['value'],
                                $_REQUEST['academyLocationIds'],
                                ''                                
                            );
                            // Try fetching EMI plans from API
                            if (is_array($merchantDetails) && isset($merchantDetails['grayquest'])) {
                                $grayquestDetails = $merchantDetails['grayquest'];                                
                                $emiPlans         = GrayquestUtils::fetchGrayquestEMIPlans(
                                    $result['amount'],
                                    $grayquestDetails['clientId'],
                                    $grayquestDetails['clientSecret'],
                                    $grayquestDetails['apiKey'],
                                    $grayquestDetails['fetchEmiURl'],                                   

                                );
                                print_r($emiPlans);
                                if ($emiPlans) {
                                    $emiMessages = [];
                                    foreach ($emiPlans as $plan) {
                                        if (isset($plan['emi_count']) && isset($plan['plan_emi_amount'])) {
                                            $emiMessages[] = $plan['emi_count'] . ' Mon: ₹' . number_format($plan['plan_emi_amount'], 2) . '/month';
                                        }
                                    }
                                    if ($emiMessages) {
                                        $emiMessage = '<div style="font-size: 0.9em; color: red; ">Choose easy EMI payment with Grayquest: ' . implode('<br>', $emiMessages) . '</div>';
                                    }
                                }
                            }

                        }

                        echo '<div class="col-md-6">';

                        echo '<label class="' . $paymentLabel . '">';

                        // If payment-option2, wrap input+span+img in a flex row div
                        if ($paymentLabel === 'payment-option2') {
                            echo '<div style="display: flex; flex-direction: row; align-items: center; ">';
                            echo '<input required type="radio" name="paymentGateway" value="' . htmlspecialchars($gateway['value']) . '" id="gateway' . (int) $gateway['id'] . '">';
                            echo '<span>' . ucfirst(htmlspecialchars($gatewayLoader->getDisplayName($gateway['value']))) . '</span>';
                            echo '<img src="assets/image/' . htmlspecialchars($gateway['value']) . '.png" alt="' . htmlspecialchars($gateway['value']) . '">';
                            echo '</div>';

                            // Also show EMI message if available
                            if (! empty($emiMessage)) {
                                echo '<div style="display: flex; flex-direction: column; font-size: 0.85em; color: #007bff; margin-top: 8px;">
                                ' . $emiMessage . '
                            </div>';
                            }

                        } else {
                            
                            echo '<input required type="radio" name="paymentGateway" value="' . htmlspecialchars($gateway['value']) . '" id="gateway' . (int) $gateway['id'] . '">';
                            echo '<span>' . ucfirst(htmlspecialchars($gatewayLoader->getDisplayName($gateway['value']))) . '</span>';
                            echo '<img src="assets/image/' . htmlspecialchars($gateway['value']) . '.png" alt="' . htmlspecialchars($gateway['value']) . '">';
                        }

                        echo '</label>';
                        echo '</div>';
                    }
                }

                echo '</div>
                        <div class="text-center mt-4">
                        <button type="submit" class="btn btn-primary">' . $translationMsg['PROCEED_WITH_PAYMENT'] . '</button>
                        </div>
                    </form>
                    </div>
                </div>';
            }
        }
    } else {
        echo '<div class="col-md-12 text-center alert alert-warning">
                <h4>' . $translationMsg['TRANSACTION_ERROR'] . '</h4>
                </div>';
    }
}

require_once "footer.php";
