<?php
/**
 * Your Current Sidebar with Role-Based Access Control Integration
 * File: layouts/menu.php
 */

// Include the RBAC system - First create the RBAC class if it doesn't exist
if (!class_exists('RoleBasedAccessControl')) {
    class RoleBasedAccessControl {
        private $conn;
        private $user_id;
        private $user_role;
        private $assigned_pages = [];
        
        public function __construct($conn, $user_id = null) {
            $this->conn = $conn;
            $this->user_id = $user_id;
            
            if ($user_id) {
                $this->loadUserRole();
               $this->loadAssignedPages();
            }
        }
        
        private function loadUserRole() {
            $sql = "SELECT u.*, ur.role_name FROM users u 
                    INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                    WHERE u.user_id = ?";
            $stmt = $this->conn->prepare($sql);
            $stmt->bind_param("i", $this->user_id);
            $stmt->execute();
            $result = $stmt->get_result()->fetch_assoc();
            
            if ($result) {
                $this->user_role = $result['role_name'];
            }
        }
        
        private function loadAssignedPages() {
            // Super Admin gets access to everything
            if ($this->user_role === 'Administrator') {
                $this->assigned_pages = ['*'];
                return;
            }
            
            // Get role ID first
            $role_sql = "SELECT role_id FROM user_roles WHERE role_name = ?";
            $role_stmt = $this->conn->prepare($role_sql);
            $role_stmt->bind_param("s", $this->user_role);
            $role_stmt->execute();
            $role_result = $role_stmt->get_result()->fetch_assoc();
            
            if (!$role_result) {
                return;
            }
            
            $role_id = $role_result['role_id'];
            
            // Get assigned pages for this role
            $pages_sql = "SELECT page_name FROM role_page_permissions WHERE role_id = ?";
            $pages_stmt = $this->conn->prepare($pages_sql);
            $pages_stmt->bind_param("i", $role_id);
            $pages_stmt->execute();
            $pages_result = $pages_stmt->get_result();
            
            $this->assigned_pages = [];
            while ($row = $pages_result->fetch_assoc()) {
                $this->assigned_pages[] = $row['page_name'];
            }
            
            // Always include basic pages
            $basic_pages = ['index.php', 'profile.php', 'change_password.php', 'logout.php'];
            $this->assigned_pages = array_merge($this->assigned_pages, $basic_pages);
        }
        
        public function hasPageAccess($page_name) {
            if ($this->user_role === 'Super Admin' || in_array('*', $this->assigned_pages)) {
                return true;
            }
            return in_array($page_name, $this->assigned_pages);
        }
        
        public function getAssignedPages() {
            return $this->assigned_pages;
        }
        
        public function getUserRole() {
            return $this->user_role;
        }
        
        public function filterMenuConfig($menuConfig) {
            if ($this->user_role === 'Super Admin' || in_array('*', $this->assigned_pages)) {
                return $menuConfig;
            }
            
            $filteredMenu = [];
            
            foreach ($menuConfig as $item) {
                if ($item['type'] === 'header') {
                    $filteredMenu[] = $item;
                    continue;
                }
                
                if ($item['type'] === 'link') {
                    if ($this->hasPageAccess($item['url'])) {
                        $filteredMenu[] = $item;
                    }
                    continue;
                }
                
                if ($item['type'] === 'dropdown' && isset($item['items'])) {
                    $filteredItems = [];
                    
                    foreach ($item['items'] as $subItem) {
                        if (isset($subItem['url']) && $this->hasPageAccess($subItem['url'])) {
                            $filteredItems[] = $subItem;
                        }
                    }
                    
                    if (!empty($filteredItems)) {
                        $item['items'] = $filteredItems;
                        $filteredMenu[] = $item;
                    }
                }
            }
            
            return $this->removeEmptyHeaders($filteredMenu);
        }
        
        private function removeEmptyHeaders($menu) {
            $cleanMenu = [];
            $currentHeader = null;
            $hasItemsAfterHeader = false;
            
            foreach ($menu as $item) {
                if ($item['type'] === 'header') {
                    if ($currentHeader && $hasItemsAfterHeader) {
                        $cleanMenu[] = $currentHeader;
                        $hasItemsAfterHeader = false;
                    }
                    $currentHeader = $item;
                } else {
                    if ($currentHeader) {
                        $cleanMenu[] = $currentHeader;
                        $currentHeader = null;
                    }
                    $cleanMenu[] = $item;
                    $hasItemsAfterHeader = true;
                }
            }
            
            if ($currentHeader && $hasItemsAfterHeader) {
                $cleanMenu[] = $currentHeader;
            }
            
            return $cleanMenu;
        }
    }
}

