<?php
/**
 * ENT Hospital Management System - Complete Database-Driven Sidebar
 * File: layouts/sidebar.php
 * 
 * Features:
 * - 100% database-driven from menu_items and role_permissions tables
 * - Role-specific dashboards
 * - System Administration pages for Super Admin
 * - Original sidebar design preserved
 * - Bootstrap native collapse
 */

// ============================================
// RBAC CLASS
// ============================================

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 === 'Super Admin') {
                $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 m.menu_url 
                          FROM role_permissions rp 
                          JOIN menu_items m ON rp.menu_id = m.menu_id 
                          WHERE rp.role_id = ? AND rp.can_view = 1 AND m.is_active = 1";
            $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()) {
                $url = $row['menu_url'];
                if ($url) {
                    $this->assigned_pages[] = $url;
                    if (strpos($url, '/') === 0) {
                        $this->assigned_pages[] = substr($url, 1);
                    }
                }
            }

            // Always include basic pages
            $basic_pages = ['index.php', 'profile.php', 'change_password.php', 'logout.php', 'notifications.php', 'help_support.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;
        }
    }
}

// ============================================
// DASHBOARD ROUTING BY ROLE
// ============================================

/**
 * Get role-specific dashboard URL
 */
function getRoleDashboard($userRole) {
    $dashboards = [
        'Super Admin' => 'index.php',
        'Hospital Admin' => 'admin_dashboard.php',
        'ENT Consultant' => 'doctor_dashboard.php',
        'ENT Doctor' => 'doctor_dashboard.php',
        'Resident Doctor' => 'doctor_dashboard.php',
        'Head Nurse' => 'nurse_dashboard.php',
        'ENT Nurse' => 'nurse_dashboard.php',
        'Audiologist' => 'audiologist_dashboard.php',
        'Lab Technician' => 'lab_dashboard.php',
        'Receptionist' => 'receptionist_dashboard.php',
        'Billing Clerk' => 'billing_dashboard.php',
        'Medical Records' => 'records_dashboard.php',
        'Patient' => 'patient_dashboard.php'
    ];
    
    return $dashboards[$userRole] ?? 'index.php';
}

// ============================================
// USER AUTHENTICATION & SETUP
// ============================================

$userRole = 'guest';
$assigned_pages = [];
$current_page = basename($_SERVER['PHP_SELF']);
$rbac = null;
$user_details = null;
$role_id = null;
$roleDashboard = 'index.php';

if (isset($_SESSION['user_id'])) {
    $user_id = $_SESSION['user_id'];
    $sql_user_details = "SELECT u.*, ur.role_name, ur.role_id 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'];
        $role_id = $user_details['role_id'];
        $roleDashboard = getRoleDashboard($userRole);
        
        // Initialize RBAC system
        $rbac = new RoleBasedAccessControl($conn, $user_id);
        $assigned_pages = $rbac->getAssignedPages();
    }
}

// ============================================
// BUILD MENU FROM DATABASE
// ============================================

