<?php
/**
 * Example AJAX files with proper filtering logic
 * Based on your database structure using MySQLi
 */

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'] ?? 0);
$teacher_id = (int)($_POST['teacher_id'] ?? $_SESSION['id']);
$action = $_POST['action'] ?? 'get_exam_subjects';

// ============================================================================
// EXAMPLE 1: ajax_get_exam_subjects.php
// Returns subjects that the teacher can access for a specific exam
// ============================================================================

if ($action === 'get_exam_subjects') {
    if ($exam_id == 0 || $school_id == 0) {
        echo json_encode(['success' => false, 'message' => 'Missing exam_id or school_id']);
        exit;
    }

    try {
        // Get subjects that the teacher is assigned to for this school
        // AND that have marks entered for this exam (or are available for the exam)
        $sql = "SELECT DISTINCT
                    s.id as subject_id,
                    s.name as subject_name,
                    s.code as subject_code,
                    cst.stream_id,
                    st.name as stream_name,
                    c.id as class_id,
                    c.name as class_name
                FROM subjects s
                INNER JOIN class_subject_teachers cst ON s.id = cst.subject_id
                INNER JOIN streams st ON cst.stream_id = st.id
                INNER JOIN classes c ON st.class_id = c.id
                LEFT JOIN marks m ON s.id = m.subject_id AND m.exam_id = ?
                WHERE cst.teacher_user_id = ?
                  AND cst.school_id = ?
                ORDER BY c.name, st.name, s.name";

        $stmt = $conn->prepare($sql);
        $stmt->bind_param("iii", $exam_id, $teacher_id, $school_id);
        $stmt->execute();
        $result = $stmt->get_result();

        $subjects = [];
        while ($row = $result->fetch_assoc()) {
            $subjects[] = [
                'subject_id' => $row['subject_id'],
                'subject_name' => $row['subject_name'],
                'subject_code' => $row['subject_code'],
                'stream_id' => $row['stream_id'],
                'stream_name' => $row['stream_name'],
                'class_id' => $row['class_id'],
                'class_name' => $row['class_name']
            ];
        }

        echo json_encode([
            'success' => true,
            'subjects' => $subjects,
            'count' => count($subjects),
            'debug' => [
                'exam_id' => $exam_id,
                'teacher_id' => $teacher_id,
                'school_id' => $school_id
            ]
        ]);

        $stmt->close();

    } catch (Exception $e) {
        echo json_encode([
            'success' => false,
            'message' => 'Error fetching subjects: ' . $e->getMessage()
        ]);
    }
}

// ============================================================================
// EXAMPLE 2: ajax_get_students_for_marks.php  
// Returns students for a specific exam, subject, class, and stream
// ============================================================================

