<?php
/**
 * Check and fix teacher assignments for my_students.php
 */

require_once 'config/database.php';
error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "<h1>Teacher Assignment Check</h1>";

try {
    // 1. Check current user session
    session_start();
    echo "<h2>Current User Session</h2>";
    if (isset($_SESSION['user_id'])) {
        echo "<p>Logged in as user_id: " . $_SESSION['user_id'] . "</p>";
        echo "<p>Role: " . ($_SESSION['user_role'] ?? 'Not set') . "</p>";
        echo "<p>Name: " . ($_SESSION['user_name'] ?? $_SESSION['username'] ?? 'Not set') . "</p>";

        // Check if this user is a teacher
        $stmt = $pdo->prepare("SELECT * FROM teachers WHERE user_id = ?");
        $stmt->execute([$_SESSION['user_id']]);
        $teacher = $stmt->fetch();

        if ($teacher) {
            echo "<p style='color: green;'>✅ Teacher record found: " . $teacher['first_name'] . ' ' . $teacher['last_name'] . "</p>";
            $teacher_id = $teacher['id'];

            // Check class assignments
            echo "<h2>Class Assignments</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 class assignments: $assignment_count</p>";

            if ($assignment_count == 0) {
                echo "<p style='color: red;'>❌ No classes assigned to this teacher!</p>";
                echo "<p>This is why my_students.php shows no students.</p>";

                // Auto-assign this teacher to first available class
                $stmt = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' LIMIT 1");
                $class = $stmt->fetch();

                if ($class) {
                    echo "<p>Found available class: {$class['name']} {$class['section']}</p>";
                    echo "<p>Assigning teacher to this class...</p>";

                    $stmt = $pdo->prepare("
                        INSERT INTO class_teachers (class_id, teacher_id, assignment_type, status)
                        VALUES (?, ?, 'primary', 'active')
                    ");
                    $stmt->execute([$class['id'], $teacher_id]);

                    echo "<p style='color: green;'>✅ Teacher assigned to class!</p>";
                } else {
                    echo "<p style='color: red;'>❌ No active classes found to assign</p>";
                }
            } else {
                // Show assigned classes
                $stmt = $pdo->prepare("
                    SELECT c.name, c.section, ct.assignment_type
                    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]);
                $assigned_classes = $stmt->fetchAll();

                echo "<h3>Assigned Classes:</h3>";
                echo "<ul>";
                foreach ($assigned_classes as $class) {
                    echo "<li>{$class['name']} {$class['section']} ({$class['assignment_type']})</li>";
                }
                echo "</ul>";
            }

            // Check students in assigned classes
            echo "<h2>Students in Assigned Classes</h2>";
            $stmt = $pdo->prepare("
                SELECT COUNT(*) as student_count
                FROM students s
                JOIN class_teachers ct ON s.class_id = ct.class_id
                WHERE ct.teacher_id = ? AND ct.status = 'active' AND s.status = 'active'
            ");
            $stmt->execute([$teacher_id]);
            $student_count = $stmt->fetch()['student_count'];

            echo "<p>Students in assigned classes: $student_count</p>";

            if ($student_count == 0) {
                echo "<p style='color: orange;'>⚠️ No students in assigned classes.</p>";
                echo "<p>You need to add students to see them in my_students.php</p>";

                // Check if there are any students at all
                $stmt = $pdo->query("SELECT COUNT(*) FROM students WHERE status = 'active'");
                $total_students = $stmt->fetchColumn();
                echo "<p>Total active students in system: $total_students</p>";

                if ($total_students == 0) {
                    echo "<p style='color: red;'>❌ No students in the system at all!</p>";
                    echo "<p>You need to add students first.</p>";
                }
            } else {
                echo "<p style='color: green;'>✅ Students found! my_students.php should work now.</p>";
            }

        } else {
            echo "<p style='color: red;'>❌ No teacher record found for this user!</p>";
            echo "<p>This user is not registered as a teacher.</p>";
        }

    } else {
        echo "<p style='color: red;'>❌ Not logged in!</p>";
        echo "<p>Please login first to access my_students.php</p>";
    }

    echo "<h2>Quick Actions</h2>";
    echo "<ul>";
    echo "<li><a href='teachers/my_students.php'>Go to My Students page</a></li>";
    echo "<li><a href='simple_test.php'>Run basic system test</a></li>";
    echo "<li><a href='debug_my_students.php'>Run detailed debug</a></li>";
    echo "</ul>";

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