<?php
session_start();
require_once '../../config/database.php';

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

// Check if user is logged in and is admin/teacher
if (!isset($_SESSION['user_id']) || ($_SESSION['user_role'] !== 'admin' && $_SESSION['user_role'] !== 'teacher')) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

try {
    // Get query parameters
    $session_id = isset($_GET['session_id']) ? (int)$_GET['session_id'] : 0;
    $class_id = isset($_GET['class_id']) ? (int)$_GET['class_id'] : 0;
    $search = isset($_GET['search']) ? trim($_GET['search']) : '';
    
    // Build query based on filters
    $where_conditions = [];
    $params = [];
    
    // Always filter for active students
    $where_conditions[] = "s.status = 'active'";
    
    // Add session filter if provided
    if ($session_id > 0) {
        $where_conditions[] = "s.session_id = ?";
        $params[] = $session_id;
    }
    
    // Add class filter if provided
    if ($class_id > 0) {
        $where_conditions[] = "s.class_id = ?";
        $params[] = $class_id;
    }
    
    // Add search filter if provided
    if (!empty($search)) {
        $where_conditions[] = "(s.first_name LIKE ? OR s.last_name LIKE ? OR s.student_id LIKE ? OR s.roll_number LIKE ?)";
        $params[] = "%$search%";
        $params[] = "%$search%";
        $params[] = "%$search%";
        $params[] = "%$search%";
    }
    
    $where_clause = '';
    if (!empty($where_conditions)) {
        $where_clause = "WHERE " . implode(" AND ", $where_conditions);
    }
    
    // Get students with related data
    $stmt = $pdo->prepare("
        SELECT 
            s.id,
            s.student_id,
            s.first_name,
            s.last_name,
            s.roll_number,
            c.name as class_name
        FROM students s
        JOIN classes c ON s.class_id = c.id
        $where_clause
        ORDER BY s.class_id, s.roll_number
        LIMIT 100
    ");
    
    $stmt->execute($params);
    $students = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode(['success' => true, 'students' => $students]);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error fetching students: ' . $e->getMessage()]);
}
?>