function buildDatabaseMenu($role_id, $conn, $roleDashboard, $userRole) {
    if (!$role_id) {
        return [];
    }
    
    $menu = [];
    
    // For Super Admin, get ALL sections and pages regardless of permissions
    if ($userRole === 'Super Admin') {
        // Get all sections
        $sections_sql = "SELECT 
                            menu_id,
                            menu_name,
                            menu_icon,
                            menu_order
                        FROM menu_items
                        WHERE menu_type = 'SECTION'
                        AND is_active = 1
                        ORDER BY menu_order ASC";
        
        $sections_result = $conn->query($sections_sql);
        
        $sections = [];
        while ($section = $sections_result->fetch_assoc()) {
            $sections[$section['menu_id']] = $section;
        }
        
        // Get all pages
        $pages_sql = "SELECT 
                        menu_id,
                        menu_name,
                        menu_url,
                        menu_icon,
                        parent_id,
                        menu_order
                    FROM menu_items
                    WHERE menu_type = 'PAGE'
                    AND is_active = 1
                    AND menu_url IS NOT NULL
                    AND menu_url != ''
                    ORDER BY parent_id, menu_order ASC";
        
        $pages_result = $conn->query($pages_sql);
        
    } else {
        // For other roles, only get sections and pages they have permission to
        $sections_sql = "SELECT DISTINCT 
                            parent.menu_id,
                            parent.menu_name,
                            parent.menu_icon,
                            parent.menu_order
                        FROM role_permissions rp
                        INNER JOIN menu_items mi ON rp.menu_id = mi.menu_id
                        INNER JOIN menu_items parent ON mi.parent_id = parent.menu_id
                        WHERE rp.role_id = ? 
                        AND rp.can_view = 1
                        AND mi.is_active = 1
                        AND parent.is_active = 1
                        AND parent.menu_type = 'SECTION'
                        AND mi.menu_url IS NOT NULL
                        AND mi.menu_url != ''
                        ORDER BY parent.menu_order ASC";
        
        $stmt = $conn->prepare($sections_sql);
        $stmt->bind_param("i", $role_id);
        $stmt->execute();
        $sections_result = $stmt->get_result();
        
        $sections = [];
        while ($section = $sections_result->fetch_assoc()) {
            $sections[$section['menu_id']] = $section;
        }
        
        // Get pages with permissions
        $pages_sql = "SELECT 
                        mi.menu_id,
                        mi.menu_name,
                        mi.menu_url,
                        mi.menu_icon,
                        mi.parent_id,
                        mi.menu_order
                    FROM role_permissions rp
                    INNER JOIN menu_items mi ON rp.menu_id = mi.menu_id
                    WHERE rp.role_id = ? 
                    AND rp.can_view = 1
                    AND mi.is_active = 1
                    AND mi.menu_type = 'PAGE'
                    AND mi.menu_url IS NOT NULL
                    AND mi.menu_url != ''
                    ORDER BY mi.parent_id, mi.menu_order ASC";
        
        $stmt = $conn->prepare($pages_sql);
        $stmt->bind_param("i", $role_id);
        $stmt->execute();
        $pages_result = $stmt->get_result();
    }
    
    // Group pages by parent
    $pagesByParent = [];
    while ($page = $pages_result->fetch_assoc()) {
        $parent_id = $page['parent_id'] ?: 0;
        $pagesByParent[$parent_id][] = $page;
    }
    
    // Build menu structure
    // Main Menu Header
    $menu[] = [
        'title' => 'Main Menu',
        'type' => 'header'
    ];
    
    // Dashboard - Use role-specific dashboard
    $menu[] = [
        'title' => 'Dashboard',
        'icon' => 'ph-chart-line',
        'url' => $roleDashboard,
        'type' => 'link'
    ];
    
    // Build sections with their pages
    foreach ($sections as $section_id => $section) {
        if (!isset($pagesByParent[$section_id]) || empty($pagesByParent[$section_id])) {
            continue; // Skip sections with no pages
        }
        
        // Add section header
        $menu[] = [
            'title' => $section['menu_name'],
            'type' => 'header'
        ];
        
        $pages = $pagesByParent[$section_id];
        
        // If section has 3 or more pages, create dropdown
        if (count($pages) >= 3) {
            $dropdownItems = [];
            foreach ($pages as $page) {
                $dropdownItems[] = [
                    'title' => $page['menu_name'],
                    'url' => $page['menu_url']
                ];
            }
            
            $menu[] = [
                'title' => $section['menu_name'],
                'icon' => $section['menu_icon'] ?: 'ph-folder',
                'type' => 'dropdown',
                'id' => 'section_' . $section_id . '_menu',
                'items' => $dropdownItems
            ];
        } else {
            // For 1-2 pages, add as individual links
            foreach ($pages as $page) {
                $menu[] = [
                    'title' => $page['menu_name'],
                    'icon' => $page['menu_icon'] ?: 'ph-file',
                    'url' => $page['menu_url'],
                    'type' => 'link'
                ];
            }
        }
    }
    
    // Add orphan pages (pages without parent sections)
    if (isset($pagesByParent[0]) && !empty($pagesByParent[0])) {
        foreach ($pagesByParent[0] as $page) {
            // Skip dashboard as it's already added
            if ($page['menu_url'] === 'index.php' || $page['menu_url'] === $roleDashboard) continue;
            
            $menu[] = [
                'title' => $page['menu_name'],
                'icon' => $page['menu_icon'] ?: 'ph-file',
                'url' => $page['menu_url'],
                'type' => 'link'
            ];
        }
    }
    
    // My Account section (always at bottom)
    $menu[] = [
        'title' => 'My Account',
        'type' => 'header'
    ];
    
    $menu[] = [
        'title' => 'My Profile',
        'icon' => 'ph-user',
        'url' => 'profile.php',
        'type' => 'link'
    ];
    
    $menu[] = [
        'title' => 'Change Password',
        'icon' => 'ph-lock-key',
        'url' => 'change_password.php',
        'type' => 'link'
    ];
    
    $menu[] = [
        'title' => 'Notifications',
        'icon' => 'ph-bell',
        'url' => 'notifications.php',
        'type' => 'link'
    ];
    
    $menu[] = [
        'title' => 'Help & Support',
        'icon' => 'ph-question',
        'url' => 'help_support.php',
        'type' => 'link'
    ];
    
    $menu[] = [
        'title' => 'Logout',
        'icon' => 'ph-sign-out',
        'url' => 'logout.php',
        'type' => 'link',
        'class' => 'text-danger'
    ];
    
    return $menu;
}

