<?php
/**
 * AJAX endpoint to get exam subjects with individual class status
 * Modified to support class-by-class publishing instead of whole-exam locking
 */

session_start();
require_once 'config.php';

header('Content-Type: application/json');
error_reporting(0);
ini_set('display_errors', 0);

// Check if user is logged in and is a teacher
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || ($_SESSION["role"] !== 2 && $_SESSION["role"] !== 1)) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

// Get parameters
$exam_id = (int)($_POST['exam_id'] ?? 0);
$school_id = (int)($_POST['school_id'] ?? $_SESSION['school_id'] ?? 0);
$teacher_id = (int)($_POST['teacher_id'] ?? $_SESSION['id'] ?? 0);

if ($exam_id == 0 || $school_id == 0 || $teacher_id == 0) {
    echo json_encode([
        'success' => false,
        'message' => 'Missing required parameters',
        'debug' => [
            'exam_id' => $exam_id,
            'school_id' => $school_id,
            'teacher_id' => $teacher_id
        ]
    ]);
    exit;
}

try {
    $subjects = [];
    $debug_info = [
        'exam_id' => $exam_id,
        'teacher_id' => $teacher_id,
        'school_id' => $school_id
    ];
    
    // Check if exam_class_status table exists for class-level locking
    $table_exists = $conn->query("SHOW TABLES LIKE 'exam_class_status'")->num_rows > 0;
    $debug_info['class_level_locking'] = $table_exists;
    
    // STEP 1: Get all subjects that are assigned to this exam
    $sql_exam_subjects = "SELECT DISTINCT
                            es.subject_id,
                            s.subject_name,
                            s.subject_code
                        FROM exam_subjects es
                        INNER JOIN subjects s ON es.subject_id = s.subject_id
                        WHERE es.exam_id = ?
                          AND s.school_id = ?
                        ORDER BY s.subject_name";
    
    $stmt_exam = $conn->prepare($sql_exam_subjects);
    $stmt_exam->bind_param("ii", $exam_id, $school_id);
    $stmt_exam->execute();
    $result_exam = $stmt_exam->get_result();
    
    $exam_subject_ids = [];
    $exam_subjects_list = [];
    while ($row_exam = $result_exam->fetch_assoc()) {
        $exam_subject_ids[] = $row_exam['subject_id'];
        $exam_subjects_list[] = [
            'subject_id' => $row_exam['subject_id'],
            'subject_name' => $row_exam['subject_name'],
            'subject_code' => $row_exam['subject_code']
        ];
    }
    $stmt_exam->close();
    
    $debug_info['subjects_in_exam'] = $exam_subjects_list;
    $debug_info['total_subjects_in_exam'] = count($exam_subject_ids);
    
    if (empty($exam_subject_ids)) {
        echo json_encode([
            'success' => false,
            'message' => 'No subjects found in exam_subjects table for this exam',
            'debug' => $debug_info
        ]);
        exit;
    }
    
    // STEP 2: Get teacher assignments for those subject IDs
    $placeholders = str_repeat('?,', count($exam_subject_ids) - 1) . '?';
    
    $sql_teacher_assignments = "SELECT DISTINCT
                                cst.class_id,
                                c.class_name,
                                cst.stream_id,
                                st.stream_name,
                                cst.subject_id,
                                s.subject_name,
                                s.subject_code,
                                cst.academic_year,
                                cst.term
                            FROM class_subject_teachers cst
                            INNER JOIN subjects s ON cst.subject_id = s.subject_id
                            LEFT JOIN classes c ON cst.class_id = c.class_id
                            LEFT JOIN streams st ON cst.stream_id = st.stream_id
                            WHERE cst.teacher_user_id = ?
                              AND cst.school_id = ?
                              AND cst.subject_id IN ($placeholders)
                            ORDER BY c.class_name, st.stream_name, s.subject_name";
    
    // Prepare parameters: teacher_id, school_id, subject_ids...
    $params = array_merge([$teacher_id, $school_id], $exam_subject_ids);
    $param_types = str_repeat('i', count($params));
    
    $stmt_teacher = $conn->prepare($sql_teacher_assignments);
    $stmt_teacher->bind_param($param_types, ...$params);
    $stmt_teacher->execute();
    $result_teacher = $stmt_teacher->get_result();
    
    // Function to get subject papers
    function getSubjectPapers($subject_id, $conn) {
        $papers = [];
        $sql_papers = "SELECT paper_id, paper_name FROM subject_papers 
                      WHERE subject_id = ? ORDER BY paper_id";
        
        if ($stmt_papers = @$conn->prepare($sql_papers)) {
            $stmt_papers->bind_param("i", $subject_id);
            if ($stmt_papers->execute()) {
                $result_papers = $stmt_papers->get_result();
                while ($row_paper = $result_papers->fetch_assoc()) {
                    $papers[] = [
                        'paper_id' => $row_paper['paper_id'],
                        'paper_name' => $row_paper['paper_name']
                    ];
                }
            }
            $stmt_papers->close();
        }
        return $papers;
    }
    
    // Function to check if class is published
    function getClassExamStatus($exam_id, $class_id, $stream_id, $conn) {
        // Check if exam_class_status table exists
        $table_exists = $conn->query("SHOW TABLES LIKE 'exam_class_status'")->num_rows > 0;
        
        if ($table_exists) {
            // Use class-level checking
            $query = "
                SELECT status, published_at
                FROM exam_class_status
                WHERE exam_id = ?
                  AND class_id = ?
                  AND (stream_id = ? OR stream_id IS NULL OR ? = 0)
                ORDER BY published_at DESC
                LIMIT 1
            ";
            
            $stmt = $conn->prepare($query);
            $stream_id_param = $stream_id ?: 0;
            $stmt->bind_param("iiii", $exam_id, $class_id, $stream_id_param, $stream_id_param);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($status = $result->fetch_assoc()) {
                return [
                    'status' => $status['status'],
                    'published_date' => $status['published_at'],
                    'locking_type' => 'class_level'
                ];
            } else {
                // No specific class record, so it's available (Draft)
                return [
                    'status' => 'Draft',
                    'published_date' => null,
                    'locking_type' => 'class_level'
                ];
            }
            
            $stmt->close();
        } else {
            // Fallback to whole-exam checking
            $query = "SELECT status, updated_at FROM exams WHERE exam_id = ?";
            $stmt = $conn->prepare($query);
            $stmt->bind_param("i", $exam_id);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($exam = $result->fetch_assoc()) {
                return [
                    'status' => $exam['status'],
                    'published_date' => $exam['updated_at'],
                    'locking_type' => 'whole_exam'
                ];
            } else {
                return [
                    'status' => 'Draft',
                    'published_date' => null,
                    'locking_type' => 'whole_exam'
                ];
            }
            
            $stmt->close();
        }
    }
    
    while ($row_teacher = $result_teacher->fetch_assoc()) {
        // Get papers for this subject
        $papers = getSubjectPapers($row_teacher['subject_id'], $conn);
        $has_papers = !empty($papers);
        
        // Check individual class status
        $class_status = getClassExamStatus(
            $exam_id, 
            $row_teacher['class_id'], 
            $row_teacher['stream_id'], 
            $conn
        );
        
        $subjects[] = [
            'subject_id' => $row_teacher['subject_id'],
            'subject_name' => $row_teacher['subject_name'],
            'subject_code' => $row_teacher['subject_code'],
            'class_id' => $row_teacher['class_id'],
            'class_name' => $row_teacher['class_name'],
            'stream_id' => $row_teacher['stream_id'],
            'stream_name' => $row_teacher['stream_name'],
            'academic_year' => $row_teacher['academic_year'],
            'term' => $row_teacher['term'],
            'has_papers' => $has_papers,
            'papers' => $papers,
            'exam_status' => $class_status['status'],
            'published_date' => $class_status['published_date'],
            'locking_type' => $class_status['locking_type'],
            'display_name' => $row_teacher['class_name'] . ' - ' . $row_teacher['stream_name'] . ' - ' . $row_teacher['subject_name']
        ];
    }
    
    $stmt_teacher->close();
    
    $debug_info['total_teacher_matches'] = count($subjects);
    
    if (count($subjects) == 0) {
        $debug_info['note'] = 'Exam has subjects, but teacher is not assigned to any of them';
        $debug_info['teacher_should_teach'] = $exam_subject_ids;
    } else {
        $debug_info['note'] = 'Found ' . count($subjects) . ' subject assignments for this exam and teacher';
    }

    echo json_encode([
        'success' => true,
        'subjects' => $subjects, // Frontend expects "subjects"
        'count' => count($subjects),
        'class_level_locking' => $table_exists,
        'debug' => $debug_info
    ]);

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage(),
        'debug' => [
            'exam_id' => $exam_id,
            'teacher_id' => $teacher_id,
            'school_id' => $school_id,
            'error_details' => $e->getMessage()
        ]
    ]);
}

$conn->close();
?>