elseif ($action === 'get_students_for_marks') {
    $exam_id = (int)($_POST['exam_id'] ?? 0);
    $subject_id = (int)($_POST['subject_id'] ?? 0);
    $class_id = (int)($_POST['class_id'] ?? 0);
    $stream_id = (int)($_POST['stream_id'] ?? 0);
    $school_id = (int)($_POST['school_id'] ?? 0);

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

    try {
        // Verify teacher has permission for this subject/stream
        $verify_sql = "SELECT COUNT(*) as count FROM class_subject_teachers 
                       WHERE teacher_user_id = ? AND subject_id = ? AND stream_id = ? AND school_id = ?";
        $verify_stmt = $conn->prepare($verify_sql);
        $verify_stmt->bind_param("iiii", $teacher_id, $subject_id, $stream_id, $school_id);
        $verify_stmt->execute();
        $verify_result = $verify_stmt->get_result();
        $verify_row = $verify_result->fetch_assoc();

        if ($verify_row['count'] == 0) {
            echo json_encode(['success' => false, 'message' => 'Teacher not authorized for this subject/stream']);
            $verify_stmt->close();
            exit;
        }
        $verify_stmt->close();

        // Get students in the specific class and stream
        $sql = "SELECT 
                    u.id as user_id,
                    u.username,
                    u.ADM,
                    COALESCE(CONCAT(u.username, ' (', u.ADM, ')'), u.username) as display_name,
                    m.mark as current_mark,
                    m.id as mark_id
                FROM users u
                INNER JOIN streams st ON u.stream_id = st.id
                LEFT JOIN marks m ON (u.id = m.student_id 
                                    AND m.exam_id = ? 
                                    AND m.subject_id = ? 
                                    AND m.stream_id = ?)
                WHERE u.school_id = ? 
                  AND u.role = 3 
                  AND st.id = ?
                  AND st.class_id = ?
                ORDER BY u.username";

        $stmt = $conn->prepare($sql);
        $stmt->bind_param("iiiiii", $exam_id, $subject_id, $stream_id, $school_id, $stream_id, $class_id);
        $stmt->execute();
        $result = $stmt->get_result();

        $students = [];
        while ($row = $result->fetch_assoc()) {
            $students[] = [
                'user_id' => $row['user_id'],
                'username' => $row['username'],
                'display_name' => $row['display_name'],
                'current_mark' => $row['current_mark'],
                'mark_id' => $row['mark_id']
            ];
        }

        echo json_encode([
            'success' => true,
            'students' => $students,
            'count' => count($students),
            'debug' => [
                'exam_id' => $exam_id,
                'subject_id' => $subject_id,
                'class_id' => $class_id,
                'stream_id' => $stream_id,
                'school_id' => $school_id,
                'teacher_id' => $teacher_id
            ]
        ]);

        $stmt->close();

    } catch (Exception $e) {
        echo json_encode([
            'success' => false,
            'message' => 'Error fetching students: ' . $e->getMessage()
        ]);
    }
}

// ============================================================================
// EXAMPLE 3: ajax_get_students_for_activity.php
// Returns students for integration activities (similar to marks but different table)
// ============================================================================

elseif ($action === 'get_students_for_activity') {
    $activity_id = (int)($_POST['activity_id'] ?? 0);
    $stream_id = (int)($_POST['stream_id'] ?? 0);
    $subject_id = (int)($_POST['subject_id'] ?? 0);
    $school_id = (int)($_POST['school_id'] ?? 0);

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

    try {
        // Get all students in this stream with their current activity marks
        $sql = "SELECT 
                    u.id as user_id,
                    u.username,
                    u.ADM,
                    COALESCE(CONCAT(u.username, ' (', u.ADM, ')'), u.username) as display_name,
                    iam.marks as current_mark,
                    iam.id as activity_mark_id
                FROM users u
                LEFT JOIN integration_activity_marks iam ON (u.id = iam.student_id 
                                                            AND iam.activity_id = ?)
                WHERE u.stream_id = ? 
                  AND u.school_id = ? 
                  AND u.role = 3
                ORDER BY u.username";

        $stmt = $conn->prepare($sql);
        $stmt->bind_param("iii", $activity_id, $stream_id, $school_id);
        $stmt->execute();
        $result = $stmt->get_result();

        $students = [];
        while ($row = $result->fetch_assoc()) {
            $students[] = [
                'user_id' => $row['user_id'],
                'username' => $row['username'],
                'display_name' => $row['display_name'],
                'current_mark' => $row['current_mark'],
                'activity_mark_id' => $row['activity_mark_id']
            ];
        }

        echo json_encode([
            'success' => true,
            'students' => $students,
            'count' => count($students),
            'debug' => [
                'activity_id' => $activity_id,
                'stream_id' => $stream_id,
                'subject_id' => $subject_id,
                'school_id' => $school_id,
                'teacher_id' => $teacher_id
            ]
        ]);

        $stmt->close();

    } catch (Exception $e) {
        echo json_encode([
            'success' => false,
            'message' => 'Error fetching students: ' . $e->getMessage()
        ]);
    }
}

else {
    echo json_encode(['success' => false, 'message' => 'Invalid action']);
}
?>