<?php
/**
 * ===================================================================================
 * Super Admin Dashboard (Interactive & Secure)
 * ===================================================================================
 *
 * File: dashboard.php
 * Location: /homework_portal/admin/dashboard.php
 *
 * Purpose:
 * 1. The main hub for all administrators.
 * 2. Provides interactive stat cards that link to management pages.
 * 3. Displays navigation links based on user role and permissions.
 */

require_once '../config.php';
require_once 'admin_helpers.php'; // Correctly include the helper file

// --- Security Check ---
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit();
}

$admin_id = $_SESSION['admin_id'];
$admin_username = e($_SESSION['admin_username'] ?? 'Admin');

// --- Fetch user role and dashboard stats ---
try {
    $stmt = $pdo->prepare("SELECT role, permissions FROM super_admins WHERE id = ?");
    $stmt->execute([$admin_id]);
    $current_admin = $stmt->fetch();
    
    // Set session variables if not already set (e.g., after initial login)
    if ($current_admin && !isset($_SESSION['is_super_admin'])) {
        if ($current_admin['role'] === 'super_admin') {
            $_SESSION['is_super_admin'] = true;
            $_SESSION['admin_permissions'] = [];
        } else {
            $_SESSION['is_super_admin'] = false;
            $_SESSION['admin_permissions'] = json_decode($current_admin['permissions'] ?? '[]', true);
        }
    }
    
    $teacher_count = $pdo->query("SELECT COUNT(id) FROM teachers")->fetchColumn();
    $student_count = $pdo->query("SELECT COUNT(id) FROM students")->fetchColumn();
    $class_count = $pdo->query("SELECT COUNT(id) FROM classes")->fetchColumn();
    $subject_count = $pdo->query("SELECT COUNT(id) FROM subjects")->fetchColumn();
    $unread_count = $pdo->query("SELECT COUNT(id) FROM teacher_messages WHERE sender_type = 'teacher' AND is_read = 0")->fetchColumn();

} catch (PDOException $e) {
    // Graceful error handling in case of a database issue
    $page_error = "Could not load dashboard statistics. Please check the database connection.";
    $teacher_count = $student_count = $class_count = $subject_count = $unread_count = 0;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin 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; transition: background-color 0.2s, color 0.2s; }
        .sidebar-link:hover, .sidebar-link.active { background-color: #e0f2fe; color: #0284c7; }
        .notification-badge { display: inline-flex; align-items: center; justify-content: center; width: 22px; height: 22px; border-radius: 9999px; background-color: #ef4444; color: white; font-size: 0.75rem; font-weight: bold; }
        .stat-card { transition: transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out; }
        .stat-card:hover { transform: translateY(-5px); box-shadow: 0 8px 25px rgba(0,0,0,0.1); }
    </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 flex flex-col">
            <div>
                <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_count > 0): ?><span class="notification-badge"><?php echo $unread_count; ?></span><?php endif; ?>
                    </a>
                    <?php if (has_permission('manage_admins')): ?><a href="manage_admins.php" class="sidebar-link"><span>Manage Admins</span></a><?php endif; ?>
                    <?php if (has_permission('manage_teachers')): ?><a href="manage_teachers.php" class="sidebar-link"><span>Manage Teachers</span></a><?php endif; ?>
                    <?php if (has_permission('manage_classes')): ?><a href="manage_classes.php" class="sidebar-link"><span>Manage Classes</span></a><?php endif; ?>
                    <?php if (has_permission('manage_subjects')): ?><a href="manage_subjects.php" class="sidebar-link"><span>Manage Subjects</span></a><?php endif; ?>
                    <?php if (has_permission('assign_subjects')): ?><a href="assign_subjects.php" class="sidebar-link"><span>Assign Subjects</span></a><?php endif; ?>
                    <?php if (has_permission('send_message')): ?><a href="send_message.php" class="sidebar-link"><span>Send Message</span></a><?php endif; ?>
                </nav>
            </div>
            <div class="mt-auto p-4 border-t">
                 <a href="account_settings.php" class="sidebar-link"><span>Account Settings</span></a>
                 <a href="logout.php" class="sidebar-link"><span>Logout</span></a>
            </div>
        </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 $admin_username; ?>!</span><a href="account_settings.php" class="p-2 text-gray-500 hover:text-blue-600" title="Account Settings"><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="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" /><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" /></svg></a><a href="logout.php" class="ml-2 py-2 px-4 bg-blue-600 text-white font-semibold rounded-lg shadow-md hover:bg-blue-700">Logout</a></div></header>

            <main class="flex-1 overflow-x-hidden overflow-y-auto bg-gray-100 p-4 md:p-6">
                 <?php if (isset($page_error)): ?><div class="p-4 my-4 text-sm text-red-800 bg-red-100 rounded-lg"><?php echo $page_error; ?></div><?php endif; ?>
                <?php if (isset($_GET['error'])): ?><div class="p-4 my-4 text-sm text-red-800 bg-red-100 rounded-lg"><?php echo e($_GET['error']); ?></div><?php endif; ?>
                
                <h2 class="text-3xl font-semibold text-gray-800">Admin Dashboard</h2>
                
                <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 md:gap-6 mt-6">
                    <a href="manage_teachers.php" class="stat-card bg-white p-6 rounded-lg shadow block"><h3 class="text-lg font-medium text-gray-500">Total Teachers</h3><p class="text-4xl font-bold text-blue-600"><?php echo $teacher_count; ?></p></a>
                    <a href="#" class="stat-card bg-white p-6 rounded-lg shadow block"><h3 class="text-lg font-medium text-gray-500">Total Students</h3><p class="text-4xl font-bold text-green-600"><?php echo $student_count; ?></p></a>
                    <a href="manage_classes.php" class="stat-card bg-white p-6 rounded-lg shadow block"><h3 class="text-lg font-medium text-gray-500">Total Classes</h3><p class="text-4xl font-bold text-yellow-600"><?php echo $class_count; ?></p></a>
                    <a href="manage_subjects.php" class="stat-card bg-white p-6 rounded-lg shadow block"><h3 class="text-lg font-medium text-gray-500">Total Subjects</h3><p class="text-4xl font-bold text-indigo-600"><?php echo $subject_count; ?></p></a>
                </div>
            </main>
        </div>
    </div>
    <footer class="text-center py-6 bg-gray-100 border-t mt-auto">
        <p class="text-sm 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>
