<?php
include('includes/dbconnection.php');

$regno   = $_GET['regno']   ?? '';
$session = $_GET['session'] ?? '';
$term    = $_GET['term']    ?? '';

$result = ['total_session' => 0, 'total_term' => 0];

if (empty($regno) || empty($session)) {
    echo json_encode($result);
    exit;
}

// Get student name (payment table uses studentName, not regno)
$stStmt = $con->prepare("SELECT studentName FROM students WHERE studentRegNo = ? LIMIT 1");
$stStmt->bind_param("s", $regno);
$stStmt->execute();
$stRow = $stStmt->get_result()->fetch_assoc();
$stStmt->close();

if (!$stRow) {
    echo json_encode($result);
    exit;
}

$studentName = $stRow['studentName'];

// Total paid this session
$sessStmt = $con->prepare(
    "SELECT SUM(amount) as total FROM payment
     WHERE studentName = ? AND session = ? AND pay_for LIKE '%School Fees%'"
);
$sessStmt->bind_param("ss", $studentName, $session);
$sessStmt->execute();
$sessRow = $sessStmt->get_result()->fetch_assoc();
$sessStmt->close();
$result['total_session'] = $sessRow['total'] ?? 0;

// Total paid this term
if (!empty($term)) {
    $termStmt = $con->prepare(
        "SELECT SUM(amount) as total FROM payment
         WHERE studentName = ? AND session = ? AND term = ? AND pay_for LIKE '%School Fees%'"
    );
    $termStmt->bind_param("sss", $studentName, $session, $term);
    $termStmt->execute();
    $termRow = $termStmt->get_result()->fetch_assoc();
    $termStmt->close();
    $result['total_term'] = $termRow['total'] ?? 0;
}

echo json_encode($result);
$con->close();
?>
