<?php
error_reporting(E_ALL);
require_once("header.php");
include("academia/courseRegistrationPendingPayment.php");
require_once("./config/QueryBuilder.php");
require_once("./config/gatewayConfig.php");

$queryBuilder = new QueryBuilder($conn);
$gatewayConfig = new GatewayConfig();

$errorMsgShow = false;
if ((count($_REQUEST) == 0) || (!isset($_REQUEST['paymentId']))) {
    echo '<div class="col-md-12 text-center alert alert-warning">
                    <h4>'.$translationMsg['TRANSACTION_ERROR'].'</h4>
                </div>';
    $errorMsgShow = true;
} else {
    $tableName = 'course_registration_pending_payment';
    $where = ['id' => $_REQUEST['paymentId']];
    $result = $queryBuilder->selectById($tableName, '*', $where);
    if ($result && ($result['gatewayConfig'] == NULL || empty($result['gatewayConfig']))) {
        $activeGateways = $gatewayConfig->getActiveGateway($result['academyLocationId']); // Get the active gateways
        if(count($activeGateways) == 0){
            echo '<div class="col-md-12 text-center alert alert-warning">
                <h4>'.$translationMsg['MERCHANT_DETAILS_NOT_CONFIGURED'].'</h4>
            </div>';
            $errorMsgShow = true;
        }else{
            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
                    if(isset($result['currency']) && $result['currency'] == 'R' && $selectedGateway['value'] == 'payu' || $selectedGateway['value'] == 'paygate')
                {
                    $result['currency'] = 'ZAR';
                }
                    $registrationPendingObj = new CourseRegistrationPendingPayment();
                    $merchantDetails = $registrationPendingObj->getStandardMerchantDetailsByAl($selectedGateway['value'], $result['academyLocationId'], $result['currency']);
                    // print_r($merchantDetails);echo 'test';
                    if ($merchantDetails == 'ACCESS_TOKEN') {
                        echo '<div class="col-md-12 text-center alert alert-warning">
                                   <h4>'.$translationMsg['SERVER_ERROR'].'</h4>
                                </div>';
                        $errorMsgShow = true;
                    } else if ($merchantDetails == 'No_DATA') {
                        echo '<div class="col-md-12 text-center alert alert-warning">
                                <h4>'.$translationMsg['MERCHANT_DETAILS_NOT_CONFIGURED'].'</h4>
                            </div>';
                            $errorMsgShow = true;
                    } else {
    
                        require_once('./config/paymentGatewayLoader.php');
                        try {
                            $gatewayLoader = new PaymentGatewayLoader();
                            $gatewayLoader->loadPaymentGateway(strtolower($selectedGateway['value']), $conn, 'course-registration-pending-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>';
                                  $errorMsgShow = true;
                        }
                    }
                    // 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>';
                          $errorMsgShow = true;
                }
            } 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'] . '?paymentId=' . $_REQUEST['paymentId'] .'">';
                        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
                    }
                }
    
                if (count($activeGateways) > 1) {
                    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'] . '?paymentId=' . $_REQUEST['paymentId'] . '">
                            <div class="row payment-row">';
                    foreach ($activeGateways as $gateway) {
                        if ($gateway['activeStatus']) {
                            echo '<div class="col-md-6">
                                        <label class="payment-option">
                                        <input required type="radio" name="paymentGateway" value="' . $gateway['value'] . '" id="gateway' . $gateway['id'] . '">
                                        <span>' . ucfirst($gateway['value']) . '</span>
                                        <img src="assets/image/' . $gateway['value'] . '.png" alt="' . $gateway['value'] . '">
                                        </label>
                                    </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>';
                $errorMsgShow = true;
    }
    if($errorMsgShow == true){
        echo '<div class="col-md-12 text-center" id="gotohome">
            <a href="' . $result['requestUrl'] . '" class="btn btn-primary proceedBtn">Go to Dashboard</a>
        </div>';
    }
}
require_once("footer.php");
?>