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

header('Content-Type: application/json');

if(isset($_GET['class_id']) && !empty($_GET['class_id'])) {
    $class_id = intval($_GET['class_id']);
    
    // First, try to get sections from class_section table
    $sql = "SELECT s.section_id, s.section_name, c.class as class_name
            FROM sections s
            INNER JOIN class_section cs ON s.section_id = cs.section_id
            INNER JOIN classes c ON cs.class_id = c.class_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' => $row['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);
            
            // Get class name for display
            $class_name_sql = "SELECT class FROM classes WHERE class_id = ?";
            $class_stmt = $conn->prepare($class_name_sql);
            $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'] : 'Selected Class';
            
            while($row = $all_sections_result->fetch_assoc()) {
                $sections[] = [
                    'section_id' => $row['section_id'],
                    'section_name' => $row['section_name'],
                    'class_name' => $class_name
                ];
            }
        }
        
        echo json_encode($sections);
        $stmt->close();
    } else {
        // Fallback: get all sections
        $fallback_sql = "SELECT section_id, section_name FROM sections WHERE status = 1 ORDER BY section_name";
        $fallback_result = $conn->query($fallback_sql);
        
        $sections = [];
        while($row = $fallback_result->fetch_assoc()) {
            $sections[] = [
                'section_id' => $row['section_id'],
                'section_name' => $row['section_name'],
                'class_name' => 'All'
            ];
        }
        
        echo json_encode($sections);
    }
} else {
    echo json_encode(['error' => 'No class ID provided']);
}
?>