<?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>Debug: My Students Page</h1>";

// Check if user is logged in and is a teacher
echo "<h2>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>";

// Get teacher ID
echo "<h2>Teacher ID Check</h2>";
$teacher_id = null;
try {
    $stmt = $pdo->prepare("SELECT id 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 ID found: $teacher_id</p>";
    } else {
        echo "<p style='color: red;'>ERROR: No teacher record found for user_id: " . $_SESSION['user_id'] . "</p>";
        exit;
    }
} catch (Exception $e) {
    echo "<p style='color: red;'>ERROR: Database query failed: " . $e->getMessage() . "</p>";
    exit;
}

// Get teacher's assigned classes
echo "<h2>Assigned Classes Check</h2>";
$assigned_classes = [];
$assigned_class_ids = [];
if ($teacher_id) {
    $assigned_class_ids = get_teacher_assigned_classes($teacher_id);
    echo "<p>Assigned class IDs: " . print_r($assigned_class_ids, true) . "</p>";

    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 style='color: green;'>✓ Found " . count($assigned_classes) . " assigned classes</p>";
        echo "<p>Classes: " . print_r($assigned_classes, true) . "</p>";
    } else {
        echo "<p style='color: red;'>ERROR: No classes assigned to this teacher</p>";
    }
}

// Check class_teachers table
echo "<h2>Class Teachers Table Check</h2>";
try {
    $stmt = $pdo->query("SELECT COUNT(*) FROM class_teachers WHERE teacher_id = $teacher_id AND status = 'active'");
    $count = $stmt->fetchColumn();
    echo "<p>Class teachers records: $count</p>";
} catch (Exception $e) {
    echo "<p style='color: red;'>ERROR: class_teachers table check failed: " . $e->getMessage() . "</p>";
}

// Check students table
echo "<h2>Students Query Test</h2>";
$class_ids = array_column($assigned_classes, 'id');
echo "<p>Class IDs for query: " . print_r($class_ids, true) . "</p>";

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

    try {
        $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);
        $total_students = $stmt->fetchColumn();

        echo "<p style='color: green;'>✓ Found $total_students students for this teacher</p>";

        // Show a few sample students
        $sql = "SELECT s.*, c.name as class_name, c.section as class_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 "<h3>Sample Students:</h3>";
        echo "<pre>" . print_r($sample_students, true) . "</pre>";

    } catch (Exception $e) {
        echo "<p style='color: red;'>ERROR: Students query failed: " . $e->getMessage() . "</p>";
    }
} else {
    echo "<p style='color: red;'>ERROR: No class IDs to query students</p>";
}

echo "<h2>Conclusion</h2>";
if (empty($assigned_class_ids)) {
    echo "<p style='color: red;'>PROBLEM: Teacher has no assigned classes. This is why the page shows no students.</p>";
    echo "<p>SOLUTION: Assign classes to this teacher in the admin panel.</p>";
} elseif ($total_students == 0) {
    echo "<p style='color: orange;'>WARNING: Teacher has assigned classes but no students in those classes.</p>";
    echo "<p>SOLUTION: Add students to the assigned classes.</p>";
} else {
    echo "<p style='color: green;'>Everything looks good! The teacher should see students on the page.</p>";
}
?>
