<?php
require 'config.php';
requireLogin(); // Ensure security

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

$class_id = $_GET['class_id'] ?? 0;
$subject_id = $_GET['subject_id'] ?? 0;

if (!$class_id || !$subject_id) {
    echo json_encode([]);
    exit;
}

// 1. Get all students in class
$stmt = $pdo->prepare("SELECT id, full_name FROM students WHERE class_id = ? ORDER BY full_name ASC");
$stmt->execute([$class_id]);
$students = $stmt->fetchAll(PDO::FETCH_ASSOC);

// 2. Get existing enrollments for this subject
$enrolled = [];
$e_stmt = $pdo->prepare("SELECT student_id FROM student_electives WHERE subject_id = ?");
$e_stmt->execute([$subject_id]);
$enrolled_raw = $e_stmt->fetchAll(PDO::FETCH_COLUMN);

// Convert to easy lookup map
foreach ($enrolled_raw as $eid) $enrolled[$eid] = true;

// 3. Merge data
$output = [];
foreach ($students as $s) {
    $s['is_enrolled'] = isset($enrolled[$s['id']]);
    $output[] = $s;
}

echo json_encode($output);
?>