// Include menu configuration
require_once 'includes/menu_config.php';

// Get user role and assigned pages
$userRole = 'guest';
$assigned_pages = [];
$current_page = basename($_SERVER['PHP_SELF']);
$rbac = null;

if (isset($_SESSION['user_id'])) {
    // Get user details and role
    $user_id = $_SESSION['user_id'];
    $sql_user_details = "SELECT u.*, ur.role_name FROM users u 
                         INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                         WHERE u.user_id = ?";
    $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'];
        
        // Initialize RBAC system
        $rbac = new RoleBasedAccessControl($conn, $user_id);
        $assigned_pages = $rbac->getAssignedPages();
    }
}

// Get menu configuration for user role, filtered by assigned pages
$menuItems = getFilteredMenuConfig($userRole, $assigned_pages, $rbac);
$currentPage = getCurrentPage();

/**
 * Filter menu configuration based on assigned pages (Updated to work with RBAC)
 */
function getFilteredMenuConfig($userRole, $assigned_pages, $rbac = null) {
    // If Super Admin or has all pages access, show everything
    if ($userRole === 'Super Admin' || in_array('*', $assigned_pages)) {
        return getMenuConfig($userRole);
    }
    
    // If RBAC is available, use it for filtering
    if ($rbac) {
        $fullMenu = getMenuConfig($userRole);
        return $rbac->filterMenuConfig($fullMenu);
    }
    
    // Fallback to original method
    $fullMenu = getMenuConfig($userRole);
    $filteredMenu = [];
    
    foreach ($fullMenu as $item) {
        // Always include headers and account items
        if ($item['type'] === 'header') {
            // Check if this section has any accessible items
            $sectionHasItems = false;
            
            // Look ahead to see if any items in this section are accessible
            foreach ($fullMenu as $checkItem) {
                if ($checkItem['type'] === 'header' && $checkItem !== $item) {
                    break; // Reached next section
                }
                
                if ($checkItem === $item) continue; // Skip the header itself
                
                if ($checkItem['type'] === 'link') {
                    if (in_array($checkItem['url'], $assigned_pages) || 
                        in_array($checkItem['url'], ['index.php', 'profile.php', 'change_password.php', 'logout.php'])) {
                        $sectionHasItems = true;
                        break;
                    }
                } elseif ($checkItem['type'] === 'dropdown' && isset($checkItem['items'])) {
                    foreach ($checkItem['items'] as $subItem) {
                        if (in_array($subItem['url'], $assigned_pages)) {
                            $sectionHasItems = true;
                            break 2;
                        }
                    }
                }
            }
            
            // Only add header if section has accessible items, or if it's Main Menu/My Account
            if ($sectionHasItems || in_array($item['title'], ['Main Menu', 'My Account'])) {
                $filteredMenu[] = $item;
            }
            continue;
        }
        
        // Always include dashboard and account links
        if ($item['type'] === 'link' && 
            in_array($item['url'], ['index.php', 'profile.php', 'change_password.php', 'logout.php'])) {
            $filteredMenu[] = $item;
            continue;
        }
        
        // For regular links, check if page is assigned
        if ($item['type'] === 'link' && isset($item['url'])) {
            if (in_array($item['url'], $assigned_pages)) {
                $filteredMenu[] = $item;
            }
            continue;
        }
        
        // For dropdowns, filter sub-items
        if ($item['type'] === 'dropdown' && isset($item['items'])) {
            $filteredItems = [];
            foreach ($item['items'] as $subItem) {
                if (isset($subItem['url']) && in_array($subItem['url'], $assigned_pages)) {
                    $filteredItems[] = $subItem;
                }
            }
            
            // Only include dropdown if it has accessible sub-items
            if (!empty($filteredItems)) {
                $item['items'] = $filteredItems;
                $filteredMenu[] = $item;
            }
        }
    }
    
    return $filteredMenu;
}

