<?php $currentPage = basename($_SERVER['PHP_SELF']); ?>
<style>
     /* Layout for Independent Scrolling */
    body {
        overflow: hidden;
    }
    *, *::before, *::after {
        box-sizing: border-box;
    }
    .admin-wrapper {
        display: flex;
        height: 100vh;
        overflow: hidden;
    }
    .sidebar {
        display: flex;
        flex-direction: column;
        height: 100%;
        flex-shrink: 0;
        width: 260px;
        background-color: #2c3e50;
        color: #ecf0f1;
    }
    .sidebar-nav {
        flex: 1;
        overflow-y: auto;
        scrollbar-width: thin;
    }
    .sidebar-nav::-webkit-scrollbar { width: 6px; }
    .sidebar-nav::-webkit-scrollbar-thumb { background-color: rgba(255,255,255,0.2); border-radius: 3px; }
    .sidebar-nav::-webkit-scrollbar-track { background: transparent; }
    .main-content {
        flex: 1;
        height: 100%;
        overflow-y: auto;
        background-color: #f8f9fc;
        padding: 20px;
        padding-bottom: 80px; /* Ensure content isn't cut off at bottom */
    }
    /* Accordion Styles */
    .nav-group-header {
        padding: 15px 20px;
        color: #bdc3c7;
        font-weight: 600;
        font-size: 0.8rem;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        cursor: pointer;
        display: flex;
        justify-content: space-between;
        align-items: center;
        transition: all 0.2s;
        border-bottom: 1px solid rgba(255,255,255,0.05);
    }
    .nav-group-header:hover { color: #fff; background: rgba(255,255,255,0.05); }
    .nav-group-items {
        display: none;
        background: #22303f;
        box-shadow: inset 0 2px 5px rgba(0,0,0,0.2);
    }
    .nav-group.open .nav-group-items { display: block; }
    .nav-group.open .nav-group-header { color: #fff; border-left: 4px solid #3498db; background: rgba(0,0,0,0.1); }
    .nav-group.open .nav-group-header i { transform: rotate(180deg); }
    
    .sidebar-nav a {
        display: flex;
        align-items: center;
        gap: 10px;
        padding: 12px 20px;
        color: #ecf0f1;
        text-decoration: none;
        transition: background 0.2s;
        font-size: 0.95rem;
        border-left: 4px solid transparent;
    }
    .sidebar-nav a:hover { background: rgba(255,255,255,0.1); color: #fff; }
    .sidebar-nav a.active { 
        background: #3498db; 
        color: white; 
        border-left-color: #fff;
    }
    .sidebar-nav a i { width: 20px; text-align: center; opacity: 0.8; }
    .nav-group-items a { padding-left: 45px; font-size: 0.9rem; border-left: none; }
    .nav-group-items a.active { background: rgba(52, 152, 219, 0.2); color: #3498db; border-left: 4px solid #3498db; }
    .sidebar-header { padding: 20px; background: #1a252f; color: white; border-bottom: 1px solid rgba(255,255,255,0.1); }
    .sidebar-footer { padding: 15px; border-top: 1px solid rgba(255,255,255,0.1); background: #1a252f; display: flex; flex-direction: column; gap: 10px; }
    .btn-switch-view {
        display: block;
        background: #3498db;
        color: white !important;
        text-align: center;
        padding: 10px;
        border-radius: 4px;
        text-decoration: none;
        font-weight: 600;
        transition: background 0.2s;
        font-size: 0.9rem;
    }
    .btn-switch-view:hover { background: #2980b9; }
    .logout-link { color: #e74c3c !important; text-align: center; text-decoration: none; font-size: 0.9rem; display: block; }
    .logout-link:hover { color: #c0392b !important; text-decoration: underline; }
    .nav-group-header i { transition: transform 0.2s; font-size: 0.8rem; }
    
    /* Single links at root level */
    .sidebar-nav > a.active { border-left-color: #fff; }

    /* Mobile Responsive Styles */
    .mobile-toggle { display: none; }
    .sidebar-overlay { display: none; }
    .admin-wrapper { display: flex; }
    .mobile-header { display: none; }

    @media (max-width: 768px) {
        .admin-wrapper {
            display: block;
            position: relative;
            width: 100%;
            height: 100vh;
            overflow: hidden;
        }

        .sidebar {
            position: fixed;
            left: -260px;
            top: 0;
            bottom: 0;
            z-index: 1001;
            transition: left 0.3s ease;
            box-shadow: 2px 0 5px rgba(0,0,0,0.2);
            width: 260px;
        }
        .sidebar.open { left: 0; }
        
        .sidebar-overlay {
            position: fixed;
            top: 0; left: 0; right: 0; bottom: 0;
            background: rgba(0,0,0,0.5);
            z-index: 1000;
            display: none;
        }
        .sidebar-overlay.show { display: block; }

        .mobile-header {
            display: flex;
            align-items: center;
            gap: 15px;
            background: #2c3e50;
            width: 100%;
            position: sticky;
            top: 0;
            color: white;
            padding: 15px 20px;
            margin: 0 0 20px 0;
            z-index: 990;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }

        .mobile-toggle {
            display: block;
            background: transparent;
            color: white;
            border: none;
            padding: 0;
            font-size: 1.2rem;
            z-index: 1002;
            cursor: pointer;
        }
        
        .main-content {
            padding: 0;
            width: 100%;
            height: 100%;
            overflow-y: auto;
            overflow-x: hidden; /* Prevent page-wide horizontal scroll */
            margin-left: 0;
            word-wrap: break-word; /* Ensure long text wraps */
        }

        .main-content > *:not(.mobile-header) {
            margin-left: 15px;
            margin-right: 15px;
            max-width: calc(100% - 30px); /* Ensure children respect margins */
        }

        /* Responsive Layout Adjustments */
        .stats-card-grid { grid-template-columns: 1fr !important; }
        .form-row { flex-direction: column; gap: 15px !important; }
        .form-group { width: 100% !important; flex: auto !important; }
        .dashboard-section { padding: 15px !important; }
        
        /* Table Scrolling */
        .table-wrapper { 
            width: 100%; 
            overflow-x: auto; 
            -webkit-overflow-scrolling: touch; 
            margin-bottom: 15px;
        }
        .styled-table { font-size: 0.85rem; min-width: 600px; }
        
        /* General Content Safety */
        img { max-width: 100%; height: auto; }
        h1 { font-size: 1.5rem; margin-bottom: 15px; margin-left: 15px; }
    }
    </style>
    
    <form id="reset-db-form" action="/smart_football/admin/reset_database.php" method="POST" style="display: none;"></form>

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const headers = document.querySelectorAll('.nav-group-header');
        headers.forEach(header => {
            header.addEventListener('click', () => {
                header.parentElement.classList.toggle('open');
            });
        });

        const resetDbLink = document.getElementById('reset-db-link');
        if (resetDbLink) {
            resetDbLink.addEventListener('click', function(e) {
                e.preventDefault();
                if (confirm('DANGER: Are you sure you want to reset the database? This will wipe all data except roles, permissions, settings, and the super admin account.')) {
                    const form = document.getElementById('reset-db-form');
                    if (form) form.submit();
                }
            });
        }

        // Mobile Sidebar Toggle
        const sidebarToggle = document.getElementById('sidebar-toggle');
        const sidebar = document.querySelector('.sidebar');
        const overlay = document.getElementById('sidebar-overlay');

        if (sidebarToggle) {
            sidebarToggle.addEventListener('click', function() {
                sidebar.classList.toggle('open');
                overlay.classList.toggle('show');
            });
        }
        
        if (overlay) {
            overlay.addEventListener('click', function() {
                sidebar.classList.remove('open');
                overlay.classList.remove('show');
            });
        }
    });
    </script>
    
    <?php
    // Helper to check if a group should be open
    function isGroupOpen($pages, $current) {
        return in_array($current, $pages) ? 'open' : '';
    }
    ?>

<div class="admin-wrapper">
    <div id="sidebar-overlay" class="sidebar-overlay"></div>
    <aside class="sidebar">
        <div class="sidebar-header">
            <h2>Smart Football</h2>
            <span>Admin Panel</span>
        </div>
        <nav class="sidebar-nav">
            <a href="dashboard.php" class="<?php echo ($currentPage == 'dashboard.php') ? 'active' : ''; ?>"><i class="fa-solid fa-gauge-high"></i> Dashboard</a>
            
            <!-- Competition Group -->
            <?php 
            $canViewLeagues = hasPermission('leagues:view');
            $canViewSeasons = hasPermission('seasons:view');
            $canViewGameweeks = hasPermission('gameweeks:view');
            $canViewFixtures = hasPermission('fixtures:view');
            
            if ($canViewLeagues || $canViewSeasons || $canViewGameweeks || $canViewFixtures): 
                $compPages = ['manage_leagues.php', 'edit_league.php', 'manage_seasons.php', 'manage_gameweeks.php', 'manage_fixtures.php', 'add_fixture.php', 'edit_fixture.php', 'generate_fixtures.php']; 
            ?>
                <div class="nav-group <?php echo isGroupOpen($compPages, $currentPage); ?>">
                    <div class="nav-group-header">Competition <i class="fa-solid fa-chevron-down"></i></div>
                    <div class="nav-group-items">
                        <?php if ($canViewLeagues): ?><a href="manage_leagues.php" class="<?php echo in_array($currentPage, ['manage_leagues.php', 'edit_league.php']) ? 'active' : ''; ?>">Leagues</a><?php endif; ?>
                        <?php if ($canViewSeasons): ?><a href="manage_seasons.php" class="<?php echo ($currentPage == 'manage_seasons.php') ? 'active' : ''; ?>">Seasons</a><?php endif; ?>
                        <?php if ($canViewGameweeks): ?><a href="manage_gameweeks.php" class="<?php echo ($currentPage == 'manage_gameweeks.php') ? 'active' : ''; ?>">Gameweeks</a><?php endif; ?>
                        <?php if ($canViewFixtures): ?><a href="manage_fixtures.php" class="<?php echo in_array($currentPage, ['manage_fixtures.php', 'add_fixture.php', 'edit_fixture.php', 'generate_fixtures.php']) ? 'active' : ''; ?>">Fixtures</a><?php endif; ?>
                        <?php if ($canViewFixtures): ?><a href="view_referee_reports.php" class="<?php echo ($currentPage == 'view_referee_reports.php') ? 'active' : ''; ?>">Referee Reports</a><?php endif; ?>
                    </div>
                </div>
            <?php endif; ?>

            <!-- Management Group -->
            <?php 
            $canViewClubs = hasPermission('clubs:view');
            $canViewTeams = hasPermission('teams:view');
            $canViewRosters = hasPermission('rosters:view');
            $canViewUsers = hasPermission('users:view');
            $canViewRoles = hasPermission('roles:view');
            
            if ($canViewClubs || $canViewTeams || $canViewRosters || $canViewUsers || $canViewRoles):
                $mgmtPages = ['manage_clubs.php', 'add_club.php', 'edit_club.php', 'manage_teams.php', 'edit_team.php', 'manage_rosters.php', 'manage_users.php', 'manage_roles.php', 'edit_role.php']; 
            ?>
                <div class="nav-group <?php echo isGroupOpen($mgmtPages, $currentPage); ?>">
                    <div class="nav-group-header">Management <i class="fa-solid fa-chevron-down"></i></div>
                    <div class="nav-group-items">
                        <?php if ($canViewClubs): ?><a href="manage_clubs.php" class="<?php echo in_array($currentPage, ['manage_clubs.php', 'add_club.php', 'edit_club.php']) ? 'active' : ''; ?>">Clubs</a><?php endif; ?>
                        <?php if ($canViewTeams): ?><a href="manage_teams.php" class="<?php echo in_array($currentPage, ['manage_teams.php', 'edit_team.php']) ? 'active' : ''; ?>">Teams</a><?php endif; ?>
                        <?php if ($canViewRosters): ?><a href="manage_rosters.php" class="<?php echo ($currentPage == 'manage_rosters.php') ? 'active' : ''; ?>">Rosters</a><?php endif; ?>
                        <?php if ($canViewUsers): ?><a href="manage_users.php" class="<?php echo ($currentPage == 'manage_users.php') ? 'active' : ''; ?>">Users</a><?php endif; ?>
                        <?php if ($canViewRoles): ?><a href="manage_roles.php" class="<?php echo in_array($currentPage, ['manage_roles.php', 'edit_role.php']) ? 'active' : ''; ?>">Roles & Permissions</a><?php endif; ?>
                    </div>
                </div>
            <?php endif; ?>

            <!-- Finance Group -->
            <?php 
            $canViewFines = hasPermission('fines:view');
            $canViewPayments = hasPermission('payments:view') || hasPermission('withdrawals:view');
            
            if ($canViewFines || $canViewPayments):
                $finPages = ['finance_dashboard.php', 'club_payments.php', 'manage_fines.php', 'payments.php', 'payment_logs.php', 'wallet_management.php', 'wallet_transactions.php', 'financial_reports.php', 'withdrawal_requests.php', 'board_wallet.php', 'pay_referees.php']; 
            ?>
                <div class="nav-group <?php echo isGroupOpen($finPages, $currentPage); ?>">
                    <div class="nav-group-header">Finance <i class="fa-solid fa-chevron-down"></i></div>
                    <div class="nav-group-items">
                        <?php if (in_array($_SESSION['admin_user_role'] ?? '', ['admin', 'super_admin', 'finance_manager'])): ?>
                            <a href="finance_dashboard.php" class="<?php echo ($currentPage == 'finance_dashboard.php') ? 'active' : ''; ?>">Finance Dashboard</a>
                        <?php endif; ?>
                        <?php if ($canViewPayments): ?><a href="club_payments.php" class="<?php echo ($currentPage == 'club_payments.php') ? 'active' : ''; ?>">Club Payments</a><?php endif; ?>
                        <?php if (in_array($_SESSION['admin_user_role'] ?? '', ['admin', 'super_admin', 'finance_manager'])): ?><a href="manage_fines.php" class="<?php echo ($currentPage == 'manage_fines.php') ? 'active' : ''; ?>">Fines</a><?php endif; ?>
                        <?php if ($canViewPayments): ?><a href="payments.php" class="<?php echo ($currentPage == 'payments.php') ? 'active' : ''; ?>">Payments</a><?php endif; ?>
                        <?php if ($canViewPayments): ?><a href="payment_logs.php" class="<?php echo ($currentPage == 'payment_logs.php') ? 'active' : ''; ?>">Gateway Logs</a><?php endif; ?>
                        <?php if ($canViewPayments): ?><a href="wallet_management.php" class="<?php echo ($currentPage == 'wallet_management.php') ? 'active' : ''; ?>">Wallet Management</a><?php endif; ?>
                        <?php if ($canViewPayments): ?><a href="wallet_transactions.php" class="<?php echo ($currentPage == 'wallet_transactions.php') ? 'active' : ''; ?>">Wallet Logs</a><?php endif; ?>
                        <?php if ($canViewPayments): ?><a href="financial_reports.php" class="<?php echo ($currentPage == 'financial_reports.php') ? 'active' : ''; ?>">Financial Reports</a><?php endif; ?>
                        <?php if (hasPermission('withdrawals:view')): ?><a href="withdrawal_requests.php" class="<?php echo ($currentPage == 'withdrawal_requests.php') ? 'active' : ''; ?>">Withdrawals</a><?php endif; ?>
                        <?php if (in_array($_SESSION['admin_user_role'] ?? '', ['admin', 'super_admin'])): ?>
                            <a href="board_wallet.php" class="<?php echo ($currentPage == 'board_wallet.php') ? 'active' : ''; ?>">Board Wallet</a>
                        <?php endif; ?>
                        <?php if (in_array($_SESSION['admin_user_role'] ?? '', ['admin', 'super_admin', 'finance_manager'])): ?>
                            <a href="pay_referees.php" class="<?php echo ($currentPage == 'pay_referees.php') ? 'active' : ''; ?>">Pay Referees</a>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endif; ?>

            <!-- Sponsorship Group -->
            <?php 
            if (in_array($_SESSION['admin_user_role'] ?? '', ['admin', 'super_admin'])):
                $sponPages = ['sponsorship_packages.php', 'sponsor_campaigns.php']; 
            ?>
                <div class="nav-group <?php echo isGroupOpen($sponPages, $currentPage); ?>">
                    <div class="nav-group-header">Sponsorships <i class="fa-solid fa-chevron-down"></i></div>
                    <div class="nav-group-items">
                        <a href="sponsorship_packages.php" class="<?php echo ($currentPage == 'sponsorship_packages.php') ? 'active' : ''; ?>">Packages</a>
                        <a href="sponsor_campaigns.php" class="<?php echo ($currentPage == 'sponsor_campaigns.php') ? 'active' : ''; ?>">Campaigns</a>
                    </div>
                </div>
            <?php endif; ?>

            <!-- Fantasy Group -->
            <?php 
            $canViewFantasy = hasPermission('fantasy:view_management');
            
            if ($canViewFantasy):
                $fantasyPages = ['fantasy_management.php', 'fantasy_players.php', 'fantasy_teams.php', 'process_fantasy_points.php', 'fantasy_points_log.php', 'season_rollover.php', 'fantasy_gameweek_stats.php']; 
            ?>
                <div class="nav-group <?php echo isGroupOpen($fantasyPages, $currentPage); ?>">
                    <div class="nav-group-header">Fantasy <i class="fa-solid fa-chevron-down"></i></div>
                    <div class="nav-group-items">
                        <a href="fantasy_management.php" class="<?php echo in_array($currentPage, $fantasyPages) ? 'active' : ''; ?>">Fantasy Dashboard</a>
                    </div>
                </div>
            <?php endif; ?>

            <!-- System Group -->
            <?php 
            $canManageAnnouncements = hasPermission('announcements:create');
            $canManageSettings = hasPermission('settings:edit');
            $isSuperAdmin = ($_SESSION['user_role'] ?? '') === 'super_admin';
            $isAdmin = in_array($_SESSION['user_role'] ?? '', ['super_admin', 'admin']);
            
            if ($canManageAnnouncements || $canManageSettings || $isSuperAdmin):
                $sysPages = ['manage_announcements.php', 'add_announcement.php', 'settings.php', 'verify_db_schema.php', 'system_health.php']; 
            ?>
                <div class="nav-group <?php echo isGroupOpen($sysPages, $currentPage); ?>">
                    <div class="nav-group-header">System <i class="fa-solid fa-chevron-down"></i></div>
                    <div class="nav-group-items">
                        <?php if ($canManageAnnouncements): ?><a href="manage_announcements.php" class="<?php echo in_array($currentPage, ['manage_announcements.php', 'add_announcement.php']) ? 'active' : ''; ?>">Announcements</a><?php endif; ?>
                        <?php if ($canManageSettings): ?><a href="settings.php" class="<?php echo ($currentPage == 'settings.php') ? 'active' : ''; ?>">Settings</a><?php endif; ?>
                        <?php if ($isSuperAdmin): ?><a href="verify_db_schema.php" class="<?php echo ($currentPage == 'verify_db_schema.php') ? 'active' : ''; ?>">Verify DB Schema</a><?php endif; ?>
                        <?php if ($isAdmin): ?><a href="system_health.php" class="<?php echo ($currentPage == 'system_health.php') ? 'active' : ''; ?>">System Health</a><?php endif; ?>
                        <?php if ($isSuperAdmin): ?><a href="#" id="reset-db-link" style="color: #e74c3c;">Reset Database</a><?php endif; ?>
                    </div>
                </div>
            <?php endif; ?>
        </nav>
        <div class="sidebar-footer">
            <a href="/smart_football/app/" class="btn-switch-view"><i class="fa-solid fa-arrow-right-from-bracket"></i> Switch to User View</a>
            <a href="auth/logout.php" class="logout-link"><i class="fa-solid fa-power-off"></i> Logout</a>
        </div>
    </aside>
    <div class="main-content">
        <div class="mobile-header">
            <button id="sidebar-toggle" class="mobile-toggle"><i class="fa-solid fa-bars"></i></button>
            <h3 style="margin: 0; font-size: 1.1rem; font-weight: 600;">Smart Football Admin</h3>
        </div>