<?php
session_start();
require 'db_connection.php';

/* ---------------- AUTH ---------------- */
if (!isset($_SESSION['username'])) {
    header("Location: login.php");
    exit();
}

$username = $_SESSION['username'];
$user_role = $_SESSION['role'] ?? 'general';

/* ---------------- SETTINGS ---------------- */
$settings = [
    'school_name'    => 'School',
    'school_tagline' => '',
    'logo'           => ''
];

$stmt = $conn->prepare("SELECT school_name, school_tagline, logo FROM settings WHERE id = 1");
$stmt->execute();
$settings = $stmt->get_result()->fetch_assoc() ?? $settings;

/* ---------------- FINANCE ---------------- */
$total_income  = (float) (($conn->query("SELECT SUM(amount) AS total FROM income")->fetch_assoc()['total'] ?? 0));
$total_expense = (float) (($conn->query("SELECT SUM(amount) AS total FROM expenses")->fetch_assoc()['total'] ?? 0));

/* ---------------- COUNTS ---------------- */
function countRole($conn, $role)
{
    $stmt = $conn->prepare("SELECT COUNT(*) AS t FROM users WHERE role = ?");
    $stmt->bind_param("s", $role);
    $stmt->execute();

    $result = $stmt->get_result()->fetch_assoc();
    return (int) ($result['t'] ?? 0);
}

$total_students = countRole($conn, 'student');
$total_teachers = countRole($conn, 'teacher');
$total_parents  = countRole($conn, 'parent');

/* ---------------- NOTIFICATIONS ---------------- */
$notif_sql = "
    SELECT n.id, n.message_head, n.message_body, n.created_at, r.status
    FROM notifications n
    JOIN notification_recipients r ON n.id = r.notification_id
    WHERE r.role = ? OR r.role = 'general'
    ORDER BY n.created_at DESC
    LIMIT 6
";

$stmt = $conn->prepare($notif_sql);
$stmt->bind_param("s", $user_role);
$stmt->execute();
$notifications = $stmt->get_result();

/* Unread count */
$count_sql = "
    SELECT COUNT(*) AS total
    FROM notification_recipients
    WHERE (role = ? OR role = 'general') AND status = 'unread'
";

$stmt2 = $conn->prepare($count_sql);
$stmt2->bind_param("s", $user_role);
$stmt2->execute();
$unread_count = (int) ($stmt2->get_result()->fetch_assoc()['total'] ?? 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</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

    <style>
        :root {
            --primary: #3a57e8;
            --sidebar-width: 280px;
            --sidebar-collapsed: 78px;
            --content-bg: #f5f7ff;
            --card-radius: 18px;
        }

        * {
            box-sizing: border-box;
        }

        body {
            background: var(--content-bg);
            overflow-x: hidden;
        }

        /* SIDEBAR */
        #sidebar {
            position: fixed;
            top: 0;
            left: 0;
            width: var(--sidebar-width);
            height: 100vh;
            background: var(--primary);
            color: #fff;
            overflow-y: auto;
            transition: width 0.3s ease;
            z-index: 1030;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.12);
        }

        #sidebar.collapsed {
            width: var(--sidebar-collapsed);
        }

        #sidebar a {
            color: #fff;
            text-decoration: none;
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 12px 20px;
            transition: background 0.2s ease;
        }

        #sidebar a:hover {
            background: rgba(255, 255, 255, 0.1);
        }

        #sidebar .menu-icon {
            width: 20px;
            text-align: center;
            flex-shrink: 0;
        }

        .hide-text {
            white-space: nowrap;
            transition: opacity 0.2s ease;
        }

        #sidebar.collapsed .hide-text {
            display: none;
        }

        .sidebar-header {
            text-align: center;
            padding: 20px 15px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.12);
        }

        .school-logo {
            width: 70px;
            height: 70px;
            object-fit: cover;
            border-radius: 50%;
            border: 2px solid rgba(255, 255, 255, 0.35);
            margin-bottom: 10px;
        }

        .submenu {
            padding-left: 14px;
            background: rgba(0, 0, 0, 0.08);
            display: none;
        }

        .submenu.show {
            display: block;
        }

        .submenu a {
            font-size: 0.95rem;
            padding-left: 18px;
        }

        /* CONTENT */
        #content {
            margin-left: var(--sidebar-width);
            padding: 22px;
            transition: margin-left 0.3s ease;
            width: calc(100% - var(--sidebar-width));
            min-height: 100vh;
        }

        #content.expanded {
            margin-left: var(--sidebar-collapsed);
            width: calc(100% - var(--sidebar-collapsed));
        }

        .card-soft,
        .panel-soft {
            background: #fff;
            border-radius: var(--card-radius);
            box-shadow: 0 8px 24px rgba(15, 23, 42, 0.06);
            border: 1px solid rgba(15, 23, 42, 0.04);
        }

        .stat-card {
            padding: 22px;
            text-align: center;
            border-radius: var(--card-radius);
            background: #fff;
            box-shadow: 0 8px 24px rgba(15, 23, 42, 0.06);
            border: 1px solid rgba(15, 23, 42, 0.04);
            height: 100%;
        }

        .stat-card h3 {
            margin-bottom: 6px;
            font-weight: 700;
        }

        .topbar {
            margin-bottom: 24px;
        }

        .notification-dropdown {
            width: 340px;
            max-width: calc(100vw - 24px);
        }

        @media (max-width: 768px) {
            #sidebar {
                transform: translateX(0);
            }

            #content {
                margin-left: 0;
                width: 100%;
                padding: 16px;
            }

            #content.expanded {
                margin-left: 0;
                width: 100%;
            }
        }
    </style>