?>

<!-- Sidebar - Your Original Design with RBAC Integration -->
<div class="sidebar">
    <nav>
        <div class="app-logo">
            <a class="logo d-inline-block" href="index.php">
                <img src="assets/images/shiine.png" alt="Cargo Platform" 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 (isset($_SESSION['user_id']) && $user_details): ?>
                <!-- Show user info -->
                <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" style="font-size: 0.65rem; color: #8391a2; margin-top: 0.25rem;">
                                <?php echo count($rbac->getAssignedPages()); ?> pages assigned
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endif; ?>

            <ul class="main-nav p-0 mt-2">
                <?php if (empty($menuItems)): ?>
                    <!-- Fallback menu if no items are accessible -->
                    <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-chart-line"></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>
/* Your Original Custom Sidebar Styles (Unchanged) */
.sidebar {
    width: 280px;
    background: #fff;
    box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
    height: 100vh;
    position: fixed;
    left: 0;
    top: 0;
    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;
}

.user-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 600;
    font-size: 0.875rem;
}

.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;
}

.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: #0d6efd;
    border-left-color: #0d6efd;
}

.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: #0d6efd;
    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: #0d6efd;
    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: #0d6efd;
    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;
    }
    
    .sidebar.show {
        transform: translateX(0);
    }
}

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

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

/* Empty state */
.empty-menu {
    text-align: center;
    padding: 2rem 1.5rem;
    color: #6c757d;
}

.empty-menu i {
    font-size: 3rem;
    margin-bottom: 1rem;
    opacity: 0.5;
}

.empty-menu h6 {
    font-weight: 600;
    margin-bottom: 0.5rem;
}

.empty-menu p {
    font-size: 0.875rem;
    margin: 0;
}

/* RBAC Enhancement - Small visual indicator for access control */
.user-permissions {
    font-size: 0.65rem !important;
    color: #8391a2 !important;
    margin-top: 0.25rem !important;
}

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

.collapse.show {
    height: auto;
}

/* Prevent double-click issues and text selection */
.main-nav > li > a {
    user-select: none;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    cursor: pointer;
}

/* Ensure dropdown menus start hidden */
.main-nav ul.collapse:not(.show) {
    display: block;
    height: 0 !important;
    overflow: hidden;
}

.main-nav ul.collapse.show {
    display: block;
    height: auto;
    overflow: visible;
}

/* Smooth transitions for dropdown items */
.main-nav ul li {
    transition: opacity 0.2s ease-in-out;
}

.main-nav ul.collapse:not(.show) li {
    opacity: 0;
}

.main-nav ul.collapse.show li {
    opacity: 1;
}

</style>

