<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/../../includes/functions.php';
// Admin Check
if (!isset($_SESSION['admin_id']) && basename($_SERVER['PHP_SELF']) !== 'index.php') {
    header("Location: index.php");
    exit;
}

// PERMISSION HELPER
function hasPermission($feature)
{
    global $pdo;
    if (!isset($_SESSION['admin_role_id']))
        return false;

    // Cache permissions in session to avoid 100 queries
    if (!isset($_SESSION['my_permissions'])) {
        try {
            $stmt = $pdo->prepare("SELECT permissions FROM staff_roles WHERE id = ?");
            $stmt->execute([$_SESSION['admin_role_id']]);
            $json = $stmt->fetchColumn();
            $_SESSION['my_permissions'] = json_decode($json, true) ?? [];
        } catch (Exception $e) {
            $_SESSION['my_permissions'] = []; // Fallback empty
        }
    }

    $perms = $_SESSION['my_permissions'];
    if (in_array('all', $perms))
        return true; // Super Admin
    return in_array($feature, $perms);
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RRR Admin</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap"
        rel="stylesheet">
    <link rel="stylesheet" href="assets/css/admin.css">
    <link rel="icon" type="image/png" href="<?php echo getSetting('favicon'); ?>">
</head>

<body>

    <?php if (isset($_SESSION['admin_id'])): ?>
        <div class="overlay" onclick="toggleSidebar()"></div>
        <div class="sidebar" id="sidebar">
            <div class="brand">
                <i class="fas fa-shield-alt"></i> RRR ADMIN
                <div style="margin-left:auto; display:block; cursor:pointer;" class="mobile-only-close"
                    onclick="toggleSidebar()">
                    <i class="fas fa-times" style="font-size:18px;"></i>
                </div>
                <style>
                    .mobile-only-close {
                        display: none;
                    }

                    @media(max-width:900px) {
                        .mobile-only-close {
                            display: block;
                        }
                    }
                </style>
            </div>

            <div class="user-info"
                style="padding:0 25px 20px; color:#aaa; font-size:12px; border-bottom:1px solid #333; margin-bottom:10px;">
                Logged in as: <strong
                    style="color:var(--primary);"><?php echo htmlspecialchars($_SESSION['admin_name'] ?? 'Admin'); ?></strong>
            </div>

            <div class="nav-links">
                <a href="dashboard.php"
                    class="nav-item <?php echo basename($_SERVER['PHP_SELF']) == 'dashboard.php' ? 'active' : ''; ?>"><i
                        class="fas fa-th-large"></i> Dashboard</a>

                <!-- USERS & FINANCE -->
                <?php if (hasPermission('users') || hasPermission('deposits') || hasPermission('withdraws')): ?>
                    <div class="nav-header">Users & Finance</div>

                    <?php if (hasPermission('users')): ?>
                        <a href="users.php"
                            class="nav-item <?php echo basename($_SERVER['PHP_SELF']) == 'users.php' ? 'active' : ''; ?>"><i
                                class="fas fa-users-cog"></i> User Management</a>
                    <?php endif; ?>

                    <?php if (hasPermission('deposits')): ?>
                        <a href="deposit_manager.php"
                            class="nav-item <?php echo basename($_SERVER['PHP_SELF']) == 'deposit_manager.php' ? 'active' : ''; ?>"><i
                                class="fas fa-arrow-circle-down"></i> Deposits</a>
                    <?php endif; ?>

                    <?php if (hasPermission('withdraws')): ?>
                        <a href="withdraw_manager.php"
                            class="nav-item <?php echo basename($_SERVER['PHP_SELF']) == 'withdraw_manager.php' ? 'active' : ''; ?>"><i
                                class="fas fa-arrow-circle-up"></i> Withdrawals</a>
                    <?php endif; ?>
                <?php endif; ?>

                <!-- APP & TOURNAMENTS -->
                <?php if (hasPermission('content') || hasPermission('tournaments')): ?>
                    <div class="nav-header">App Management</div>

                    <?php if (hasPermission('content')): ?>
                        <a href="banners.php"
                            class="nav-item <?php echo basename($_SERVER['PHP_SELF']) == 'banners.php' ? 'active' : ''; ?>"><i
                                class="fas fa-images"></i> App Banners</a>
                        <a href="categories.php"
                            class="nav-item <?php echo basename($_SERVER['PHP_SELF']) == 'categories.php' ? 'active' : ''; ?>"><i
                                class="fas fa-layer-group"></i> Categories</a>
                    <?php endif; ?>

                    <?php if (hasPermission('tournaments')): ?>
                        <a href="tournaments.php"
                            class="nav-item <?php echo basename($_SERVER['PHP_SELF']) == 'tournaments.php' ? 'active' : ''; ?>"><i
                                class="fas fa-trophy"></i> Tournaments</a>
                        <a href="results.php"
                            class="nav-item <?php echo basename($_SERVER['PHP_SELF']) == 'results.php' ? 'active' : ''; ?>"><i
                                class="fas fa-poll"></i> Result Submission</a>
                    <?php endif; ?>
                <?php endif; ?>

                <!-- SYSTEM -->
                <div class="nav-header">System</div>

                <?php if (hasPermission('notice')): ?>
                    <a href="notification.php"
                        class="nav-item <?php echo basename($_SERVER['PHP_SELF']) == 'notification.php' ? 'active' : ''; ?>"><i
                            class="fas fa-bullhorn"></i> Noticeboard</a>
                <?php endif; ?>

                <?php if (hasPermission('settings')): ?>
                    <a href="settings.php"
                        class="nav-item <?php echo basename($_SERVER['PHP_SELF']) == 'settings.php' ? 'active' : ''; ?>"><i
                            class="fas fa-cog"></i> Settings</a>
                <?php endif; ?>

                <?php if (hasPermission('staff')): ?>
                    <a href="staff_manager.php"
                        class="nav-item <?php echo basename($_SERVER['PHP_SELF']) == 'staff_manager.php' ? 'active' : ''; ?>"><i
                            class="fas fa-user-shield"></i> Staff Manager</a>
                <?php endif; ?>

                <a href="logout.php" class="nav-item"><i class="fas fa-sign-out-alt"></i> Logout</a>

                <div class="nav-header">Appearance</div>
                <div class="nav-item" onclick="document.body.classList.toggle('dark-theme')" style="cursor:pointer;"><i
                        class="fas fa-moon"></i> Dark Mode</div>
            </div>
        </div>
        <div class="main-content">
            <div style="display:flex; align-items:center;">
                <i class="fas fa-bars mobile-toggle" onclick="toggleSidebar()"></i>
            </div>

            <script>
                function toggleSidebar() {
                    document.getElementById('sidebar').classList.toggle('active');
                    document.querySelector('.overlay').classList.toggle('active');
                }
            </script>
        <?php endif; ?>