<?php
/**
 * AJAX: returns subjects or groups for a given class_id
 * Used by bulk panels in students_with_subjects.php
 */
session_start();
if (!isset($_SESSION['user_id'])) { http_response_code(403); echo '[]'; exit; }

require_once '../config/database.php';
header('Content-Type: application/json; charset=utf-8');

$class_id = isset($_GET['class_id']) ? (int)$_GET['class_id'] : 0;
if (!$class_id) { echo '[]'; exit; }

// ── Return groups for this class ─────────────────────────────────────────────
if (!empty($_GET['groups'])) {
    // 'source' param: 'subjects' = from class_subjects table, default = from students table
    $source = $_GET['source'] ?? 'students';
    $groups = [];

    if ($source === 'subjects') {
        // Groups defined in class_subjects (teacher assignment based)
        $stmt = $pdo->prepare("
            SELECT DISTINCT group_name
            FROM class_subjects
            WHERE class_id = ? AND group_name IS NOT NULL AND group_name != ''
            ORDER BY group_name
        ");
        $stmt->execute([$class_id]);
    } else {
        // Groups from students table (student enrollment based)
        $stmt = $pdo->prepare("
            SELECT DISTINCT group_name
            FROM students
            WHERE class_id = ? AND group_name IS NOT NULL AND group_name != ''
            ORDER BY group_name
        ");
        $stmt->execute([$class_id]);
    }

    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $groups[] = (string)$row['group_name'];
    }
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(array_values($groups), JSON_UNESCAPED_UNICODE);
    exit;
}

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

// Fallback: subjects from student_subjects for students of this class
if (empty($rows)) {
    $stmt = $pdo->prepare("
        SELECT DISTINCT s.id, s.name, s.code
        FROM student_subjects ss
        JOIN students st ON ss.student_id = st.id
        JOIN subjects s ON ss.subject_id = s.id
        WHERE st.class_id = ? AND s.status = 'active'
        ORDER BY s.name
    ");
    $stmt->execute([$class_id]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

echo json_encode($rows);
