<?php
session_start();
require_once 'config/database.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    // Create a temporary session for testing
    $_SESSION['user_id'] = 1;
    $_SESSION['user_role'] = 'admin';
    $_SESSION['user_name'] = 'Admin User';
}

echo "<h2>Assignment Debug</h2>";
echo "<p>User Role: " . $_SESSION['user_role'] . "</p>";

try {
    // Fetch assignments
    if ($_SESSION['user_role'] == 'admin' || $_SESSION['user_role'] == 'teacher') {
        $stmt = $pdo->prepare("
            SELECT a.*, c.name as class_name, c.section as class_section, s.name as subject_name 
            FROM assignments a
            JOIN classes c ON a.class_id = c.id
            JOIN subjects s ON a.subject_id = s.id
            ORDER BY a.created_at DESC
            LIMIT 20
        ");
        $stmt->execute();
        echo "<p>Admin/Teacher query executed</p>";
    } else {
        $stmt = $pdo->prepare("
            SELECT a.*, c.name as class_name, c.section as class_section, s.name as subject_name 
            FROM assignments a
            JOIN classes c ON a.class_id = c.id
            JOIN subjects s ON a.subject_id = s.id
            WHERE a.class_id = (SELECT class_id FROM students WHERE user_id = ?)
            AND a.status = 'published'
            ORDER BY a.created_at DESC
            LIMIT 20
        ");
        $stmt->execute([$_SESSION['user_id']]);
        echo "<p>Student query executed</p>";
    }
    
    $assignments = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo "<p>Assignments found: " . count($assignments) . "</p>";
    
    if (count($assignments) > 0) {
        echo "<table border='1'>";
        echo "<tr><th>ID</th><th>Title</th><th>Class</th><th>Subject</th><th>Status</th></tr>";
        foreach ($assignments as $assignment) {
            echo "<tr>";
            echo "<td>" . $assignment['id'] . "</td>";
            echo "<td>" . htmlspecialchars($assignment['title']) . "</td>";
            echo "<td>" . htmlspecialchars($assignment['class_name'] . ' - ' . $assignment['class_section']) . "</td>";
            echo "<td>" . htmlspecialchars($assignment['subject_name']) . "</td>";
            echo "<td>" . $assignment['status'] . "</td>";
            echo "</tr>";
        }
        echo "</table>";
    } else {
        echo "<p>No assignments found</p>";
    }
} catch (Exception $e) {
    echo "<p>Error: " . $e->getMessage() . "</p>";
}
?>