<?php

include('includes/dbconnection.php');

// Support multiple session contexts (super admin, small admin, etc.)
$authenticated = false;

$sessionConfigs = [
    'super_admin_session' => dirname(__DIR__) . '/session_data/super',
    'small_admin_session' => dirname(__DIR__) . '/session_data/small',
];

foreach ($sessionConfigs as $sname => $savePath) {
    if (session_status() === PHP_SESSION_ACTIVE) {
        session_write_close();
    }
    if (is_dir($savePath)) {
        session_save_path($savePath);
    }
    session_name($sname);
    session_start();
    if (!empty($_SESSION['sid'])) {
        $authenticated = true;
        break;
    }
}

if (!$authenticated) {
    header('Content-Type: application/json');
    echo json_encode(['amount' => 0]);
    exit;
}



$fee_name = trim($_GET['fee_name'] ?? '');

$class    = trim($_GET['class']    ?? '');

$stream   = trim($_GET['stream']   ?? '');

$term     = trim($_GET['term']     ?? '');

$session  = trim($_GET['session']  ?? '');



if ($fee_name === '' || $class === '' || $stream === '' || $term === '' || $session === '') {

    header('Content-Type: application/json');

    echo json_encode(['amount' => 0]);

    exit;

}



$amount = 0.0;

// Priority 1: fee_records (session/term-specific)
$stmt = $con->prepare(
    "SELECT amount FROM fee_records
     WHERE name=? AND class=? AND stream=? AND session=? AND term=? AND student_type='Old'
     ORDER BY id DESC LIMIT 1"
);
$stmt->bind_param("sssss", $fee_name, $class, $stream, $session, $term);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();
$stmt->close();

if ($row && (float)$row['amount'] > 0) {
    $amount = (float)$row['amount'];
} else {
    // Fallback: fees catalogue
    $stmt2 = $con->prepare(
        "SELECT amount FROM fees
         WHERE name=? AND class=? AND stream=? AND student_type='Old'
         LIMIT 1"
    );
    $stmt2->bind_param("sss", $fee_name, $class, $stream);
    $stmt2->execute();
    $row2 = $stmt2->get_result()->fetch_assoc();
    $stmt2->close();

    if ($row2) {
        $amount = (float)$row2['amount'];
    }
}

// --- TEMP DEBUG REMOVED ---

header('Content-Type: application/json');
echo json_encode(['amount' => $amount]);

