<?php
error_reporting(E_ALL);

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

$queryBuilder = new QueryBuilder($conn);
$gatewayConfig = new GatewayConfig();
$activeGateways = $gatewayConfig->getActiveGateway($_REQUEST['academyLocationId'] ?? '');

$requestUrl = $_REQUEST['requestUrl'] ?? '';
if(count($activeGateways) > 0){
    $translationMsg = json_decode(TRANSLATION_MSG, true);
    $failToOpenPaymentGatewayPage = false;
    
    function checkOnlinePaymentId($onlinePaymentId, $queryBuilder) {
        return !empty($onlinePaymentId) ? $queryBuilder->selectById('course_registration_payment', '*', ['onlinePaymentId' => $onlinePaymentId]) : false;
    }

    function createOnlinePaymentId($data, $queryBuilder, $conn, $connMain)
    {
        $advancePaymentObj = new CourseRegistrationPayment();
        $advancePaymentObj->setConnection($conn, $connMain);
        return $advancePaymentObj->createOnlinePaymentId($data);
    }   
    
    function displayGateways() {
        global $activeGateways, $requestUrl, $translationMsg , $singleGateway;
        
        unset($_SESSION['gateway_selected']);
    
        if (count($activeGateways) === 1) {
            $gateway = reset($activeGateways);
            if ($gateway['activeStatus'] && strtolower($singleGateway['value']) !== 'grayquest') {
                $_SESSION['gateway_selected'] = true;
                echo '<form id="autoSubmitForm" method="POST" action="' . htmlspecialchars($_SERVER['PHP_SELF']) . '?requestUrl='.htmlspecialchars($requestUrl) .'&academyLocationId='.$_REQUEST['academyLocationId'].'&paymentId='.$_REQUEST['paymentId'].'&admissionId='.$_REQUEST['admissionId'].'">
                        <input type="hidden" name="paymentGateway" value="' . $gateway['value'] . '">
                      </form>
                      <script>document.getElementById("autoSubmitForm").submit();</script>';
                exit;
            }
        }
    
        if (count($activeGateways) > 1) {
            $_SESSION['gateway_selected'] = true;
            echo '<div class="container d-flex justify-content-center align-items-center min-vh-100">
                    <div class="card p-4 card main-card-apyment" 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="' . htmlspecialchars($_SERVER['PHP_SELF']) . '?requestUrl='.htmlspecialchars($requestUrl) .'&academyLocationId='.$_REQUEST['academyLocationId'].'&paymentId='.$_REQUEST['paymentId'].'&admissionId='.$_REQUEST['admissionId'].'">
                            <div class="row payment-row">';
                    foreach ($activeGateways as $gateway) {
                        if ($gateway['activeStatus'] && strtolower($gateway['value']) !== 'grayquest') {
                            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{
            $failToOpenPaymentGatewayPage = true;
            echo '<div class="col-md-12 text-center alert alert-warning">
                    <h4>'.$translationMsg['MERCHANT_DETAILS_NOT_CONFIGURED'].'</h4>
                </div>';
        }
    }
    
    function processGatewayPayment($checkId) {
        global $gatewayConfig, $activeGateways, $queryBuilder, $translationMsg, $conn;
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['paymentGateway'])) {
            // $selectedGateway = array_filter($activeGateways, fn($g) => $g['value'] === $_POST['paymentGateway'])[0] ?? null;
            $selectedGatewayValue = $_POST['paymentGateway'];

            // Get the gateway details by its code
            $selectedGateway = null;
            foreach ($activeGateways as $gateway) {
                if ($gateway['value'] == $selectedGatewayValue) {
                    $selectedGateway = $gateway;
                    break;
                }
            }
    
            if ($selectedGateway) {
                $result = checkOnlinePaymentId($_REQUEST['paymentId'], $queryBuilder);
                if (!$result) {
                    $failToOpenPaymentGatewayPage = true;
                    echo '<div class="alert alert-warning text-center"><h4>' . $translationMsg['TRANSACTION_ERROR'] . '11</h4></div>';
                }else{
                    $courseRegPaymentObj = new CourseRegistrationPayment();
                    // echo $selectedGateway['value'].'---'.$_REQUEST['academyLocationId'].'---'. $result['currency'];
                    if(isset($result['currency']) && $result['currency'] == 'R' && $selectedGateway['value'] == 'payu' || $selectedGateway['value'] == 'paygate')
                    {
                        $result['currency'] = 'ZAR';
                    }
                    $merchantDetails = $courseRegPaymentObj->getStandardMerchantDetailsByAl($selectedGateway['value'], $_REQUEST['academyLocationId'], $result['currency']);
                    $result['paymentOption'] = $selectedGateway['value'];
                    if($merchantDetails == 'ACCESS_TOKEN')
                    {
                        $failToOpenPaymentGatewayPage = true;
                        echo '<div class="col-md-12 text-center alert alert-warning">
                                    <h4>'.$translationMsg['SERVER_ERROR'].'</h4>
                                </div>';
                    }
                    else if($merchantDetails == 'No_DATA')
                    {
                        $failToOpenPaymentGatewayPage = true;
                        echo '<div class="col-md-12 text-center alert alert-warning">
                                <h4>'.$translationMsg['MERCHANT_DETAILS_NOT_CONFIGURED'].'</h4>
                            </div>';
                    }else{ 
                        require_once('./config/paymentGatewayLoader.php');
                        try {
                            $tableName = 'course_registration_payment';
                            $gatewayLoader = new PaymentGatewayLoader();
                            $gatewayLoader->loadPaymentGateway(strtolower($selectedGateway['value']), $conn, 'course-registration-payment', $result, $tableName,$merchantDetails[strtolower($selectedGateway['value'])]);
                            unset($_SESSION['gateway_selected']);
                        } catch (Exception $e) {
                            $failToOpenPaymentGatewayPage = true;
                            echo '<div class="alert alert-warning text-center"><h4>' . $translationMsg['TRANSACTION_ERROR'] . '33</h4></div>';
                        }
                    }
                }
            }else{
                $failToOpenPaymentGatewayPage = true;
                echo '<div class="alert alert-warning text-center"><h4>' . $translationMsg['INVALID_PAYMENT_GATEWAY_SELECTED'] . '</h4></div>';
            }
    
        }
    }
    
    if (empty($_REQUEST['paymentId']) || empty($_REQUEST['admissionId']) || empty($_REQUEST['academyLocationId'])) {
        $failToOpenPaymentGatewayPage = true;
        echo '<div class="alert alert-warning text-center"><h4>' . $translationMsg['TRANSACTION_ERROR'] . '44</h4></div>';
    } else {
        $checkId = checkOnlinePaymentId($_REQUEST['paymentId'], $queryBuilder);
        if ($_SESSION['gateway_selected'] ?? false) {
            processGatewayPayment($checkId);
        } elseif (!$checkId) {
            $advancePaymentId = createOnlinePaymentId($_REQUEST, $queryBuilder, $conn, $connMain);
            if ($advancePaymentId === 'No_DATA') {
                $failToOpenPaymentGatewayPage = true;
                echo '<div class="alert alert-warning text-center"><h4>' . $translationMsg['TRANSACTION_ERROR'] . '22</h4></div>';
            } else {
                $_SESSION['gateway_selected'] = false;
                displayGateways();
            }
        } else {
            $failToOpenPaymentGatewayPage = true;
            echo '<div class="alert alert-warning text-center"><h4>' . $translationMsg['TRANSACTION_ALREADY_PROCESSED'] . '</h4></div>';
        }
    }
}else{
    echo '<div class="col-md-12 text-center alert alert-warning">
        <h4>'.$translationMsg['MERCHANT_DETAILS_NOT_CONFIGURED'].'</h4>
    </div>';
    $failToOpenPaymentGatewayPage = true;
}

if ($requestUrl && $failToOpenPaymentGatewayPage) {
    echo '<div class="text-center" id="gotohome">
          <a href="' . htmlspecialchars($requestUrl) . '" class="btn btn-primary">' . $translationMsg['GO_TO_Home_Page'] . '</a>
          </div>';
}

require_once("footer.php");