</head>

<body>

<!-- SIDEBAR -->
<nav id="sidebar">
    <div class="sidebar-header">
        <?php if (!empty($settings['logo'])): ?>
            <img src="uploads/<?= htmlspecialchars($settings['logo']) ?>" alt="School Logo" class="school-logo">
        <?php endif; ?>

        <h5 class="hide-text mb-1"><?= htmlspecialchars($settings['school_name']) ?></h5>
        <small class="hide-text"><?= htmlspecialchars($settings['school_tagline']) ?></small>
    </div>

    <a href="#">
        <i class="fas fa-home menu-icon"></i>
        <span class="hide-text">Dashboard</span>
    </a>

    <a data-bs-toggle="collapse" href="#adminMenu" role="button" aria-expanded="false" aria-controls="adminMenu">
        <i class="fas fa-user-shield menu-icon"></i>
        <span class="hide-text">Admin Management</span>
    </a>
    <div class="collapse submenu" id="adminMenu">
        <a href="register.php">Add Admin</a>
    </div>

    <a data-bs-toggle="collapse" href="#subjectMenu" role="button" aria-expanded="false" aria-controls="subjectMenu">
        <i class="fas fa-book menu-icon"></i>
        <span class="hide-text">Subjects</span>
    </a>
    <div class="collapse submenu" id="subjectMenu">
        <a href="add_subject.php">Add Subject</a>
    </div>

    <a data-bs-toggle="collapse" href="#studentMenu" role="button" aria-expanded="false" aria-controls="studentMenu">
        <i class="fas fa-user-graduate menu-icon"></i>
        <span class="hide-text">Students</span>
    </a>
    <div class="collapse submenu" id="studentMenu">
        <a href="manage_students.php">View Students</a>
        <a href="admin_groups.php">Add Groups</a>
        <a href="add_student.php">Add Student</a>
        <a href="add_homework.php">Add Homework</a>
        <a href="add_enrollment.php">Enrollment</a>
        <a href="manage_fees.php">Manage Fees</a>
        <a href="academic_history.php">Academic History</a>
    </div>

    <a data-bs-toggle="collapse" href="#teacherMenu" role="button" aria-expanded="false" aria-controls="teacherMenu">
        <i class="fas fa-chalkboard-teacher menu-icon"></i>
        <span class="hide-text">Teachers</span>
    </a>
    <div class="collapse submenu" id="teacherMenu">
        <a href="manage_teachers.php">View Teachers</a>
        <a href="add_teacher.php">Add Teacher</a>
        <a href="assign_teacher_subject.php">Assign Classes</a>
        <a href="view_teacher_subject.php">Teacher subject Classes</a>

    </div>

    <a data-bs-toggle="collapse" href="#payrollMenu" role="button" aria-expanded="false" aria-controls="payrollMenu">
        <i class="fas fa-money-check menu-icon"></i>
        <span class="hide-text">Payroll</span>
    </a>
    <div class="collapse submenu" id="payrollMenu">
        <a href="add_payroll.php">Manage Payroll</a>
    </div>

    <a data-bs-toggle="collapse" href="#attMenu" role="button" aria-expanded="false" aria-controls="attMenu">
        <i class="fas fa-calendar-check menu-icon"></i>
        <span class="hide-text">Attendance</span>
    </a>
    <div class="collapse submenu" id="attMenu">
        <a href="manage_attendance.php">Teachers Attendance</a>
        <a href="student_attendance.php">Students Attendance</a>
    </div>

    <a data-bs-toggle="collapse" href="#classMenu" role="button" aria-expanded="false" aria-controls="classMenu">
        <i class="fas fa-school menu-icon"></i>
        <span class="hide-text">Class Management</span>
    </a>
    <div class="collapse submenu" id="classMenu">
        <a href="add_class.php">Add Class</a>
        <a href="edit_class.php">Edit Class</a>
        <a href="add_term.php">Add Term</a>
        <a href="add_session.php">Add Session</a>
    </div>

    <a data-bs-toggle="collapse" href="#parentMenu" role="button" aria-expanded="false" aria-controls="parentMenu">
        <i class="fas fa-users menu-icon"></i>
        <span class="hide-text">Parents</span>
    </a>
    <div class="collapse submenu" id="parentMenu">
        <a href="view_parents.php">View Parents</a>
        <a href="add_parent.php">Add Parent</a>
    </div>

    <a data-bs-toggle="collapse" href="#notMenu" role="button" aria-expanded="false" aria-controls="notMenu">
        <i class="fas fa-envelope menu-icon"></i>
        <span class="hide-text">Notification</span>
    </a>
    <div class="collapse submenu" id="notMenu">
        <a href="add_notification.php">Add Notification</a>
    </div>

    <a data-bs-toggle="collapse" href="#actMenu" role="button" aria-expanded="false" aria-controls="actMenu">
        <i class="fas fa-calendar-alt menu-icon"></i>
        <span class="hide-text">Activities</span>
    </a>
    <div class="collapse submenu" id="actMenu">
        <a href="add_activity.php">Add Activity</a>
    </div>

    <a data-bs-toggle="collapse" href="#timeMenu" role="button" aria-expanded="false" aria-controls="timeMenu">
        <i class="fas fa-table menu-icon"></i>
        <span class="hide-text">Time Table</span>
    </a>
    <div class="collapse submenu" id="timeMenu">
        <a href="add_timetable.php">Add Time Table</a>
        <a href="assign_subject.php">Assign Subject</a>
        <a href="break_period.php">Break Period</a>
        <a href="subject_frequency.php">Subject Frequency</a>
        <a href="display_timetable.php">View Time Table</a>
        <a href="generate_timetable.php">Generate Time-Table</a>


    </div>

    <a data-bs-toggle="collapse" href="#feeMenu" role="button" aria-expanded="false" aria-controls="feeMenu">
        <i class="fas fa-money-bill-wave menu-icon"></i>
        <span class="hide-text">Fees</span>
    </a>
    <div class="collapse submenu" id="feeMenu">
        <a href="issue_receipt.php">Student Fees</a>
    </div>

    <a data-bs-toggle="collapse" href="#incomeMenu" role="button" aria-expanded="false" aria-controls="incomeMenu">
        <i class="fas fa-coins menu-icon"></i>
        <span class="hide-text">Income</span>
    </a>
    <div class="collapse submenu" id="incomeMenu">
        <a href="add_income.php">Add Income</a>
        <a href="add_expense.php">Add Expense</a>
        <a href="view_transactions.php">Transactions</a>
    </div>

    <a href="logout.php">
        <i class="fas fa-sign-out-alt menu-icon"></i>
        <span class="hide-text">Logout</span>
    </a>

    <div class="text-center p-2">
        <button id="toggleSidebar" class="btn btn-light btn-sm" type="button" aria-label="Toggle sidebar">
            <i class="fas fa-angle-left"></i>
        </button>
    </div>
