<?php
/**
 * ajax_get_exam_subjects.php - WITH PAPER SUPPORT
 * Gets teacher's assigned subjects with paper information
 */

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) {
    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
    ];
    
    // 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;
    }
    
    while ($row_teacher = $result_teacher->fetch_assoc()) {
        // Get papers for this subject
        $papers = getSubjectPapers($row_teacher['subject_id'], $conn);
        $has_papers = !empty($papers);
        
        $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,
            'status' => 'Available',
            '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),
        '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();
?>