// Helper functions (with existence checks)
if (!function_exists('getCurrentPage')) {
    function getCurrentPage() {
        return basename($_SERVER['PHP_SELF']);
    }
}

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

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

// Build menu from database
$menuItems = buildDatabaseMenu($role_id, $conn, $roleDashboard, $userRole);
$currentPage = getCurrentPage();

?>

<!-- Sidebar - Original Design with Complete Database Menu -->
<div class="sidebar">
    <nav>
        <div class="app-logo">
            <a class="logo d-inline-block" href="<?php echo $roleDashboard; ?>">
                <img src="assets/images/logo/nelcare.png" alt="ENT Hospital" 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): ?>
                <!-- 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 
                                $pageCount = ($userRole === 'Super Admin') ? 'All' : count($rbac->getAssignedPages());
                                echo $pageCount; 
                                ?> pages assigned
                            </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="<?php echo $roleDashboard; ?>" class="<?php echo $currentPage === basename($roleDashboard) ? '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'): ?>
                            <li class="menu-title">
                                <span><?php echo htmlspecialchars($item['title']); ?></span>
                            </li>

                        <?php elseif ($item['type'] === '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'): ?>
                            <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>

    </nav>
</div>

<style>
/* Original 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-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;
}

@media (max-width: 768px) {
    .sidebar {
        transform: translateX(-100%);
        transition: transform 0.3s ease;
    }

    .sidebar.show {
        transform: translateX(0);
    }
}

.text-danger {
    color: #dc3545 !important;
}

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

.collapse {
    transition: height 0.35s ease;
}

.user-permissions {
    font-size: 0.65rem !important;
    color: #8391a2 !important;
    margin-top: 0.25rem !important;
}
</style>

<script>
// Bootstrap handles collapse automatically
document.addEventListener('DOMContentLoaded', function () {
    <?php if (isset($_SESSION['user_id']) && $rbac): ?>
        console.group('📊 ENT Menu - Complete Database');
        console.log('User Role:', '<?php echo $userRole; ?>');
        console.log('Dashboard:', '<?php echo $roleDashboard; ?>');
        console.log('Menu Items Built:', <?php echo count($menuItems); ?>);
        console.log('Sections Found:', <?php 
            $headerCount = 0;
            foreach($menuItems as $item) {
                if($item['type'] === 'header') $headerCount++;
            }
            echo $headerCount;
        ?>);
        <?php if ($userRole === 'Super Admin'): ?>
        console.log('⚠️ Super Admin Mode: Showing ALL menu items from database');
        <?php endif; ?>
        console.groupEnd();
    <?php endif; ?>

    // Mobile sidebar toggle
    const toggleBtn = document.querySelector('.toggle-semi-nav');
    const sidebar = document.querySelector('.sidebar');

    if (toggleBtn && sidebar) {
        toggleBtn.addEventListener('click', function(e) {
            e.preventDefault();
            sidebar.classList.toggle('show');
        });
    }

    // Close on outside click (mobile)
    document.addEventListener('click', function(e) {
        if (window.innerWidth <= 768) {
            if (sidebar && !sidebar.contains(e.target) && sidebar.classList.contains('show')) {
                sidebar.classList.remove('show');
            }
        }
    });
});

// Utility function to check page access
function checkPageAccess(pageName) {
    <?php if ($rbac): ?>
        <?php if ($userRole === 'Super Admin'): ?>
            return true; // Super Admin has access to everything
        <?php else: ?>
            const assignedPages = <?php echo json_encode($rbac->getAssignedPages()); ?>;
            return assignedPages.includes(pageName) || assignedPages.includes('*');
        <?php endif; ?>
    <?php else: ?>
        return true;
    <?php endif; ?>
}
</script>