<?php
// AJAX endpoint - do not include session.php (requires tab_id in GET, breaks AJAX)
session_name("student_portal");
session_start();
ob_start(); // Buffer any accidental output so JSON is never corrupted
include('includes/dbconnection.php');
require_once 'vendor/autoload.php';
require_once __DIR__ . '/includes/session_term_helper.php';
require_once __DIR__ . '/helpers/term_allocation_helpers.php';

// Validate session
if (empty($_SESSION['student_id'])) {
    ob_end_clean();
    header('Content-Type: application/json');
    echo json_encode(['status' => 'error', 'message' => 'Session expired. Please log in again.']);
    exit;
}

error_reporting(0);
ob_end_clean(); // Discard any output from includes
header('Content-Type: application/json');

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

$prefix = $_ENV['Admission_prefix'] ?? "REF";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $stdid      = mysqli_real_escape_string($con, $_POST['stdid']);
    $amount     = floatval($_POST['amount']);
    $feeType    = mysqli_real_escape_string($con, $_POST['feeType']);
    $paySession = trim($_POST['session'] ?? '');
    $reference  = $prefix . "-WLT-" . strtoupper(bin2hex(random_bytes(5)));
    $payment_for = 'Wallet Payment for ' . $feeType;

    // ── Future session guard (School Fees only) ───────────────────────────────
    // Validate BEFORE touching the wallet — if rejected, return error JSON
    if (stripos($feeType, 'School Fees') !== false && !empty($paySession)) {
        $stResult          = resolveCurrentSessionTerm($con);
        $activeSessionName = $stResult['session_name'];

        if (isFutureSession($paySession, $activeSessionName)) {
            $stuId   = (int)$stdid;
            $stuStmt = $con->prepare("SELECT class, stream FROM students WHERE id = ? LIMIT 1");
            $stuStmt->bind_param("i", $stuId);
            $stuStmt->execute();
            $stuRow = $stuStmt->get_result()->fetch_assoc();
            $stuStmt->close();

            if ($stuRow && !validateFutureSessionPayment($con, $stuId, $activeSessionName, $stuRow['class'], $stuRow['stream'], $paySession)) {
                echo json_encode([
                    'status'  => 'error',
                    'message' => 'Future session payment rejected: you still have unpaid fees in the current session (' . $activeSessionName . '). Please clear those first.'
                ]);
                exit;
            }
        }
    }

    mysqli_begin_transaction($con);

    try {

        $check  = mysqli_query($con, "SELECT balance FROM wallets WHERE student_id = '$stdid' FOR UPDATE");
        $wallet = mysqli_fetch_assoc($check);

        if (!$wallet) {
            throw new Exception("Wallet account not found.");
        }

        if ($wallet['balance'] < $amount) {
            throw new Exception("Insufficient Wallet Balance. Current: " . $wallet['balance']);
        }

        // 1. Deduct from wallet
        $deduct = mysqli_query($con, "UPDATE wallets SET balance = balance - $amount WHERE student_id = '$stdid'");
        if (!$deduct)
            throw new Exception("Failed to update wallet balance.");

        // 2. Log wallet transaction
        $logQuery = "INSERT INTO wallet_transactions (student_id, amount, reference, type, status) 
                     VALUES ('$stdid', '$amount', '$reference', '$payment_for', 'success')";

        if (!mysqli_query($con, $logQuery)) {
            throw new Exception("Failed to log transaction: " . mysqli_error($con));
        }

        mysqli_commit($con);

        echo json_encode([
            'status'    => 'success',
            'reference' => $reference
        ]);
        exit;

    } catch (Exception $e) {
        mysqli_rollback($con);
        echo json_encode([
            'status'  => 'error',
            'message' => $e->getMessage()
        ]);
        exit;
    }
}
?>