<?php
/**
 * AJAX endpoint: returns subjects assigned to a given class
 * GET param: class_id (int)
 */
session_start();
require_once '../config/database.php';

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit();
}

header('Content-Type: application/json; charset=utf-8');

$class_id = isset($_GET['class_id']) ? (int)$_GET['class_id'] : 0;

if ($class_id <= 0) {
    // No class selected — return all active subjects as fallback
    $stmt = $pdo->query("SELECT id, name, code FROM subjects WHERE status = 'active' ORDER BY name");
    echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
    exit();
}

// Get subjects assigned to this class via class_subjects table
$stmt = $pdo->prepare("
    SELECT DISTINCT s.id, s.name, s.code
    FROM subjects s
    INNER JOIN class_subjects cs ON cs.subject_id = s.id
    WHERE cs.class_id = ? AND s.status = 'active'
    ORDER BY s.name
");
$stmt->execute([$class_id]);
$subjects = $stmt->fetchAll(PDO::FETCH_ASSOC);

// If no subjects assigned via class_subjects, fall back to all active subjects
if (empty($subjects)) {
    $stmt = $pdo->query("SELECT id, name, code FROM subjects WHERE status = 'active' ORDER BY name");
    $subjects = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

echo json_encode($subjects);
