<?php
/**
 * Property Management System Menu/Sidebar
 * File: layouts/menu.php or layouts/sidebar.php
 * Aligned with property management database schema
 */

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

// Get user role and current page
$userRole = 'guest';
$current_page = basename($_SERVER['PHP_SELF']);
$user_details = null;

if (isset($_SESSION['user_id'])) {
    // Get user details with correct schema
    $user_id = $_SESSION['user_id'];
    $sql_user_details = "SELECT u.*, r.role_name 
                         FROM users u 
                         INNER JOIN roles r ON u.role_id = r.id 
                         WHERE u.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'];
        // Build full name
        $full_name = trim($user_details['first_name'] . ' ' . 
                         ($user_details['middle_name'] ?? '') . ' ' . 
                         $user_details['last_name']);
        $user_details['full_name'] = $full_name;
    }
}

// Get menu configuration for user role
$menuItems = getMenuConfig($userRole);
$currentPage = basename($_SERVER['PHP_SELF']);

/**
 * Check if current page matches menu item URL
 */
function isMenuActive($url, $currentPage) {
    $menuPage = basename($url);
    return $menuPage === $currentPage;
}

/**
 * Check if dropdown has active item
 */
function hasActiveItem($items, $currentPage) {
    foreach ($items as $item) {
        if (isset($item['url'])) {
            $menuPage = basename($item['url']);
            if ($menuPage === $currentPage) {
                return true;
            }
        }
    }
    return false;
}

/**
 * Get current page for menu highlighting
 */
function getCurrentPage() {
    return basename($_SERVER['PHP_SELF']);
}
?>

<!-- Sidebar - Property Management System -->
<div class="sidebar">
    <nav>
        <div class="app-logo">
            <a class="logo d-inline-block" href="index.php">
                <img src="assets/images/logo/logo.png" alt="Property Management" 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 
                        $initials = '';
                        if (!empty($user_details['first_name'])) {
                            $initials .= strtoupper(substr($user_details['first_name'], 0, 1));
                        }
                        if (!empty($user_details['last_name'])) {
                            $initials .= strtoupper(substr($user_details['last_name'], 0, 1));
                        }
                        if (empty($initials)) {
                            $initials = 'U';
                        }
                        echo $initials;
                        ?>
                    </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>
                    </div>
                </div>
            <?php endif; ?>

            <ul class="main-nav p-0 mt-2">
                <?php if (empty($menuItems)): ?>
                    <!-- Fallback menu if no items are configured -->
                    <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; ?>

                    <!-- Always add My Account section at the end -->
                    <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="change_password.php" class="<?php echo $currentPage === 'change_password.php' ? 'active' : ''; ?>">
                            <i class="ph-duotone ph-lock"></i>
                            Change Password
                        </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 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>
    /* Property Management 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: 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;
    }

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

    .collapse.show {
        height: auto;
    }

    /* Prevent text selection on menu items */
    .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;
    }

    /* Scrollbar styling */
    .sidebar::-webkit-scrollbar {
        width: 6px;
    }

    .sidebar::-webkit-scrollbar-track {
        background: #f1f1f1;
    }

    .sidebar::-webkit-scrollbar-thumb {
        background: #888;
        border-radius: 3px;
    }

    .sidebar::-webkit-scrollbar-thumb:hover {
        background: #555;
    }
</style>

<script>
    // Enhanced menu functionality
    document.addEventListener('DOMContentLoaded', function () {
        console.log('Property Management System Menu Initialized');
        console.log('User Role: <?php echo $userRole; ?>');

        // Initialize menu state
        initializeMenuState();

        // Handle dropdown toggles
        const dropdownToggles = document.querySelectorAll('[data-bs-toggle="collapse"]');
        dropdownToggles.forEach(toggle => {
            // Remove 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
                        targetElement.style.height = targetElement.scrollHeight + 'px';
                        targetElement.offsetHeight; // Force reflow
                        targetElement.style.height = '0px';

                        setTimeout(() => {
                            targetElement.classList.remove('show');
                            targetElement.style.height = '';
                        }, 300);

                        this.setAttribute('aria-expanded', 'false');
                    } else {
                        // Open the dropdown
                        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);

                        this.setAttribute('aria-expanded', 'true');
                    }

                    // Save state
                    setTimeout(() => {
                        saveMenuState();
                    }, 350);
                }
            });
        });

        // Save menu state to localStorage
        function saveMenuState() {
            const openDropdowns = [];
            document.querySelectorAll('.collapse.show').forEach(dropdown => {
                openDropdowns.push(dropdown.id);
            });
            localStorage.setItem('property_menu_state', JSON.stringify(openDropdowns));
        }

        // Restore menu state from localStorage
        function initializeMenuState() {
            try {
                const savedState = localStorage.getItem('property_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';
                });
            }
        }

        // Mobile menu toggle (if you have a hamburger button)
        const mobileMenuToggle = document.querySelector('.mobile-menu-toggle');
        if (mobileMenuToggle) {
            mobileMenuToggle.addEventListener('click', function() {
                const sidebar = document.querySelector('.sidebar');
                sidebar.classList.toggle('show');
            });
        }

        // Close sidebar on mobile when clicking outside
        document.addEventListener('click', function(e) {
            if (window.innerWidth <= 768) {
                const sidebar = document.querySelector('.sidebar');
                const mobileToggle = document.querySelector('.mobile-menu-toggle');
                
                if (sidebar && !sidebar.contains(e.target) && !mobileToggle?.contains(e.target)) {
                    sidebar.classList.remove('show');
                }
            }
        });
    });
</script>