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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit();
}

// Get class_id from request
$class_id = $_GET['class_id'] ?? '';

if (empty($class_id)) {
    http_response_code(400);
    echo json_encode(['error' => 'Class ID is required']);
    exit();
}

try {
    // Get students for the specified class
    $stmt = $pdo->prepare("
        SELECT id, student_id, first_name, last_name, roll_number 
        FROM students 
        WHERE class_id = ? AND status = 'active' 
        ORDER BY roll_number
    ");
    $stmt->execute([$class_id]);
    $students = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Return JSON response
    header('Content-Type: application/json');
    echo json_encode($students);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}
?>