<?php
/**
 * Pension System Sidebar with Role-Based Access Control
 * File: layouts/sidebar.php
 */

// Include topbar (only once)
include_once 'layouts/topbar.php';

// Role-Based Access Control Class for Pension System
if (!class_exists('PensionRBAC')) {
    class PensionRBAC {
    private $conn;
    private $user_id;
    private $role_id;
    private $role_name;
    private $permissions = [];
    
    public function __construct($conn, $user_id = null) {
        $this->conn = $conn;
        $this->user_id = $user_id;
        
        if ($user_id) {
            $this->loadUserRole();
            $this->loadPermissions();
        }
    }
    
    private function loadUserRole() {
        $sql = "SELECT u.role_id, r.role_name 
                FROM users u 
                INNER JOIN roles r ON u.role_id = r.role_id 
                WHERE u.user_id = ? AND u.deleted_at IS NULL";
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param("i", $this->user_id);
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();
        
        if ($result) {
            $this->role_id = $result['role_id'];
            $this->role_name = $result['role_name'];
        }
    }
    
    private function loadPermissions() {
        // Super Admin gets all permissions
        if ($this->role_id === 1) { // role_id 1 is System Administrator
            $this->permissions = ['*'];
            return;
        }
        
        // Get permissions for this role
        $sql = "SELECT p.permission_name, p.module 
                FROM role_permissions rp
                INNER JOIN permissions p ON rp.permission_id = p.permission_id
                WHERE rp.role_id = ?";
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param("i", $this->role_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $this->permissions = [];
        while ($row = $result->fetch_assoc()) {
            $this->permissions[] = $row['permission_name'];
        }
    }
    
    public function hasPermission($permission) {
        if ($this->role_id === 1 || in_array('*', $this->permissions)) {
            return true;
        }
        return in_array($permission, $this->permissions);
    }
    
    public function hasAnyPermission($permissions) {
        foreach ($permissions as $permission) {
            if ($this->hasPermission($permission)) {
                return true;
            }
        }
        return false;
    }
    
    public function getRoleName() {
        return $this->role_name;
    }
    
    public function getRoleId() {
        return $this->role_id;
    }
    
    public function getPermissions() {
        return $this->permissions;
    }
}
}

// Initialize variables
$userRole = 'guest';
$current_page = basename($_SERVER['PHP_SELF']);
$rbac = null;
$user_details = null;

if (isset($_SESSION['user_id'])) {
    $user_id = $_SESSION['user_id'];
    
    // Get user details
    $sql_user_details = "SELECT u.*, r.role_name,
                         CONCAT(u.first_name, ' ', u.last_name) as full_name
                         FROM users u 
                         INNER JOIN roles r ON u.role_id = r.role_id 
                         WHERE u.user_id = ? AND u.deleted_at IS NULL";
    $stmt_user = $conn->prepare($sql_user_details);
    $stmt_user->bind_param("i", $user_id);
    $stmt_user->execute();
    $user_details = $stmt_user->get_result()->fetch_assoc();
    
    if ($user_details) {
        $userRole = $user_details['role_name'];
        $rbac = new PensionRBAC($conn, $user_id);
    }
}

// Helper functions - with guards to prevent redeclaration
if (!function_exists('getCurrentPage')) {
    function getCurrentPage() {
        return basename($_SERVER['PHP_SELF']);
    }
}

if (!function_exists('isMenuActive')) {
    function isMenuActive($url, $currentPage) {
        return basename($url) === $currentPage;
    }
}

if (!function_exists('hasActiveItem')) {
    function hasActiveItem($items, $currentPage) {
        foreach ($items as $item) {
            if (isset($item['url']) && isMenuActive($item['url'], $currentPage)) {
                return true;
            }
        }
        return false;
    }
}

// Get menu configuration based on role and permissions
if (!function_exists('getPensionMenuConfig')) {
    function getPensionMenuConfig($rbac) {
    $menuItems = [];
    
    if (!$rbac) {
        return [
            ['type' => 'header', 'title' => 'Main Menu'],
            ['type' => 'link', 'url' => 'index.php', 'icon' => 'ph-house', 'title' => 'Dashboard'],
            ['type' => 'header', 'title' => 'My Account'],
            ['type' => 'link', 'url' => 'profile.php', 'icon' => 'ph-user', 'title' => 'My Profile'],
            ['type' => 'link', 'url' => 'logout.php', 'icon' => 'ph-sign-out', 'title' => 'Logout', 'class' => 'text-danger']
        ];
    }
    
    $role_id = $rbac->getRoleId();
    
    // Main Menu
    $menuItems[] = ['type' => 'header', 'title' => 'Main Menu'];
    $menuItems[] = ['type' => 'link', 'url' => 'index.php', 'icon' => 'ph-house', 'title' => 'Dashboard'];
    
    // PENSION MANAGEMENT SECTION
    if ($rbac->hasAnyPermission(['view_schemes', 'manage_schemes', 'view_members', 'manage_members'])) {
        $menuItems[] = ['type' => 'header', 'title' => 'Pension Management'];
        
        // Schemes Management
        if ($rbac->hasAnyPermission(['view_schemes', 'manage_schemes'])) {
            $schemeItems = [];
            if ($rbac->hasPermission('view_schemes')) {
                $schemeItems[] = ['url' => 'list_schemes.php', 'title' => 'All Schemes'];
            }
            if ($rbac->hasPermission('manage_schemes')) {
                $schemeItems[] = ['url' => 'create_scheme.php', 'title' => 'Create Scheme'];
                $schemeItems[] = ['url' => 'scheme_rules.php', 'title' => 'Scheme Rules'];
            }
            
            if (!empty($schemeItems)) {
                $menuItems[] = [
                    'type' => 'dropdown',
                    'id' => 'schemes-menu',
                    'icon' => 'ph-briefcase',
                    'title' => 'Pension Schemes',
                    'items' => $schemeItems
                ];
            }
        }
        
        // Members Management
        if ($rbac->hasAnyPermission(['view_members', 'manage_members'])) {
            $memberItems = [];
            if ($rbac->hasPermission('view_members')) {
                $memberItems[] = ['url' => 'list_members.php', 'title' => 'All Members'];
            }
            if ($rbac->hasPermission('manage_members')) {
                $memberItems[] = ['url' => 'add_member.php', 'title' => 'Add Member'];
                $memberItems[] = ['url' => 'member_accounts.php', 'title' => 'Member Accounts'];
                $memberItems[] = ['url' => 'beneficiaries.php', 'title' => 'Beneficiaries'];
            }
            
            if (!empty($memberItems)) {
                $menuItems[] = [
                    'type' => 'dropdown',
                    'id' => 'members-menu',
                    'icon' => 'ph-users',
                    'title' => 'Members',
                    'items' => $memberItems
                ];
            }
        }
        
        // Employers
        if ($role_id == 1 || $role_id == 2 || $role_id == 3) {
            $menuItems[] = ['type' => 'link', 'url' => 'list_employers.php', 'icon' => 'ph-buildings', 'title' => 'Employers'];
        }
    }
    
    // CONTRIBUTIONS & FUND MANAGEMENT
    if ($rbac->hasAnyPermission(['view_contributions', 'manage_contributions'])) {
        $menuItems[] = ['type' => 'header', 'title' => 'Fund Management'];
        
        $contributionItems = [];
        if ($rbac->hasPermission('view_contributions')) {
            $contributionItems[] = ['url' => 'list_contributions.php', 'title' => 'View Contributions'];
        }
        if ($rbac->hasPermission('manage_contributions')) {
            $contributionItems[] = ['url' => 'post_contribution.php', 'title' => 'Post Contribution'];
            $contributionItems[] = ['url' => 'bulk_contributions.php', 'title' => 'Bulk Upload'];
        }
        if ($role_id == 1 || $role_id == 2) {
            $contributionItems[] = ['url' => 'fund_returns.php', 'title' => 'Fund Returns'];
            $contributionItems[] = ['url' => 'return_allocation.php', 'title' => 'Allocate Returns'];
        }
        
        if (!empty($contributionItems)) {
            $menuItems[] = [
                'type' => 'dropdown',
                'id' => 'contributions-menu',
                'icon' => 'ph-coins',
                'title' => 'Contributions',
                'items' => $contributionItems
            ];
        }
    }
    
    // WITHDRAWALS & BENEFITS
    if ($rbac->hasAnyPermission(['view_withdrawals', 'approve_withdrawal', 'process_withdrawal', 'create_withdrawal_request'])) {
        $withdrawalItems = [];
        if ($rbac->hasPermission('view_withdrawals')) {
            $withdrawalItems[] = ['url' => 'list_withdrawals.php', 'title' => 'All Withdrawals'];
        }
        if ($rbac->hasPermission('create_withdrawal_request')) {
            $withdrawalItems[] = ['url' => 'create_withdrawal.php', 'title' => 'New Withdrawal'];
        }
        if ($rbac->hasPermission('approve_withdrawal')) {
            $withdrawalItems[] = ['url' => 'pending_approvals.php', 'title' => 'Pending Approvals'];
        }
        if ($rbac->hasPermission('process_withdrawal')) {
            $withdrawalItems[] = ['url' => 'process_withdrawals.php', 'title' => 'Process Withdrawals'];
        }
        
        if (!empty($withdrawalItems)) {
            $menuItems[] = [
                'type' => 'dropdown',
                'id' => 'withdrawals-menu',
                'icon' => 'ph-arrow-circle-down',
                'title' => 'Withdrawals',
                'items' => $withdrawalItems
            ];
        }
    }
    
    // LIFE INSURANCE SECTION
    if ($rbac->hasAnyPermission(['view_policies', 'manage_policies', 'view_claims', 'manage_claims', 'manage_surrenders'])) {
        $menuItems[] = ['type' => 'header', 'title' => 'Life Insurance'];
        
        // Policies
        if ($rbac->hasAnyPermission(['view_policies', 'manage_policies'])) {
            $policyItems = [];
            if ($rbac->hasPermission('view_policies')) {
                $policyItems[] = ['url' => 'list_policies.php', 'title' => 'All Policies'];
            }
            if ($rbac->hasPermission('manage_policies')) {
                $policyItems[] = ['url' => 'create_policy.php', 'title' => 'Create Policy'];
                $policyItems[] = ['url' => 'policy_products.php', 'title' => 'Products'];
                $policyItems[] = ['url' => 'policy_rules.php', 'title' => 'Policy Rules'];
            }
            
            if (!empty($policyItems)) {
                $menuItems[] = [
                    'type' => 'dropdown',
                    'id' => 'policies-menu',
                    'icon' => 'ph-file-text',
                    'title' => 'Policies',
                    'items' => $policyItems
                ];
            }
        }
        
        // Premiums
        if ($role_id == 1 || $role_id == 5) {
            $menuItems[] = ['type' => 'link', 'url' => 'list_premiums.php', 'icon' => 'ph-currency-circle-dollar', 'title' => 'Premiums'];
        }
        
        // Claims
        if ($rbac->hasAnyPermission(['view_claims', 'manage_claims', 'approve_claims'])) {
            $claimItems = [];
            if ($rbac->hasPermission('manage_claims')) {
                $claimItems[] = ['url' => 'create_claim.php', 'title' => 'New Claim'];
            }
            $claimItems[] = ['url' => 'list_claims.php', 'title' => 'All Claims'];
            if ($rbac->hasPermission('approve_claims')) {
                $claimItems[] = ['url' => 'pending_claims.php', 'title' => 'Pending Claims'];
            }
            
            if (!empty($claimItems)) {
                $menuItems[] = [
                    'type' => 'dropdown',
                    'id' => 'claims-menu',
                    'icon' => 'ph-first-aid',
                    'title' => 'Claims',
                    'items' => $claimItems
                ];
            }
        }
        
        // Surrenders
        if ($rbac->hasPermission('manage_surrenders')) {
            $menuItems[] = ['type' => 'link', 'url' => 'list_surrenders.php', 'icon' => 'ph-hand-coins', 'title' => 'Surrender Requests'];
        }
    }
    
    // PAYMENTS & FINANCE
    if ($rbac->hasAnyPermission(['process_payments', 'view_payments'])) {
        $menuItems[] = ['type' => 'header', 'title' => 'Payments'];
        
        $paymentItems = [];
        if ($rbac->hasPermission('process_payments')) {
            $paymentItems[] = ['url' => 'pending_payouts.php', 'title' => 'Pending Payouts'];
            $paymentItems[] = ['url' => 'process_payment.php', 'title' => 'Process Payment'];
        }
        $paymentItems[] = ['url' => 'payment_history.php', 'title' => 'Payment History'];
        
        if (!empty($paymentItems)) {
            $menuItems[] = [
                'type' => 'dropdown',
                'id' => 'payments-menu',
                'icon' => 'ph-wallet',
                'title' => 'Payments',
                'items' => $paymentItems
            ];
        }
    }
    
    // REPORTS & COMPLIANCE
    if ($rbac->hasAnyPermission(['view_reports', 'generate_reports'])) {
        $menuItems[] = ['type' => 'header', 'title' => 'Reports & Compliance'];
        
        $reportItems = [];
        $reportItems[] = ['url' => 'member_statements.php', 'title' => 'Member Statements'];
        $reportItems[] = ['url' => 'contribution_reports.php', 'title' => 'Contribution Reports'];
        $reportItems[] = ['url' => 'fund_performance.php', 'title' => 'Fund Performance'];
        if ($role_id == 1 || $role_id == 2) {
            $reportItems[] = ['url' => 'rba_reports.php', 'title' => 'RBA Reports'];
            $reportItems[] = ['url' => 'actuarial_reports.php', 'title' => 'Actuarial Reports'];
        }
        
        $menuItems[] = [
            'type' => 'dropdown',
            'id' => 'reports-menu',
            'icon' => 'ph-chart-line',
            'title' => 'Reports',
            'items' => $reportItems
        ];
    }
    
    // ADMINISTRATION (System Admin Only)
    if ($role_id == 1) {
        $menuItems[] = ['type' => 'header', 'title' => 'Administration'];
        
        $adminItems = [];
        $adminItems[] = ['url' => 'list_users.php', 'title' => 'User Management'];
        $adminItems[] = ['url' => 'role_permissions.php', 'title' => 'Roles & Permissions'];
        $adminItems[] = ['url' => 'system_settings.php', 'title' => 'System Settings'];
        $adminItems[] = ['url' => 'audit_logs.php', 'title' => 'Audit Logs'];
        
        $menuItems[] = [
            'type' => 'dropdown',
            'id' => 'admin-menu',
            'icon' => 'ph-gear',
            'title' => 'Administration',
            'items' => $adminItems
        ];
    }
    
    // MY ACCOUNT SECTION (Always visible)
    $menuItems[] = ['type' => 'header', 'title' => 'My Account'];
    
    // Member-specific items
    if ($role_id == 4) {
        $menuItems[] = ['type' => 'link', 'url' => 'my_account.php', 'icon' => 'ph-user-circle', 'title' => 'My Account'];
        $menuItems[] = ['type' => 'link', 'url' => 'my_contributions.php', 'icon' => 'ph-coins', 'title' => 'My Contributions'];
        $menuItems[] = ['type' => 'link', 'url' => 'my_statement.php', 'icon' => 'ph-file-text', 'title' => 'My Statement'];
    }
    
    $menuItems[] = ['type' => 'link', 'url' => 'profile.php', 'icon' => 'ph-user', 'title' => 'My Profile'];
    $menuItems[] = ['type' => 'link', 'url' => 'change_password.php', 'icon' => 'ph-lock', 'title' => 'Change Password'];
    $menuItems[] = ['type' => 'link', 'url' => 'logout.php', 'icon' => 'ph-sign-out', 'title' => 'Logout', 'class' => 'text-danger'];
    
    return $menuItems;
    }
}

$currentPage = getCurrentPage();
$menuItems = getPensionMenuConfig($rbac);

?>

<!-- Pension System Sidebar -->
<div class="sidebar">
    <nav>
        <div class="app-logo">
            <a class="logo d-inline-block" href="index.php">
                <img src="assets/images/logo-sm.png" alt="Pension System" class="img-fluid" style="max-height: 40px;">
            </a>
            <span class="bg-light-primary toggle-semi-nav ms-2">
                <i class="ti ti-chevrons-right f-s-20"></i>
            </span>
        </div>

        <div class="app-nav" id="app-simple-bar">
            <?php if ($user_details): ?>
                <!-- User Info in Sidebar -->
                <div class="user-info-sidebar">
                    <div class="user-avatar">
                        <?php echo strtoupper(substr($user_details['full_name'] ?? 'U', 0, 2)); ?>
                    </div>
                    <div class="user-details">
                        <div class="user-name"><?php echo htmlspecialchars($user_details['full_name'] ?? 'User'); ?></div>
                        <div class="user-role"><?php echo htmlspecialchars($userRole); ?></div>
                        <?php if ($rbac): ?>
                            <div class="user-permissions">
                                <?php 
                                $perms = $rbac->getPermissions();
                                echo count($perms) === 1 && $perms[0] === '*' ? 'Full Access' : count($perms) . ' permissions';
                                ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endif; ?>

            <ul class="main-nav p-0 mt-2">
                <?php if (empty($menuItems)): ?>
                    <!-- Fallback menu -->
                    <li class="menu-title">
                        <span>Main Menu</span>
                    </li>
                    <li class="no-sub">
                        <a href="index.php" class="<?php echo $currentPage === 'index.php' ? 'active' : ''; ?>">
                            <i class="ph-duotone ph-house"></i>
                            Dashboard
                        </a>
                    </li>
                    <li class="menu-title">
                        <span>My Account</span>
                    </li>
                    <li class="no-sub">
                        <a href="profile.php" class="<?php echo $currentPage === 'profile.php' ? 'active' : ''; ?>">
                            <i class="ph-duotone ph-user"></i>
                            My Profile
                        </a>
                    </li>
                    <li class="no-sub">
                        <a href="logout.php" class="text-danger">
                            <i class="ph-duotone ph-sign-out"></i>
                            Logout
                        </a>
                    </li>
                <?php else: ?>
                    <?php foreach ($menuItems as $item): ?>
                        
                        <?php if ($item['type'] === 'header'): ?>
                            <!-- Menu Header -->
                            <li class="menu-title">
                                <span><?php echo htmlspecialchars($item['title']); ?></span>
                            </li>
                        
                        <?php elseif ($item['type'] === 'link'): ?>
                            <!-- Single Link -->
                            <li class="no-sub">
                                <a class="<?php echo isMenuActive($item['url'], $currentPage) ? 'active' : ''; ?> <?php echo isset($item['class']) ? $item['class'] : ''; ?>" 
                                   href="<?php echo htmlspecialchars($item['url']); ?>">
                                    <i class="ph-duotone <?php echo htmlspecialchars($item['icon']); ?>"></i>
                                    <?php echo htmlspecialchars($item['title']); ?>
                                </a>
                            </li>
                        
                        <?php elseif ($item['type'] === 'dropdown'): ?>
                            <!-- Dropdown Menu -->
                            <li>
                                <a class="<?php echo hasActiveItem($item['items'], $currentPage) ? 'active' : ''; ?>" 
                                   data-bs-toggle="collapse" 
                                   href="#<?php echo htmlspecialchars($item['id']); ?>" 
                                   aria-expanded="<?php echo hasActiveItem($item['items'], $currentPage) ? 'true' : 'false'; ?>">
                                    <i class="ph-duotone <?php echo htmlspecialchars($item['icon']); ?>"></i>
                                    <?php echo htmlspecialchars($item['title']); ?>
                                    <span class="item-count"><?php echo count($item['items']); ?></span>
                                </a>
                                <ul class="collapse <?php echo hasActiveItem($item['items'], $currentPage) ? 'show' : ''; ?>" 
                                    id="<?php echo htmlspecialchars($item['id']); ?>">
                                    <?php foreach ($item['items'] as $subItem): ?>
                                        <li>
                                            <a href="<?php echo htmlspecialchars($subItem['url']); ?>" 
                                               class="<?php echo isMenuActive($subItem['url'], $currentPage) ? 'active' : ''; ?>">
                                                <?php echo htmlspecialchars($subItem['title']); ?>
                                            </a>
                                        </li>
                                    <?php endforeach; ?>
                                </ul>
                            </li>
                        
                        <?php endif; ?>
                        
                    <?php endforeach; ?>
                <?php endif; ?>
            </ul>
        </div>

        <div class="menu-navs">
            <span class="menu-previous"><i class="ti ti-chevron-left"></i></span>
            <span class="menu-next"><i class="ti ti-chevron-right"></i></span>
        </div>
    </nav>
</div>

<style>
/* Pension System Sidebar Styles */
.sidebar {
    width: 280px;
    background: #fff;
    box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
    height: 100vh;
    position: fixed;
    left: 0;
    top: 70px; /* Below topbar */
    z-index: 1000;
    overflow-y: auto;
}

.app-logo {
    padding: 1rem;
    border-bottom: 1px solid #e9ecef;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

/* User Info in Sidebar */
.user-info-sidebar {
    padding: 1rem 1.5rem;
    border-bottom: 1px solid #e9ecef;
    display: flex;
    align-items: center;
    gap: 0.75rem;
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
}

.user-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: linear-gradient(135deg, #2563eb 0%, #3b82f6 100%);
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 600;
    font-size: 0.875rem;
    box-shadow: 0 2px 8px rgba(37, 99, 235, 0.3);
}

.user-details {
    flex: 1;
}

.user-name {
    font-weight: 600;
    color: #495057;
    font-size: 0.875rem;
    margin-bottom: 0.25rem;
}

.user-role {
    font-size: 0.75rem;
    color: #6c757d;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.user-permissions {
    font-size: 0.65rem;
    color: #8391a2;
    margin-top: 0.25rem;
}

.main-nav {
    list-style: none;
    padding: 0;
    margin: 0;
}

.menu-title {
    padding: 1rem 1.5rem 0.5rem;
    font-size: 0.75rem;
    font-weight: 600;
    text-transform: uppercase;
    color: #6c757d;
    letter-spacing: 0.5px;
}

.main-nav > li > a {
    display: flex;
    align-items: center;
    padding: 0.75rem 1.5rem;
    color: #495057;
    text-decoration: none;
    transition: all 0.3s ease;
    border-left: 3px solid transparent;
    position: relative;
}

.main-nav > li > a:hover,
.main-nav > li > a.active {
    background-color: #f8f9fa;
    color: #2563eb;
    border-left-color: #2563eb;
}

.main-nav > li > a i {
    margin-right: 0.75rem;
    font-size: 1.25rem;
    width: 20px;
}

.item-count {
    margin-left: auto;
    background: #e9ecef;
    color: #6c757d;
    font-size: 0.75rem;
    padding: 0.25rem 0.5rem;
    border-radius: 1rem;
    font-weight: 600;
}

.main-nav > li > a.active .item-count {
    background: #2563eb;
    color: white;
}

.main-nav ul {
    list-style: none;
    padding: 0;
    margin: 0;
    background-color: #f8f9fa;
}

.main-nav ul li a {
    display: block;
    padding: 0.5rem 1.5rem 0.5rem 3.5rem;
    color: #6c757d;
    text-decoration: none;
    transition: all 0.3s ease;
    position: relative;
}

.main-nav ul li a:hover,
.main-nav ul li a.active {
    color: #2563eb;
    background-color: #e3f2fd;
}

.main-nav ul li a.active::before {
    content: '';
    position: absolute;
    left: 3rem;
    top: 50%;
    transform: translateY(-50%);
    width: 4px;
    height: 4px;
    background: #2563eb;
    border-radius: 50%;
}

.toggle-semi-nav {
    cursor: pointer;
    padding: 0.25rem 0.5rem;
    border-radius: 0.25rem;
    transition: all 0.3s ease;
}

.toggle-semi-nav:hover {
    background-color: #e9ecef;
}

.menu-navs {
    position: absolute;
    bottom: 1rem;
    left: 50%;
    transform: translateX(-50%);
    display: flex;
    gap: 0.5rem;
}

.menu-navs span {
    cursor: pointer;
    padding: 0.5rem;
    background: #f8f9fa;
    border-radius: 0.25rem;
    transition: all 0.3s ease;
}

.menu-navs span:hover {
    background: #e9ecef;
}

/* Responsive */
@media (max-width: 768px) {
    .sidebar {
        transform: translateX(-100%);
        transition: transform 0.3s ease;
        top: 60px;
    }
    
    .sidebar.show {
        transform: translateX(0);
    }
}

/* Main Content Area Layout */
.main-content {
    margin-left: 280px;
    margin-top: 70px;
    padding: 2rem 1.5rem 1.5rem 1.5rem;
    min-height: calc(100vh - 70px);
    background: #f8f9fa;
    transition: all 0.3s ease;
}

/* Add spacing to first content elements */
.main-content > *:first-child,
.main-content .page-header:first-child,
.main-content .card:first-child,
.main-content .row:first-child {
    margin-top: 1rem;
}

/* Welcome/Greeting Card Styling */
.welcome-card,
.greeting-card {
    margin-bottom: 1.5rem;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* Stats Cards Spacing */
.stats-row,
.dashboard-stats {
    margin-top: 1.5rem;
}

/* Responsive adjustments for main content */
@media (max-width: 768px) {
    .main-content {
        margin-left: 0;
        margin-top: 60px;
        padding: 1.5rem 1rem 1rem 1rem;
    }
    
    .main-content > *:first-child,
    .main-content .page-header:first-child,
    .main-content .card:first-child,
    .main-content .row:first-child {
        margin-top: 0.75rem;
    }
}

/* Text danger style for logout */
.text-danger {
    color: #dc3545 !important;
}

.text-danger:hover {
    color: #bb2d3b !important;
    background-color: #f8d7da !important;
}

/* Smooth transitions for dropdowns */
.collapse {
    transition: height 0.3s ease-in-out;
    overflow: hidden;
}

.collapse:not(.show) {
    display: block;
    height: 0 !important;
}

.collapse.show {
    display: block;
    height: auto;
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    <?php if ($rbac): ?>
    console.group('Pension RBAC Info');
    console.log('User Role: <?php echo $userRole; ?>');
    console.log('Role ID: <?php echo $rbac->getRoleId(); ?>');
    console.log('Permissions:', <?php echo json_encode($rbac->getPermissions()); ?>);
    console.log('Menu Items: <?php echo count($menuItems); ?>');
    console.groupEnd();
    <?php endif; ?>
    
    // Initialize menu state
    initializeMenuState();
    
    // Handle dropdown toggles
    const dropdownToggles = document.querySelectorAll('[data-bs-toggle="collapse"]');
    dropdownToggles.forEach(toggle => {
        toggle.removeAttribute('data-bs-toggle');
        
        toggle.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            const targetId = this.getAttribute('href').substring(1);
            const targetElement = document.getElementById(targetId);
            
            if (targetElement) {
                const isOpen = targetElement.classList.contains('show');
                
                if (isOpen) {
                    targetElement.style.height = targetElement.scrollHeight + 'px';
                    targetElement.offsetHeight;
                    targetElement.style.height = '0px';
                    
                    setTimeout(() => {
                        targetElement.classList.remove('show');
                        targetElement.style.height = '';
                    }, 300);
                    
                    this.setAttribute('aria-expanded', 'false');
                } else {
                    targetElement.classList.add('show');
                    const height = targetElement.scrollHeight;
                    targetElement.style.height = '0px';
                    targetElement.offsetHeight;
                    targetElement.style.height = height + 'px';
                    
                    setTimeout(() => {
                        targetElement.style.height = 'auto';
                    }, 300);
                    
                    this.setAttribute('aria-expanded', 'true');
                }
                
                setTimeout(saveMenuState, 350);
            }
        });
    });
    
    function saveMenuState() {
        const openDropdowns = [];
        document.querySelectorAll('.collapse.show').forEach(dropdown => {
            openDropdowns.push(dropdown.id);
        });
        localStorage.setItem('pension_sidebar_state', JSON.stringify(openDropdowns));
    }
    
    function initializeMenuState() {
        try {
            const savedState = localStorage.getItem('pension_sidebar_state');
            if (savedState) {
                const openDropdowns = JSON.parse(savedState);
                
                document.querySelectorAll('.collapse').forEach(dropdown => {
                    dropdown.classList.remove('show');
                    dropdown.style.height = '0px';
                });
                
                openDropdowns.forEach(dropdownId => {
                    const dropdown = document.getElementById(dropdownId);
                    const toggle = document.querySelector(`[href="#${dropdownId}"]`);
                    
                    if (dropdown && toggle) {
                        dropdown.classList.add('show');
                        dropdown.style.height = 'auto';
                        toggle.setAttribute('aria-expanded', 'true');
                    }
                });
            } else {
                document.querySelectorAll('.collapse').forEach(dropdown => {
                    dropdown.classList.remove('show');
                    dropdown.style.height = '0px';
                });
            }
        } catch (e) {
            console.warn('Failed to restore menu state:', e);
        }
    }
});
</script>