</nav>

<!-- CONTENT -->
<div id="content">

    <!-- TOP BAR -->
    <div class="d-flex justify-content-between align-items-center topbar">
        <button id="mobileToggle" class="btn btn-primary" type="button">
            <i class="fas fa-bars"></i>
        </button>

        <div class="d-flex align-items-center gap-3">
            <!-- NOTIFICATION BELL -->
            <div class="dropdown">
                <button class="btn btn-light position-relative" data-bs-toggle="dropdown" aria-expanded="false" type="button">
                    <i class="fas fa-bell"></i>
                    <?php if ($unread_count > 0): ?>
                        <span class="position-absolute top-0 start-100 translate-middle badge bg-danger">
                            <?= $unread_count ?>
                        </span>
                    <?php endif; ?>
                </button>

                <div class="dropdown-menu dropdown-menu-end p-2 notification-dropdown">
                    <div class="fw-bold px-2 mb-2">Notifications</div>
                    <hr class="my-1">

                    <?php if ($notifications->num_rows > 0): ?>
                        <?php while ($n = $notifications->fetch_assoc()): ?>
                            <a href="view_notification.php?id=<?= (int) $n['id'] ?>" class="dropdown-item border-bottom py-2">
                                <div class="d-flex justify-content-between align-items-center">
                                    <strong><?= htmlspecialchars($n['message_head']) ?></strong>
                                    <?php if (($n['status'] ?? '') === 'unread'): ?>
                                        <span class="badge bg-primary">New</span>
                                    <?php endif; ?>
                                </div>

                                <small class="text-muted d-block mt-1">
                                    <?= htmlspecialchars(substr($n['message_body'] ?? '', 0, 70)) ?>...
                                </small>

                                <small class="text-muted d-block mt-1">
                                    <?= date('d M Y h:i A', strtotime($n['created_at'])) ?>
                                </small>
                            </a>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <div class="text-muted px-2">No notifications</div>
                    <?php endif; ?>

                    <hr>
                    <a href="all_notifications.php" class="btn btn-sm btn-primary w-100">
                        View All Notifications
                    </a>
                </div>
            </div>

            <!-- USER INFO -->
            <div class="text-end">
                <h5 class="mb-0">Welcome, <?= htmlspecialchars($username) ?></h5>
                <small class="text-muted">Dashboard Overview</small>
            </div>
        </div>
    </div>

    <!-- QUICK STATS CARDS -->
    <div class="row g-3 mb-4">
        <div class="col-md-3">
            <div class="stat-card">
                <i class="fas fa-user-graduate fa-2x text-primary mb-2"></i>
                <h3><?= $total_students ?></h3>
                <p class="mb-0 text-muted">Total Students</p>
            </div>
        </div>

        <div class="col-md-3">
            <div class="stat-card">
                <i class="fas fa-chalkboard-teacher fa-2x text-success mb-2"></i>
                <h3><?= $total_teachers ?></h3>
                <p class="mb-0 text-muted">Teaching Staff</p>
            </div>
        </div>

        <div class="col-md-3">
            <div class="stat-card">
                <i class="fas fa-users fa-2x text-warning mb-2"></i>
                <h3><?= $total_parents ?></h3>
                <p class="mb-0 text-muted">Parents</p>
            </div>
        </div>

        <div class="col-md-3">
            <div class="stat-card">
                <i class="fas fa-money-bill-wave fa-2x text-info mb-2"></i>
                <h3>₦<?= number_format($total_income, 2) ?></h3>
                <p class="mb-0 text-muted">Total Income</p>
            </div>
        </div>
    </div>

    <!-- FINANCIAL OVERVIEW -->
    <div class="row mb-4">
        <div class="col-md-6">
            <div class="p-4 card-soft">
                <h5><i class="fas fa-chart-line text-primary"></i> Financial Overview</h5>
                <hr>

                <div class="d-flex justify-content-between mb-2">
                    <span>Total Income</span>
                    <strong class="text-success">₦<?= number_format($total_income, 2) ?></strong>
                </div>

                <div class="d-flex justify-content-between mb-2">
                    <span>Total Expense</span>
                    <strong class="text-danger">₦<?= number_format($total_expense, 2) ?></strong>
                </div>

                <div class="d-flex justify-content-between">
                    <span>Balance</span>
                    <strong class="text-primary">
                        ₦<?= number_format($total_income - $total_expense, 2) ?>
                    </strong>
                </div>
            </div>
        </div>

        <div class="col-md-6">
            <div class="p-4 card-soft">
                <h5><i class="fas fa-bolt text-warning"></i> Quick Actions</h5>
                <hr>

                <a href="add_student.php" class="btn btn-primary btn-sm mb-2 w-100">
                    <i class="fas fa-user-plus"></i> Add Student
                </a>

                <a href="add_teacher.php" class="btn btn-success btn-sm mb-2 w-100">
                    <i class="fas fa-chalkboard-teacher"></i> Add Teacher
                </a>

                <a href="add_notification.php" class="btn btn-warning btn-sm mb-2 w-100">
                    <i class="fas fa-bell"></i> Send Notification
                </a>

                <a href="manage_fees.php" class="btn btn-info btn-sm w-100">
                    <i class="fas fa-money-bill"></i> Manage Fees
                </a>
            </div>
        </div>
    </div>

    <!-- ACTIVITY SUMMARY -->
    <div class="row">
        <div class="col-md-12">
            <div class="p-4 card-soft">
                <h5><i class="fas fa-chart-pie text-success"></i> System Summary</h5>
                <p class="text-muted mb-0">
                    Welcome to your school management dashboard. From here you can manage students, teachers,
                    academic records, finance operations, notifications, and system settings efficiently.
                </p>
            </div>
        </div>
    </div>

</div>

<!-- JS -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<script>
$(function () {
    $('#toggleSidebar, #mobileToggle').on('click', function () {
        $('#sidebar').toggleClass('collapsed');
        $('#content').toggleClass('expanded');
    });
});
</script>

</body>
</html>