<?php
// Simulate the AJAX request for getting students
$_GET['ajax'] = 'get_students';
$_GET['class_id'] = '6'; // Assuming class ID 6 exists
$_GET['session'] = '2025-2026'; // Using one of the sessions we found

chdir('fees');
require_once '../config/database.php';
require_once '../config/database.php';

// Copy the AJAX handler code here for testing
$class_id = $_GET['class_id'] ?? '';
$session = $_GET['session'] ?? '';
$group_name = $_GET['group_name'] ?? '';

$where_conditions = ["s.status = 'active'"];
$params = [];

if (!empty($class_id)) {
    $where_conditions[] = "s.class_id = ?";
    $params[] = $class_id;
}

if (!empty($session)) {
    $where_conditions[] = "s.session = ?";
    $params[] = $session;
}

// Handle group filtering properly
if ($group_name !== '') {
    $where_conditions[] = "COALESCE(s.group_name, '') = ?";
    $params[] = $group_name;
}

$where_clause = implode(' AND ', $where_conditions);

$sql = "
    SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number, s.session, s.group_name, s.scholarship, c.name as class_name, c.section as class_section,
           COALESCE(SUM(f.amount - f.paid_amount), 0) as total_due
    FROM students s
    JOIN classes c ON s.class_id = c.id
    LEFT JOIN fees f ON s.id = f.student_id AND f.status != 'paid'
    WHERE $where_clause
    GROUP BY s.id, s.student_id, s.first_name, s.last_name, s.roll_number, s.session, s.group_name, s.scholarship, c.name, c.section
    ORDER BY s.roll_number
";

try {
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $students = $stmt->fetchAll();
    
    // Clean up group names to handle encoding issues
    foreach ($students as &$student) {
        if (isset($student['group_name'])) {
            $student['group_name'] = trim($student['group_name']);
        }
    }
    
    echo json_encode($students);
} catch (Exception $e) {
    error_log("Error loading students: " . $e->getMessage());
    echo json_encode([]);
}
?>