<?php
session_start();

// Include access control functions
require_once 'includes/access_control.php';
require_once 'config/database.php';

// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "<h1>Detailed Debug: My Students Page</h1>";

try {
    // 1. Check authentication
    echo "<h2>1. Authentication Check</h2>";
    if (!isset($_SESSION['user_id'])) {
        echo "<p style='color: red;'>ERROR: User not logged in</p>";
        echo "<p>Session data: " . print_r($_SESSION, true) . "</p>";
        exit;
    }

    echo "<p>User ID: " . $_SESSION['user_id'] . "</p>";
    echo "<p>User Role: " . ($_SESSION['user_role'] ?? 'Not set') . "</p>";
    echo "<p>User Name: " . ($_SESSION['user_name'] ?? $_SESSION['username'] ?? 'Not set') . "</p>";

    if (!is_teacher()) {
        echo "<p style='color: red;'>ERROR: User is not a teacher</p>";
        exit;
    }

    echo "<p style='color: green;'>✓ User is logged in as teacher</p>";

    // 2. Check teacher record
    echo "<h2>2. Teacher Record Check</h2>";
    $teacher_id = null;
    $stmt = $pdo->prepare("SELECT * FROM teachers WHERE user_id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $teacher = $stmt->fetch();

    if ($teacher) {
        $teacher_id = $teacher['id'];
        echo "<p style='color: green;'>✓ Teacher record found: " . $teacher['first_name'] . ' ' . $teacher['last_name'] . " (ID: $teacher_id)</p>";
    } else {
        echo "<p style='color: red;'>ERROR: No teacher record found for user_id: " . $_SESSION['user_id'] . "</p>";
        exit;
    }

    // 3. Check class_teachers table
    echo "<h2>3. Class Teachers Table Check</h2>";
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM class_teachers WHERE teacher_id = ? AND status = 'active'");
    $stmt->execute([$teacher_id]);
    $assignment_count = $stmt->fetchColumn();
    echo "<p>Active assignments in class_teachers: $assignment_count</p>";

    if ($assignment_count > 0) {
        $stmt = $pdo->prepare("
            SELECT ct.*, c.name, c.section, c.status as class_status
            FROM class_teachers ct
            JOIN classes c ON ct.class_id = c.id
            WHERE ct.teacher_id = ? AND ct.status = 'active'
        ");
        $stmt->execute([$teacher_id]);
        $assignments = $stmt->fetchAll();
        echo "<p>Assignments details:</p>";
        echo "<pre>" . print_r($assignments, true) . "</pre>";
    }

    // 4. Test get_teacher_assigned_classes function
    echo "<h2>4. get_teacher_assigned_classes Function Test</h2>";
    $assigned_class_ids = get_teacher_assigned_classes($teacher_id);
    echo "<p>Function returned class IDs: " . print_r($assigned_class_ids, true) . "</p>";

    // 5. Check if auto-assignment is needed
    echo "<h2>5. Auto-assignment Check</h2>";
    if (empty($assigned_class_ids)) {
        echo "<p style='color: orange;'>⚠️ No assigned classes found. Auto-assignment would trigger.</p>";

        // Test auto-assignment query
        $stmt = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active'");
        $all_classes = $stmt->fetchAll();
        echo "<p>All active classes: " . count($all_classes) . "</p>";
        echo "<pre>" . print_r($all_classes, true) . "</pre>";

        if (!empty($all_classes)) {
            echo "<p>Auto-assignment would assign " . count($all_classes) . " classes</p>";
        } else {
            echo "<p style='color: red;'>ERROR: No active classes found in database!</p>";
        }
    } else {
        echo "<p style='color: green;'>✓ Teacher has assigned classes: " . implode(', ', $assigned_class_ids) . "</p>";
    }

    // 6. Test assigned classes query
    echo "<h2>6. Assigned Classes Query Test</h2>";
    if (!empty($assigned_class_ids)) {
        $placeholders = str_repeat('?,', count($assigned_class_ids) - 1) . '?';
        $stmt = $pdo->prepare("
            SELECT DISTINCT c.id, c.name, c.section, 'assigned' as assignment_type
            FROM classes c
            WHERE c.id IN ($placeholders) AND c.status = 'active'
            ORDER BY c.name, c.section
        ");
        $stmt->execute($assigned_class_ids);
        $assigned_classes = $stmt->fetchAll();
        echo "<p>Assigned classes query result: " . count($assigned_classes) . " classes</p>";
        echo "<pre>" . print_r($assigned_classes, true) . "</pre>";

        $class_ids = array_column($assigned_classes, 'id');
        echo "<p>Class IDs array: " . print_r($class_ids, true) . "</p>";
    } else {
        echo "<p>Skipping assigned classes query (no assigned class IDs)</p>";
    }

    // 7. Check students in database
    echo "<h2>7. Students Check</h2>";
    $stmt = $pdo->query("SELECT COUNT(*) FROM students WHERE status = 'active'");
    $total_students = $stmt->fetchColumn();
    echo "<p>Total active students: $total_students</p>";

    if ($total_students > 0) {
        // Check students by class
        $stmt = $pdo->query("SELECT class_id, COUNT(*) as count FROM students WHERE status = 'active' GROUP BY class_id");
        $students_by_class = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
        echo "<p>Students by class: " . print_r($students_by_class, true) . "</p>";
    }

    // 8. Test final student query logic
    echo "<h2>8. Final Student Query Test</h2>";
    $class_ids = !empty($assigned_class_ids) ? $assigned_class_ids : [];

    if (!empty($class_ids)) {
        $placeholders = str_repeat('?,', count($class_ids) - 1) . '?';
        $where_clause = "s.status = 'active' AND s.class_id IN ($placeholders)";

        $sql = "SELECT COUNT(*) FROM students s LEFT JOIN classes c ON s.class_id = c.id WHERE $where_clause";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($class_ids);
        $student_count = $stmt->fetchColumn();

        echo "<p style='color: green;'>✓ Student query successful. Students found: $student_count</p>";

        if ($student_count > 0) {
            // Show sample students
            $sql = "SELECT s.id, s.student_id, s.first_name, s.last_name, s.roll_number, c.name as class_name, c.section
                    FROM students s LEFT JOIN classes c ON s.class_id = c.id
                    WHERE $where_clause LIMIT 5";
            $stmt = $pdo->prepare($sql);
            $stmt->execute($class_ids);
            $sample_students = $stmt->fetchAll();
            echo "<p>Sample students:</p>";
            echo "<pre>" . print_r($sample_students, true) . "</pre>";
        }
    } else {
        echo "<p style='color: red;'>❌ No class IDs available for student query. Students will not show!</p>";
    }

    // 9. Summary
    echo "<h2>9. Summary</h2>";
    if (empty($assigned_class_ids)) {
        echo "<p style='color: red;'>PROBLEM: Teacher has no assigned classes</p>";
        echo "<p>SOLUTION: Auto-assignment should handle this, but let's check if it runs properly</p>";
    } elseif (empty($class_ids)) {
        echo "<p style='color: red;'>PROBLEM: Class IDs array is empty</p>";
        echo "<p>SOLUTION: The assigned classes query is failing</p>";
    } elseif ($student_count == 0) {
        echo "<p style='color: orange;'>PROBLEM: No students in assigned classes</p>";
        echo "<p>SOLUTION: Add students to the assigned classes</p>";
    } else {
        echo "<p style='color: green;'>SUCCESS: Everything looks good. Students should show on the page.</p>";
    }

} catch (Exception $e) {
    echo "<p style='color: red;'>ERROR: " . $e->getMessage() . "</p>";
    echo "<p>Stack trace: " . $e->getTraceAsString() . "</p>";
}
?>
