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

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

// Debug: Log the POST data
error_log("POST data: " . print_r($_POST, true));

if (isset($_POST['exam_id']) && isset($_POST['class_id']) && isset($_POST['section_ids'])) {
    $examId = intval($_POST['exam_id']);
    $classId = intval($_POST['class_id']);
    $sectionIds = $_POST['section_ids'];
    
    error_log("Exam ID: $examId, Class ID: $classId");
    
    if (!is_array($sectionIds)) {
        $sectionIds = [$sectionIds];
    }
    
    $sanitizedSectionIds = array_map('intval', $sectionIds);
    $sectionList = implode(',', $sanitizedSectionIds);
    
    error_log("Section IDs: $sectionList");
    
    // First, let's see what students are being fetched
    $studentsQuery = "SELECT 
                        s.student_id, 
                        s.name,
                        scsd.section_id
                      FROM student_class_section_data scsd
                      INNER JOIN students s ON scsd.student_id = s.student_id
                      WHERE scsd.class_id = $classId
                        AND scsd.section_id IN ($sectionList)
                        AND scsd.status = 'active'
                      ORDER BY scsd.section_id, s.name
                      LIMIT 10";
    
    error_log("Students query: $studentsQuery");
    
    $studentsResult = $conn->query($studentsQuery);
    $studentIds = [];
    while ($row = $studentsResult->fetch_assoc()) {
        $studentIds[] = $row['student_id'];
        error_log("Student ID: {$row['student_id']}, Name: {$row['name']}, Section: {$row['section_id']}");
    }
    
    // Now check if these students have symbol numbers
    if (!empty($studentIds)) {
        $studentIdList = implode(',', $studentIds);
        $symbolQuery = "SELECT student_id, symbol_no 
                       FROM symbolno_data 
                       WHERE exam_id = $examId 
                       AND student_id IN ($studentIdList)";
        
        error_log("Symbol query: $symbolQuery");
        
        $symbolResult = $conn->query($symbolQuery);
        while ($row = $symbolResult->fetch_assoc()) {
            error_log("Found symbol for student {$row['student_id']}: {$row['symbol_no']}");
        }
    }
    
    // Now run the actual query
    $query = "SELECT 
                s.student_id, 
                s.regd_id, 
                s.registration_no, 
                s.name, 
                scsd.class_id, 
                c.class as class_name, 
                scsd.section_id,
                sec.section_name as section,
                sn.symbol_no
              FROM student_class_section_data scsd
              INNER JOIN students s ON scsd.student_id = s.student_id
              INNER JOIN classes c ON scsd.class_id = c.class_id
              LEFT JOIN sections sec ON scsd.section_id = sec.section_id
              LEFT JOIN symbolno_data sn ON sn.student_id = s.student_id 
                AND sn.exam_id = ?
              WHERE scsd.class_id = ?
                AND scsd.section_id IN ($sectionList)
                AND scsd.status = 'active'
              ORDER BY scsd.section_id, s.registration_no, s.name";
    
    $stmt = $conn->prepare($query);
    if (!$stmt) {
        error_log("Prepare error: " . $conn->error);
        die(json_encode(["error" => "Prepare failed: " . $conn->error]));
    }
    
    $stmt->bind_param("ii", $examId, $classId);
    
    if (!$stmt->execute()) {
        error_log("Execute error: " . $stmt->error);
        die(json_encode(["error" => "Execute failed: " . $stmt->error]));
    }
    
    $result = $stmt->get_result();
    
    $students = [];
    while ($row = $result->fetch_assoc()) {
        error_log("Fetched student ID: {$row['student_id']}, Symbol: " . ($row['symbol_no'] ?: 'NULL'));
        $students[] = [
            'student_id' => $row['student_id'],
            'regd_id' => $row['regd_id'],
            'registration_no' => $row['registration_no'],
            'name' => $row['name'],
            'class_id' => $row['class_id'],
            'class_name' => $row['class_name'],
            'section_id' => $row['section_id'],
            'section' => $row['section'] ?: 'N/A',
            'symbol_no' => $row['symbol_no']
        ];
    }
    
    error_log("Total students fetched: " . count($students));
    
    echo json_encode($students);
    
    $stmt->close();
} else {
    echo json_encode(["error" => "Required parameters missing"]);
}

$conn->close();
?>