<script>
// Enhanced menu functionality with RBAC debugging
document.addEventListener('DOMContentLoaded', function() {
    // Debug RBAC info in console (remove in production)
    <?php if (isset($_SESSION['user_id']) && $rbac): ?>
    console.group('RBAC Debug Information');
    console.log('User Role: <?php echo $userRole; ?>');
    console.log('Total Assigned Pages: <?php echo count($rbac->getAssignedPages()); ?>');
    console.log('Assigned Pages:', <?php echo json_encode($rbac->getAssignedPages()); ?>);
    console.log('Menu Items Count: <?php echo count($menuItems); ?>');
    console.groupEnd();
    <?php endif; ?>
    
    // Initialize menu state first
    initializeMenuState();
    
    // Handle dropdown toggles with improved logic
    const dropdownToggles = document.querySelectorAll('[data-bs-toggle="collapse"]');
    dropdownToggles.forEach(toggle => {
        // Disable Bootstrap's automatic handling
        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 isCurrentlyOpen = targetElement.classList.contains('show');
                
                if (isCurrentlyOpen) {
                    // Close the dropdown with smooth transition
                    targetElement.style.height = targetElement.scrollHeight + 'px';
                    targetElement.offsetHeight; // Force reflow
                    targetElement.style.height = '0px';
                    
                    setTimeout(() => {
                        targetElement.classList.remove('show');
                        targetElement.style.height = '';
                    }, 300); // Match CSS transition duration
                    
                    this.setAttribute('aria-expanded', 'false');
                } else {
                    // Open the dropdown with smooth transition
                    targetElement.classList.add('show');
                    const height = targetElement.scrollHeight;
                    targetElement.style.height = '0px';
                    targetElement.offsetHeight; // Force reflow
                    targetElement.style.height = height + 'px';
                    
                    setTimeout(() => {
                        targetElement.style.height = 'auto';
                    }, 300); // Match CSS transition duration
                    
                    this.setAttribute('aria-expanded', 'true');
                }
                
                // Save state after animation
                setTimeout(() => {
                    saveMenuState();
                }, 350);
            }
        });
    });
    
    // Save menu state to localStorage
    function saveMenuState() {
        const openDropdowns = [];
        document.querySelectorAll('.collapse.show').forEach(dropdown => {
            openDropdowns.push(dropdown.id);
        });
        localStorage.setItem('sidebar_menu_state', JSON.stringify(openDropdowns));
    }
    
    // Restore menu state from localStorage
    function initializeMenuState() {
        try {
            const savedState = localStorage.getItem('sidebar_menu_state');
            if (savedState) {
                const openDropdowns = JSON.parse(savedState);
                
                // Close all dropdowns first
                document.querySelectorAll('.collapse').forEach(dropdown => {
                    dropdown.classList.remove('show');
                    dropdown.style.height = '0px';
                });
                
                // Open saved dropdowns
                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');
                    }
                });
                
                // Set proper states for all toggles
                document.querySelectorAll('[href^="#"]').forEach(toggle => {
                    const targetId = toggle.getAttribute('href').substring(1);
                    const targetElement = document.getElementById(targetId);
                    if (targetElement && !targetElement.classList.contains('show')) {
                        toggle.setAttribute('aria-expanded', 'false');
                    }
                });
            } else {
                // No saved state - ensure all dropdowns are closed
                document.querySelectorAll('.collapse').forEach(dropdown => {
                    dropdown.classList.remove('show');
                    dropdown.style.height = '0px';
                });
                document.querySelectorAll('[href^="#"]').forEach(toggle => {
                    toggle.setAttribute('aria-expanded', 'false');
                });
            }
        } catch (e) {
            console.warn('Failed to restore menu state:', e);
            // Fallback: close all dropdowns
            document.querySelectorAll('.collapse').forEach(dropdown => {
                dropdown.classList.remove('show');
                dropdown.style.height = '0px';
            });
        }
    }
});
});

// Function to refresh menu permissions (useful after role changes)
function refreshMenuPermissions() {
    console.log('Refreshing menu permissions...');
    
    // Add loading state to sidebar
    const sidebar = document.querySelector('.sidebar');
    sidebar.style.opacity = '0.6';
    sidebar.style.pointerEvents = 'none';
    
    // Reload the page to refresh permissions
    setTimeout(() => {
        window.location.reload();
    }, 500);
}

// Page access check function (call this when trying to navigate)
function checkPageAccess(pageName) {
    <?php if ($rbac): ?>
    const assignedPages = <?php echo json_encode($rbac->getAssignedPages()); ?>;
    const userRole = '<?php echo $userRole; ?>';
    
    if (userRole === 'Super Admin' || assignedPages.includes('*') || assignedPages.includes(pageName)) {
        return true;
    }
    
    console.warn('Access denied to page:', pageName);
    return false;
    <?php else: ?>
    return true; // Fallback if RBAC not initialized
    <?php endif; ?>
}
</script>