<?php
include("includes/db.php");

if (isset($_GET['exam_id'])) {
    $examId = $_GET['exam_id'];

    // Get assigned_class from examination_type
    $examQuery = "SELECT assigned_class FROM examination_type WHERE id = ?";
    $stmt = $conn->prepare($examQuery);
    $stmt->bind_param("i", $examId);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($row = $result->fetch_assoc()) {
        $assignedClassIds = explode(',', $row['assigned_class']); // Convert to array

        // Fetch class details
        $placeholders = implode(',', array_fill(0, count($assignedClassIds), '?'));
        $classQuery = "SELECT class_id, class_name, section FROM classes WHERE class_id IN ($placeholders) AND status = 'on'";
        
        $stmt = $conn->prepare($classQuery);
        $stmt->bind_param(str_repeat("i", count($assignedClassIds)), ...$assignedClassIds);
        $stmt->execute();
        $classResult = $stmt->get_result();

        $classes = [];
        while ($classRow = $classResult->fetch_assoc()) {
            $classes[] = $classRow;
        }
        echo json_encode($classes);
    } else {
        echo json_encode([]);
    }
}
?>
