<?php
/**
 * ===================================================================================
 * Teacher Dashboard Page (Mobile Responsive)
 * ===================================================================================
 *
 * File: dashboard.php
 * Location: /homework_portal/teacher/dashboard.php
 *
 * Purpose:
 * 1. Provides a responsive dashboard for teachers with all original features.
 * 2. Includes notification badges for new submissions and messages.
 * 3. Adapts for mobile, tablet, and desktop screens.
 */

require_once '../config.php';

// --- Security Check ---
if (!isset($_SESSION['teacher_id'])) {
    header('Location: login.php');
    exit();
}
$teacher_id = $_SESSION['teacher_id'];
$teacher_full_name = e($_SESSION['teacher_full_name'] ?? 'Teacher');

// --- Fetch Dashboard Data ---
try {
    // Fetch assigned classes/subjects
    $sql = "SELECT c.class_name, s.subject_name FROM teacher_subject_class tsc JOIN classes c ON tsc.class_id = c.id JOIN subjects s ON tsc.subject_id = s.id WHERE tsc.teacher_id = ? ORDER BY c.class_name ASC, s.subject_name ASC";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$teacher_id]);
    $assignments = $stmt->fetchAll();

    // Fetch the count of unread admin messages
    $unread_sql = "SELECT COUNT(id) FROM teacher_messages WHERE teacher_id = ? AND is_read = 0 AND sender_type = 'admin'";
    $unread_stmt = $pdo->prepare($unread_sql);
    $unread_stmt->execute([$teacher_id]);
    $unread_messages_count = $unread_stmt->fetchColumn();

    // Fetch count of new, unseen student submissions
    $new_submission_sql = "
        SELECT COUNT(sub.id) 
        FROM submissions sub
        JOIN assignments a ON sub.assignment_id = a.id
        LEFT JOIN teacher_seen_submissions tss ON sub.id = tss.submission_id AND tss.teacher_id = ?
        WHERE a.teacher_id = ? AND tss.submission_id IS NULL
    ";
    $new_submission_stmt = $pdo->prepare($new_submission_sql);
    $new_submission_stmt->execute([$teacher_id, $teacher_id]);
    $new_submission_count = $new_submission_stmt->fetchColumn();

} catch (PDOException $e) {
    error_log($e->getMessage());
    $assignments = [];
    $unread_messages_count = 0;
    $new_submission_count = 0; // Default to 0 on error
    $dashboard_error = "Could not fetch dashboard data.";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Teacher Dashboard - TTTEDDDEL</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&family=Baloo+2:wght@700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Poppins', sans-serif; background-color: #f0f9ff; }
        .font-brand { font-family: 'Baloo 2', cursive; }
        .sidebar-link { display: flex; align-items: center; padding: 0.75rem 1rem; border-radius: 0.5rem; font-weight: 500; transition: background-color 0.2s, color 0.2s; }
        .sidebar-link:hover, .sidebar-link.active { background-color: #e0f2fe; color: #0284c7; font-weight: 600; }
        .notification-badge { display: inline-flex; align-items: center; justify-content: center; min-width: 22px; height: 22px; padding: 0 4px; border-radius: 9999px; background-color: #ef4444; color: white; font-size: 0.75rem; font-weight: bold; }
    </style>
</head>
<body class="flex flex-col min-h-screen">
    <div class="relative min-h-screen md:flex">
        <!-- Mobile menu header -->
        <div class="md:hidden flex justify-between items-center bg-white p-4 shadow-md">
             <a href="dashboard.php">
                <h1 class="text-3xl font-bold text-red-600 font-sans">TTTEDDDEL</h1>
            </a>
            <div class="flex items-center space-x-4">
                <a href="../logout.php" class="text-gray-500 hover:text-red-600" title="Logout">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                      <path stroke-linecap="round" stroke-linejoin="round" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
                    </svg>
                </a>
                <button id="mobile-menu-button" class="text-gray-500 hover:text-blue-600 focus:outline-none">
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16m-7 6h7"></path></svg>
                </button>
            </div>
        </div>

        <!-- Sidebar Navigation -->
        <aside id="sidebar" class="w-64 bg-white shadow-md absolute inset-y-0 left-0 transform -translate-x-full md:relative md:translate-x-0 transition-transform duration-300 ease-in-out z-30">
            <div class="p-4 border-b text-center">
                <a href="dashboard.php">
                    <h1 class="text-4xl font-bold text-red-600 tracking-widest font-sans">TTTEDDDEL</h1>
                    <p class="text-xs font-semibold text-blue-800 mt-1">Teacher-Student Interactive System</p>
                    <p class="text-xs text-blue-800">by Ele Infocomm Technologies</p>
                </a>
            </div>
            <nav class="p-4 space-y-2">
                <a href="dashboard.php" class="sidebar-link active"><span>Dashboard</span></a>
                <a href="inbox.php" class="sidebar-link flex justify-between items-center">
                    <span>Inbox</span>
                    <?php if ($unread_messages_count > 0): ?><span class="notification-badge"><?php echo $unread_messages_count; ?></span><?php endif; ?>
                </a>
                <a href="manage_students.php" class="sidebar-link"><span>My Students</span></a>
                <a href="post_material.php" class="sidebar-link"><span>Post Material</span></a>
                <a href="my_materials.php" class="sidebar-link"><span>My Posted Materials</span></a>
                <a href="view_submissions.php" class="sidebar-link flex justify-between items-center">
                    <span>View Submissions</span>
                    <?php if ($new_submission_count > 0): ?>
                        <span class="notification-badge"><?php echo $new_submission_count; ?></span>
                    <?php endif; ?>
                </a>
            </nav>
        </aside>

        <!-- Main Content Area -->
        <div class="flex-1 flex flex-col overflow-hidden">
            <header class="bg-white shadow-sm border-b hidden md:flex"><div class="flex items-center justify-end p-4 w-full"><span class="text-gray-600 mr-4">Welcome, <?php echo $teacher_full_name; ?>!</span><a href="../logout.php" class="ml-2 py-2 px-4 bg-teal-600 text-white font-semibold rounded-lg shadow-md hover:bg-teal-700">Logout</a></div></header>
            
            <main class="flex-1 overflow-x-hidden overflow-y-auto bg-gray-100 p-4 md:p-6">
                <h2 class="text-3xl font-semibold text-gray-800">Teacher Dashboard</h2>
            
                <div class="mt-6 bg-white p-6 rounded-lg shadow">
                    <h3 class="text-xl font-semibold text-gray-800 mb-4">My Assigned Classes & Subjects</h3>
                    <?php if (isset($dashboard_error)): ?>
                        <p class="text-red-500"><?php echo e($dashboard_error); ?></p>
                    <?php elseif (empty($assignments)): ?>
                        <p class="text-gray-500">You have not been assigned to any classes or subjects yet. Please contact the administrator.</p>
                    <?php else: ?>
                        <ul class="space-y-2 list-disc list-inside">
                            <?php foreach($assignments as $assignment): ?>
                                <li><span class="font-semibold"><?php echo e($assignment['class_name']); ?></span> - <span><?php echo e($assignment['subject_name']); ?></span></li>
                            <?php endforeach; ?>
                        </ul>
                    <?php endif; ?>
                </div>

                <div class="mt-8">
                     <h3 class="text-xl font-semibold text-gray-800 mb-4">Quick Actions</h3>
                     <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                         <a href="post_material.php" class="block p-6 bg-white rounded-lg shadow hover:bg-sky-50 transition-colors"><h4 class="font-semibold text-lg text-sky-700">Post New Material</h4><p class="text-sm text-gray-500 mt-1">Create and upload a new assignment for your students.</p></a>
                         <a href="manage_students.php" class="block p-6 bg-white rounded-lg shadow hover:bg-sky-50 transition-colors"><h4 class="font-semibold text-lg text-sky-700">Manage Students</h4><p class="text-sm text-gray-500 mt-1">View your student list and create new student accounts.</p></a>
                         <a href="view_submissions.php" class="block p-6 bg-white rounded-lg shadow hover:bg-sky-50 transition-colors"><h4 class="font-semibold text-lg text-sky-700">View Submissions</h4><p class="text-sm text-gray-500 mt-1">Check and grade work submitted by your students.</p></a>
                         <a href="my_materials.php" class="block p-6 bg-white rounded-lg shadow hover:bg-sky-50 transition-colors"><h4 class="font-semibold text-lg text-sky-700">My Posted Materials</h4><p class="text-sm text-gray-500 mt-1">View and manage all the content you have uploaded.</p></a>
                     </div>
                </div>
            </main>
        </div>
    </div>
    <footer class="text-center py-6 bg-gray-100 border-t mt-auto">
        <p class="text-xs text-gray-500">Built By Ele InfoComm Technologies- Kenya | <a href="http://web.e-ict.co.ke" target="_blank" class="hover:underline">web.e-ict.co.ke</a> | <a href="mailto:info@e-ict.co.ke" class="hover:underline">info@e-ict.co.ke</a> | +254202000121 | +254 722 215810 | 2025 All right reserved.</p>
    </footer>

    <script>
        const btn = document.getElementById('mobile-menu-button');
        const sidebar = document.getElementById('sidebar');

        btn.addEventListener('click', () => {
            sidebar.classList.toggle('-translate-x-full');
        });
    </script>
</body>
</html>
