<?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($_REQUEST['academyLocationId']); // Get the active gateways
$requestUrl = isset($_REQUEST['requestUrl']) ? $_REQUEST['requestUrl'] : '';
$failToOpenPaymentGatewayPage = false;
$translationMsg = json_decode(TRANSLATION_MSG, true);
$dc = !empty($_REQUEST['_dc'])?$_REQUEST['_dc']:time();
function checkOnlinePaymentId($onlinePaymentId, $queryBuilder)
{
    if (isset($onlinePaymentId)) {
        $tableName = 'advance_payment';
        $where = ['onlinePaymentId' => $onlinePaymentId];
        $result = $queryBuilder->selectById($tableName, '*', $where);
        return ($result !== null) ? $result : 0;
    }
    return false;
}

function createOnlinePaymentId($data, $queryBuilder, $conn, $connMain)
{
    $academyLocationId = $data['academyLocationId'] ?? '';
    $advancePaymentObj = new AdvancePayment();
    $advancePaymentObj->setConnection($conn, $connMain);
    return $advancePaymentObj->createAdvancePaymentId($data);
}

// MAIN LOGIC - FIXED VERSION
if((count($_REQUEST) == 0) || (!isset($_REQUEST['onlinePaymentId']) || !isset($_REQUEST['studentId']) || !isset($_REQUEST['academyLocationId'])))
{
    $failToOpenPaymentGatewayPage = true;
    echo '<div class="col-md-12 text-center alert alert-warning">
            <h4>'.$translationMsg['TRANSACTION_ERROR'].'</h4>
        </div>';
}
else
{
    // Check if payment ID exists in database
    $checkId = checkOnlinePaymentId($_REQUEST['onlinePaymentId'], $queryBuilder);
    
    // FIX 1: Check payment status instead of just existence
    $isPaymentCompleted = false;
    if ($checkId && isset($checkId['paymentStatus'])) {
        // Assuming payment status field exists - adjust field name as per your database
        $completedStatuses = ['completed', 'success', 'paid', 'processed']; // Adjust as per your status values
        $isPaymentCompleted = in_array(strtolower($checkId['paymentStatus']), $completedStatuses);
    }
    
    // FIX 2: Handle gateway selection logic properly
    if (isset($_POST['paymentGateway'])) {
        // User has selected a gateway, process payment
        $_SESSION['gateway_selected'] = true;
        processGatewayPayment($checkId);
    }
    elseif (isset($_SESSION['gateway_selected']) && $_SESSION['gateway_selected'] === true && $checkId) {   
        // Gateway already selected in session, process payment
        processGatewayPayment($checkId);
    }
    elseif (!$checkId) {
        // No payment record exists, create new one
        $advancePaymentId = createOnlinePaymentId($_REQUEST, $queryBuilder, $conn, $connMain);
        if ($advancePaymentId == 'No_DATA') {
            $failToOpenPaymentGatewayPage = true;
            echo '<div class="col-md-12 text-center alert alert-warning">
                    <h4>'.$translationMsg['TRANSACTION_ERROR'].'</h4>
                 </div>';
        } else {            
            $_SESSION['gateway_selected'] = false;           
            displayGateways();
        }
    }
    elseif ($checkId && $isPaymentCompleted) {
        // Payment already completed - show appropriate message
        $failToOpenPaymentGatewayPage = true;
        echo '<div class="col-md-12 text-center alert alert-info">
                <h4>'.$translationMsg['TRANSACTION_ALREADY_PROCESSED'].'</h4>
            </div>';
    }
    else {
        // Payment record exists but not completed - allow user to proceed
        displayGateways();
    }
}

function displayGateways()
{
    global $activeGateways,$requestUrl,$translationMsg,$dc;
    
    // FIX 3: Don't unset session here if we want to maintain state
    // unset($_SESSION['gateway_selected']); // COMMENTED OUT
    
    if (count($activeGateways) === 1) {
        $singleGateway = reset($activeGateways);
        if ($singleGateway['activeStatus'] && strtolower($singleGateway['value']) !== 'grayquest') {
            $_SESSION['gateway_selected'] = true;
            echo '<form id="autoSubmitForm" method="POST" action="' . $_SERVER['PHP_SELF'] . '?_dc='. $dc .'&onlinePaymentId=' . $_REQUEST['onlinePaymentId'] . '&studentId='.$_REQUEST['studentId'].'&academyLocationId=' . $_REQUEST['academyLocationId'] . '">';
            echo '<input type="hidden" name="paymentGateway" value="' . $singleGateway['value'] . '">';
            echo '<input type="hidden" name="requestUrl" value="' . $requestUrl . '">';
            echo '</form>';
            echo '<script>document.getElementById("autoSubmitForm").submit();</script>';
            exit;
        }
    }
   
    if(count($activeGateways) > 1){
        $_SESSION['gateway_selected'] = false; // Set to false until user selects
        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'] . '?_dc='. $dc . '&onlinePaymentId=' . $_REQUEST['onlinePaymentId'] . '&studentId='.$_REQUEST['studentId'].'&academyLocationId=' . $_REQUEST['academyLocationId'] . '">
                <div class="row payment-row">';
                echo '<input type="hidden" name="requestUrl" value="' . $requestUrl . '">';
                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>';
    }
}

function processGatewayPayment($checkId)
{
    global $gatewayConfig, $activeGateways, $queryBuilder, $conn, $connMain, $translationMsg;
    
    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) {   
            $result = checkOnlinePaymentId($_REQUEST['onlinePaymentId'], $queryBuilder);
            $advancePaymentObj = new AdvancePayment();
            $gatewayConfig->set_session($selectedGatewayValue,true);
            
            if(isset($result['currency']) && $result['currency'] == 'R' && $selectedGateway['value'] == 'payu' || $selectedGateway['value'] == 'paygate')
            {
                $result['currency'] = 'ZAR';
            }          
            
            $merchantDetails = $advancePaymentObj->getStandardMerchantDetailsByAl($selectedGateway['value'], $_REQUEST['academyLocationId'], $result['currency']);
            $result['paymentOption'] = $selectedGateway['value'];
            $result['academyLocationId'] = $_REQUEST['academyLocationId'];
            
            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 {
                    $gatewayLoader = new PaymentGatewayLoader();
                    $tableName = 'advance_payment';
                    $gatewayLoader->loadPaymentGateway(strtolower($selectedGateway['value']), $conn, 'advance-payment', $result, $tableName,$merchantDetails[strtolower($selectedGateway['value'])]);
                    
                    // FIX 4: Only unset session after successful payment processing
                    unset($_SESSION['gateway_selected']);
                } catch (Exception $e) {
                    $failToOpenPaymentGatewayPage = true;
                    echo '<div class="col-md-12 text-center alert alert-warning">
                            <h4>'.$translationMsg['TRANSACTION_ERROR'].'</h4>
                          </div>';
                    // Clear session on error
                    unset($_SESSION['gateway_selected']);
                }
            }
            
        } else {
            $failToOpenPaymentGatewayPage = true;
            echo '<div class="col-md-12 text-center alert alert-warning">
                    <h4>'.$translationMsg['INVALID_PAYMENT_GATEWAY_SELECTED'].'</h4>
                  </div>';
        }
    }
    else {
        $failToOpenPaymentGatewayPage = true;
        unset($_SESSION['gateway_selected']);
        echo '<div class="col-md-12 text-center alert alert-warning">
                <h4>'.$translationMsg['INVALID_PAYMENT_GATEWAY_SELECTED'].'</h4>
              </div>';
    }
}

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

require_once("footer.php");
?>