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

if(isset($_GET['class_id']) && !empty($_GET['class_id'])) {
    $class_id = intval($_GET['class_id']);
    
    // Get class name
    $class_name_query = "SELECT class FROM classes WHERE class_id = ?";
    $class_stmt = $conn->prepare($class_name_query);
    $class_stmt->bind_param("i", $class_id);
    $class_stmt->execute();
    $class_result = $class_stmt->get_result();
    $class_row = $class_result->fetch_assoc();
    $class_name = $class_row ? $class_row['class'] : '';
    
    // First, try to get sections from class_section table
    $sql = "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
            ORDER BY s.section_name";
    
    $stmt = $conn->prepare($sql);
    
    if ($stmt) {
        $stmt->bind_param("i", $class_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $sections = [];
        if ($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
                $sections[] = [
                    'section_id' => $row['section_id'],
                    'section_name' => $row['section_name'],
                    'class_name' => $class_name
                ];
            }
        }
        
        // If no sections found in class_section, get all active sections
        if (empty($sections)) {
            $all_sections_sql = "SELECT section_id, section_name FROM sections WHERE status = 1 ORDER BY section_name";
            $all_sections_result = $conn->query($all_sections_sql);
            
            while($row = $all_sections_result->fetch_assoc()) {
                $sections[] = [
                    'section_id' => $row['section_id'],
                    'section_name' => $row['section_name'],
                    'class_name' => $class_name
                ];
            }
        }
        
        header('Content-Type: application/json');
        echo json_encode($sections);
        $stmt->close();
    } else {
        header('Content-Type: application/json');
        echo json_encode([]);
    }
} else {
    header('Content-Type: application/json');
    echo json_encode(['error' => 'No class ID provided']);
}
?>