<?php
/**
 * Outstanding fee items for one student, for the Record Payment modal's
 * bulk-select checklist (fees.php). Replaces a single "pick one fee
 * structure" dropdown with "here's everything this student still owes,
 * check as many as you're being paid for right now".
 */
declare(strict_types=1);
if (session_status() === PHP_SESSION_NONE) session_start();
header('Content-Type: application/json');

require_once '../config.php';
require_once '../ai/fee_balance.php';

if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'] ?? '', ['admin', 'accountant', 'cashier'], true)) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Access denied.']);
    exit;
}

$conn = getDBConnection();
if (!$conn) {
    echo json_encode(['success' => false, 'message' => 'Database connection failed.']);
    exit;
}

$studentId = (int) ($_GET['student_id'] ?? 0);
if ($studentId <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid student.']);
    exit;
}

$stmt = $conn->prepare("SELECT id, first_name, last_name, class FROM students WHERE id = ? AND status = 'active' LIMIT 1");
$stmt->bind_param('i', $studentId);
$stmt->execute();
$student = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$student) {
    echo json_encode(['success' => false, 'message' => 'Student not found or inactive.']);
    exit;
}

$context = rbcCheckoutFeeContext($conn, $studentId, (string) $student['class'], getAcademicYear());

$items = array_map(static function (array $row): array {
    return [
        'fee_structure_id' => $row['fee_structure_id'],
        'fee_type'         => $row['fee_type'],
        'term'             => $row['term'],
        'is_current_term'  => $row['is_current_term'],
        'is_feeding'       => $row['is_feeding'],
        'amount'           => $row['amount'],
        'paid'             => $row['paid'],
        'remaining'        => $row['remaining'],
    ];
}, $context['items']);

echo json_encode([
    'success'           => true,
    'student'           => [
        'id'    => (int) $student['id'],
        'name'  => trim($student['first_name'] . ' ' . $student['last_name']),
        'class' => (string) $student['class'],
    ],
    'current_term'      => $context['current_term'],
    'max_weeks_covered'  => $context['max_weeks_covered'],
    'items'             => $items,
]);
