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

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

$query = "SELECT s.section_id, s.section_name 
          FROM sections s
          INNER JOIN class_section cs ON s.section_id = cs.section_id
          WHERE cs.class_id = ? AND s.status = 1";
          
if (!empty($section_ids)) {
    $sectionArray = explode(',', $section_ids);
    $placeholders = implode(',', array_fill(0, count($sectionArray), '?'));
    $query .= " AND s.section_id IN ($placeholders)";
}

$query .= " ORDER BY s.section_name";

$stmt = $conn->prepare($query);

if (!empty($section_ids)) {
    $params = array_merge([$class_id], $sectionArray);
    $stmt->bind_param(str_repeat('i', count($params)), ...$params);
} else {
    $stmt->bind_param("i", $class_id);
}

$stmt->execute();
$result = $stmt->get_result();

$sections = [];
while ($row = $result->fetch_assoc()) {
    $sections[] = $row;
}

echo json_encode($sections);
?>