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

require_once("header.php");
require_once("./config/QueryBuilder.php");
require_once("./config/gatewayConfig.php");
include("academia/advancePayment.php");

$queryBuilder = new QueryBuilder($conn);
$gatewayConfig = new GatewayConfig();
$activeGateways = $gatewayConfig->getActiveGateway(); // Get the active gateways

if((count($_REQUEST) == 0) || (!isset($_REQUEST['onlinePaymentId']) || !isset($_REQUEST['studentId']) || !isset($_REQUEST['academyLocationId'])))
{
    echo '<div class="col-md-12 text-center alert alert-warning">
            <h4>Unfortunately, Your transaction could not be processed. Please try again.</h4>
            </div>';
}
else
{
    $tableName = 'advance_payment';
    $where = ['id' => $_REQUEST['id']];
    $result = $queryBuilder->selectById($tableName, '*', $where);
    if ($result) {
        // 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
                $advancePaymentObj = new AdvancePayment();
                $merchantDetails = $advancePaymentObj->getStandardMerchantDetailsByAl($selectedGateway['value'],$result['academyLocationId']);
              
                if($merchantDetails == 'ACCESS_TOKEN')
                {
                    echo '<div class="col-md-12 text-center alert alert-warning">
                                <h4>Unfortunately, Your transaction could not be processed because server not responding. Please try again.</h4>
                            </div>';
                }
                else if($merchantDetails == 'No_DATA')
                {
                    echo '<div class="col-md-12 text-center alert alert-warning">
                            <h4>Unfortunately, Your transaction could not be processed. Please contact to Admin.</h4>
                        </div>';
                }else{                 
                    
                    require_once('./config/paymentGatewayLoader.php');
                    try {
                        $gatewayLoader = new PaymentGatewayLoader();
                        $gatewayLoader->loadPaymentGateway(strtolower($selectedGateway['value']), $conn, 'advance-payment', $result, $tableName,$merchantDetails[strtolower($selectedGateway['value'])]);
                    } catch (Exception $e) {
                        echo '<div class="col-md-12 text-center alert alert-warning">
                                <h4>Unfortunately, Your transaction could not be processed. Please try again.</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>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
                }
            }
           
            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'] . '?id=' . $_REQUEST['id'] . '&academyLocationIds=' . $_REQUEST['academyLocationIds'] . '">
                        <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>'.$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">Proceed with Payment</button>
                        </div>
                    </form>
                    </div>
                </div>';
            }

        }
    } else {
        echo '<div class="col-md-12 text-center alert alert-warning">
                    <h4>Unfortunately, Your transaction could not be processed. Please try again.</h4>
                </div>';
    }

}
require_once("footer.php");
