<?php
/**
 * Menu Mobile Fixo no Rodapé (Estilo App/Nubank)
 * Visível apenas em dispositivos móveis (< 768px)
 * Incluir antes de fechar </body> no layout do dashboard
 */

// Detectar página atual para marcar item ativo
$currentPage = basename($_SERVER['PHP_SELF'], '.php');

// Se estiver em uma pasta específica (ex: /pages/produtos/index.php), usar o nome da pasta
$scriptPath = $_SERVER['PHP_SELF'];
if (preg_match('/pages\/([^\/]+)\/index\.php$/', $scriptPath, $matches)) {
    $currentPage = $matches[1]; // Ex: "produtos"
}

// Definir itens do menu com base no tipo de negócio
$businessType = $_SESSION['business_type'] ?? 'service';

// Buscar dados do usuário e loja se não existirem
if (!isset($user) || !isset($store)) {
    $pdo = getDB();
    $userId = $_SESSION['user_id'] ?? null;
    $storeId = $_SESSION['store_id'] ?? null;

    if ($userId && !isset($user)) {
        $userStmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
        $userStmt->execute([$userId]);
        $user = $userStmt->fetch(PDO::FETCH_ASSOC);
    }

    if ($storeId && !isset($store)) {
        $storeStmt = $pdo->prepare("SELECT * FROM stores WHERE id = ?");
        $storeStmt->execute([$storeId]);
        $store = $storeStmt->fetch(PDO::FETCH_ASSOC);
    }
}

// Menu items - Personalizável
$menuItems = [
    'agendamentos' => [
        'icon' => 'solar:calendar-mark-bold',
        'label' => 'Agenda',
        'url' => '/pages/agendamentos.php',
        'show' => ($businessType === 'service')
    ],
    'pedidos' => [
        'icon' => 'solar:clipboard-list-bold',
        'label' => 'Pedidos',
        'url' => '/pages/pedidos.php',
        'show' => ($businessType === 'retail')
    ],
    'produtos' => [
        'icon' => 'solar:bag-bold',
        'label' => 'Produtos',
        'url' => '/pages/produtos/'
    ],
    'dashboard' => [
        'icon' => 'solar:home-2-bold',
        'label' => 'Início',
        'url' => '/dashboard.php',
        'highlight' => true
    ],
    'clientes' => [
        'icon' => 'solar:users-group-rounded-bold',
        'label' => 'Clientes',
        'url' => '/pages/clientes.php'
    ],
    'more' => [
        'icon' => 'solar:hamburger-menu-linear',
        'label' => 'Mais',
        'url' => '#',
        'onclick' => 'toggleMobileMenu()'
    ]
];

// Filtrar itens que devem ser exibidos
$visibleItems = array_filter($menuItems, function($item) {
    return !isset($item['show']) || $item['show'] === true;
});

// Limitar a 5 itens
$visibleItems = array_slice($visibleItems, 0, 5, true);

// Carregar configuração do menu completo
require_once __DIR__ . '/business-config.php';
$menuConfig = getMenuItems($businessType);

// Itens para acesso rápido (cards)
$quickAccessItems = ['dashboard', 'agendamentos', 'pedidos', 'produtos', 'clientes', 'servicos', 'equipe', 'catalogo', 'categorias', 'estoque'];

// Itens fixos do rodapé
$fixedMenuItems = ['dashboard', 'agendamentos', 'pedidos', 'produtos', 'clientes'];
?>

<!-- Mobile Bottom Navigation -->
<nav class="mobile-bottom-nav" id="mobileBottomNav">
    <div class="mobile-nav-container">
        <?php foreach ($visibleItems as $key => $item):
            $isActive = ($currentPage === $key);
            $isHighlight = isset($item['highlight']) && $item['highlight'];
            $onclick = isset($item['onclick']) ? 'onclick="' . $item['onclick'] . '"' : '';
        ?>
        <a href="<?php echo $item['url']; ?>"
           class="mobile-nav-item <?php echo $isActive ? 'active' : ''; ?> <?php echo $isHighlight ? 'highlight' : ''; ?>"
           <?php echo $onclick; ?>>
            <?php if ($isActive): ?>
            <span class="active-indicator"></span>
            <?php endif; ?>
            <div class="nav-icon-wrapper <?php echo $isHighlight ? 'fab-button' : ''; ?>">
                <iconify-icon icon="<?php echo $item['icon']; ?>"></iconify-icon>
            </div>
            <span class="nav-label"><?php echo $item['label']; ?></span>
        </a>
        <?php endforeach; ?>
    </div>
</nav>


<!-- Mobile Menu Overlay (Estilo Nubank) -->
<div class="mobile-menu-overlay" id="mobileMenuOverlay">
    <div class="mobile-menu-sheet nubank-style">
        
        <!-- Header Nubank -->
        <div class="nubank-header">
            <div class="nubank-header-spacer"></div>
            <h3 class="nubank-title">Menu</h3>
            <button type="button" class="nubank-close-btn" onclick="toggleMobileMenu()">
                <iconify-icon icon="solar:close-circle-bold"></iconify-icon>
            </button>
        </div>

        <!-- Campo de Busca com Resultados Flutuantes -->
        <div class="nubank-search-wrapper">
            <div class="nubank-search">
                <iconify-icon icon="solar:magnifer-linear"></iconify-icon>
                <input type="text" placeholder="O que você procura?" id="menuSearchInput" oninput="filterMenuItems(this.value)">
            </div>
            <!-- Container de Resultados Flutuante -->
            <div class="search-results-dropdown" id="searchResultsDropdown"></div>
        </div>

        <!-- Conteúdo Scrollável -->
        <div class="nubank-menu-content">
            
            <!-- Acesso Rápido (Grid de Cards) -->
            <div class="nubank-section" id="quickAccessSection">
                <h4 class="nubank-section-title">Acesso rápido</h4>
                <div class="nubank-cards-grid">
                    <?php
                    foreach ($menuConfig as $sectionKey => $items) {
                        foreach ($items as $item) {
                            if (in_array($item['page'], $quickAccessItems)) {
                                if (in_array($item['page'], $fixedMenuItems)) continue;
                                $isActive = ($currentPage === $item['page']);
                    ?>
                    <a href="<?php echo $item['url']; ?>" 
                       class="nubank-card <?php echo $isActive ? 'active' : ''; ?>"
                       data-search="<?php echo strtolower($item['label']); ?>">
                        <iconify-icon icon="<?php echo $item['icon']; ?>"></iconify-icon>
                        <span><?php echo $item['label']; ?></span>
                    </a>
                    <?php
                            }
                        }
                    }
                    ?>
                </div>
            </div>

            <!-- Financeiro -->
            <?php if (isset($menuConfig['financeiro']) && !empty($menuConfig['financeiro'])): ?>
            <div class="nubank-section" id="financeiroSection">
                <h4 class="nubank-section-title">Financeiro</h4>
                <div class="nubank-list">
                    <?php foreach ($menuConfig['financeiro'] as $item): 
                        $isActive = ($currentPage === $item['page']);
                    ?>
                    <a href="<?php echo $item['url']; ?>" 
                       class="nubank-list-item <?php echo $isActive ? 'active' : ''; ?>"
                       data-search="<?php echo strtolower($item['label']); ?>">
                        <span><?php echo $item['label']; ?></span>
                        <iconify-icon icon="<?php echo $item['icon']; ?>"></iconify-icon>
                    </a>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>

            <!-- Configurações -->
            <?php if (isset($menuConfig['configuracoes']) && !empty($menuConfig['configuracoes'])): ?>
            <div class="nubank-section" id="configSection">
                <h4 class="nubank-section-title">Configurações</h4>
                <div class="nubank-list">
                    <?php foreach ($menuConfig['configuracoes'] as $item): 
                        $isActive = ($currentPage === $item['page']);
                    ?>
                    <a href="<?php echo $item['url']; ?>" 
                       class="nubank-list-item <?php echo $isActive ? 'active' : ''; ?>"
                       data-search="<?php echo strtolower($item['label']); ?>">
                        <span><?php echo $item['label']; ?></span>
                        <iconify-icon icon="<?php echo $item['icon']; ?>"></iconify-icon>
                    </a>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>

            <!-- Ver Minha Loja -->
            <?php if (!empty($store['slug'] ?? '')): ?>
            <div class="nubank-section">
                <div class="nubank-list">
                    <a href="<?php echo get_store_url($store); ?>" 
                       target="_blank" 
                       class="nubank-list-item highlight"
                       data-search="ver minha loja visualizar">
                        <span>Ver Minha Loja</span>
                        <iconify-icon icon="solar:arrow-right-up-linear"></iconify-icon>
                    </a>
                </div>
            </div>
            <?php endif; ?>

            <!-- Seção do Usuário -->
            <div class="nubank-user-section">
                <div class="nubank-user-card">
                    <div class="nubank-user-avatar">
                        <?php echo strtoupper(substr($user['name'] ?? 'U', 0, 1)); ?>
                    </div>
                    <div class="nubank-user-info">
                        <div class="nubank-user-name"><?php echo htmlspecialchars($user['name'] ?? 'Usuário'); ?></div>
                        <div class="nubank-user-store"><?php echo htmlspecialchars($store['name'] ?? 'Minha Loja'); ?></div>
                    </div>
                </div>
                
                <a href="/logout.php" class="nubank-logout-btn">
                    <iconify-icon icon="solar:logout-2-bold"></iconify-icon>
                    <span>Sair da Conta</span>
                </a>
            </div>

        </div>
    </div>
</div>

<style>
/* ==========================================
   MOBILE BOTTOM NAVIGATION - Estilo App
   ========================================== */

/* Oculto em desktop, visível em mobile */
.mobile-bottom-nav {
    display: none;
}

@media (max-width: 768px) {
        .mobile-bottom-nav {
        transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        transform: translateY(0);
        display: block;
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        z-index: 1020;
        border-top: 1px solid var(--border);
        background: var(--bg-card);
        border-radius: 24px 24px 0 0;
        box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.1);
        padding-bottom: env(safe-area-inset-bottom, 0);
    }
    /* CLASSE MÁGICA: CSS Nativo Bootstrap + Classe auxiliar JS */
    body.modal-open .mobile-bottom-nav,
    .mobile-bottom-nav.force-hide {
        transform: translateY(120%) !important;
    }

    .mobile-nav-container {
        display: flex;
        justify-content: space-around;
        align-items: flex-end;
        padding: 8px 12px 12px;
        max-width: 100%;
    }

    .mobile-nav-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        text-decoration: none;
        color: var(--text-muted);
        padding: 8px 12px;
        min-width: 64px;
        position: relative;
        transition: all 0.2s ease;
        -webkit-tap-highlight-color: transparent;
    }

    .mobile-nav-item:active {
        transform: scale(0.95);
    }

    .mobile-nav-item .nav-icon-wrapper {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 48px;
        height: 48px;
        border-radius: 16px;
        background: transparent;
        transition: all 0.3s ease;
    }

    .mobile-nav-item .nav-icon-wrapper iconify-icon {
        font-size: 24px;
        transition: all 0.2s ease;
    }

    .mobile-nav-item .nav-label {
        font-size: 11px;
        font-weight: 500;
        margin-top: 4px;
        transition: color 0.2s ease;
    }

    /* Estado Ativo */
    .mobile-nav-item.active {
        color: var(--text-primary);
    }

    .mobile-nav-item.active .nav-icon-wrapper {
        background: var(--primary-2);
    }

    .mobile-nav-item.active .nav-icon-wrapper iconify-icon {
        color: var(--primary);
    }

    .mobile-nav-item.active .nav-label {
        color: var(--primary);
        font-weight: 600;
    }

    /* Indicador Ativo (barra superior) */
    .active-indicator {
        position: absolute;
        top: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 32px;
        height: 3px;
        background: var(--primary);
        border-radius: 0 0 4px 4px;
    }

    /* Botão de Destaque (FAB) - Início */
    .mobile-nav-item.highlight {
        margin-top: -20px;
    }

    .mobile-nav-item.highlight .fab-button {
        width: 56px;
        height: 56px;
        background: var(--primary);
        border-radius: 50%;
       /* box-shadow: var(--shadow-primary);*/
        margin-bottom: 4px;
    }

    .mobile-nav-item.highlight .fab-button iconify-icon {
        font-size: 28px;
        color: #ffffff;
    }

    .mobile-nav-item.highlight .nav-label {
        color: var(--primary);
        font-weight: 600;
    }

    .mobile-nav-item.highlight.active .fab-button {
        background: var(--primary);
        /*box-shadow: var(--shadow-primary);*/
    }

    .mobile-nav-item.highlight.active .nav-label {
        color: var(--primary);
    }

    /* Ajuste do conteúdo principal para não ficar atrás do menu */
    body {
        padding-bottom: 85px !important;
    }

    .dashboard-content,
    .main-content,
    main {
        padding-bottom: 100px !important;
    }
}

/* ==========================================
   MOBILE MENU OVERLAY (Bottom Sheet)
   ========================================== */
.mobile-menu-overlay {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    z-index: 10000;
    opacity: 0;
    transition: opacity 0.3s ease;
}

.mobile-menu-overlay.active {
    display: block;
    opacity: 1;
}

.mobile-menu-sheet {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background: var(--bg-card);
    border-radius: 24px 24px 0 0;
    transform: translateY(100%);
    transition: transform 0.3s ease;
}

.mobile-menu-overlay.active .mobile-menu-sheet {
    transform: translateY(0);
}

/* ==========================================
   NUBANK STYLE MENU
   ========================================== */

/* Sheet estilo Nubank */
.mobile-menu-sheet.nubank-style {
    background: var(--bg-card);
    border-radius: 24px 24px 0 0;
    padding: 0;
    max-height: 92vh;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}

/* Header Nubank */
.nubank-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px 20px 16px;
    border-bottom: none;
}

.nubank-header-spacer {
    width: 44px;
}

.nubank-title {
    font-size: 17px;
    font-weight: 600;
    color: var(--text-primary);
    margin: 0;
    text-align: center;
    flex: 1;
}

.nubank-close-btn {
    width: 44px;
    height: 44px;
    background: var(--bg-card-hover);
    border: none;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.2s ease;
}

.nubank-close-btn iconify-icon {
    font-size: 22px;
    color: var(--text-primary);
}

.nubank-close-btn:active {
    background: var(--bg-darker);
    transform: scale(0.95);
}

/* Campo de Busca Nubank */
.nubank-search {
    display: flex;
    align-items: center;
    gap: 12px;
    background: var(--bg-card-hover);
    border-radius: 50px;
    padding: 14px 20px;
    margin: 0 20px 20px;
}

.nubank-search iconify-icon {
    font-size: 20px;
    color: var(--text-muted);
    flex-shrink: 0;
}

.nubank-search input {
    border: none;
    background: transparent;
    outline: none;
    font-size: 16px;
    color: var(--text-primary);
    width: 100%;
}

.nubank-search input::placeholder {
    color: var(--text-muted);
}

/* Search Wrapper (para posicionamento do dropdown) */
.nubank-search-wrapper {
    position: relative;
    margin: 0 20px 20px;
}

.nubank-search-wrapper .nubank-search {
    margin: 0;
}

/* Dropdown de Resultados da Busca */
.search-results-dropdown {
    display: none;
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background: var(--bg-card);
    border: 1px solid var(--border);
    border-radius: 16px;
    box-shadow: var(--shadow-lg);
    max-height: 280px;
    overflow-y: auto;
    z-index: 100;
    margin-top: 8px;
    padding: 8px;
}

.search-results-dropdown.active {
    display: block;
}

.search-results-dropdown .search-result-item {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 14px 16px;
    border-radius: 12px;
    text-decoration: none;
    color: var(--text-primary);
    transition: all 0.2s ease;
}

.search-results-dropdown .search-result-item:active {
    background: var(--bg-card-hover);
}

.search-results-dropdown .search-result-item iconify-icon {
    font-size: 22px;
    color: var(--text-muted);
    flex-shrink: 0;
}

.search-results-dropdown .search-result-item span {
    font-size: 15px;
    font-weight: 500;
}

.search-results-dropdown .no-results {
    padding: 20px;
    text-align: center;
    color: var(--text-muted);
    font-size: 14px;
}

/* Conteúdo do Menu */
.nubank-menu-content {
    flex: 1;
    overflow-y: auto;
    padding: 0 20px 20px;
    padding-bottom: calc(20px + env(safe-area-inset-bottom, 0));
    -webkit-overflow-scrolling: touch;
}

/* Seções */
.nubank-section {
    margin-bottom: 24px;
}

.nubank-section-title {
    font-size: 18px;
    font-weight: 700;
    color: var(--text-primary);
    margin: 0 0 16px 0;
}

/* Grid de Cards (Acesso Rápido) */
.nubank-cards-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 12px;
}

.nubank-card {
    background: var(--bg-card-hover);
    border-radius: 20px;
    padding: 18px;
    text-decoration: none;
    color: var(--text-primary);
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    min-height: 110px;
    transition: all 0.2s ease;
    border: none;
}

.nubank-card iconify-icon {
    font-size: 28px;
    color: var(--text-primary);
}

.nubank-card span {
    font-size: 14px;
    font-weight: 500;
    margin-top: auto;
    line-height: 1.3;
}

.nubank-card:active {
    background: var(--bg-darker);
    transform: scale(0.98);
}

.nubank-card.active {
    background: var(--primary);
    color: #ffffff;
}

.nubank-card.active iconify-icon {
    color: #ffffff;
}

/* Lista de Itens */
.nubank-list {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.nubank-list-item {
    background: var(--bg-card-hover);
    border-radius: 20px;
    padding: 18px 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: var(--text-primary);
    text-decoration: none;
    transition: all 0.2s ease;
}

.nubank-list-item span {
    font-size: 15px;
    font-weight: 500;
}

.nubank-list-item iconify-icon {
    font-size: 22px;
    color: var(--text-muted);
}

.nubank-list-item:active {
    background: var(--bg-darker);
    transform: scale(0.98);
}

.nubank-list-item.active {
    background: var(--primary-2);
    color: var(--primary);
}

.nubank-list-item.active iconify-icon {
    color: var(--primary);
}

.nubank-list-item.highlight {
    background: linear-gradient(135deg, rgba(16, 185, 129, 0.15) 0%, rgba(5, 150, 105, 0.15) 100%);
    color: #059669;
}

.nubank-list-item.highlight iconify-icon {
    color: #059669;
}

/* Seção do Usuário */
.nubank-user-section {
    margin-top: 24px;
    padding-top: 20px;
    border-top: 1px solid var(--border);
}

.nubank-user-card {
    display: flex;
    align-items: center;
    gap: 14px;
    padding: 16px;
    background: var(--bg-card-hover);
    border-radius: 16px;
    margin-bottom: 12px;
}

.nubank-user-avatar {
    width: 50px;
    height: 50px;
    background: linear-gradient(135deg, #7C3AED 0%, #6D28D9 100%);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-weight: 700;
    font-size: 20px;
    flex-shrink: 0;
}

.nubank-user-info {
    flex: 1;
    min-width: 0;
}

.nubank-user-name {
    font-weight: 600;
    color: var(--text-primary);
    font-size: 16px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.nubank-user-store {
    font-size: 13px;
    color: var(--text-muted);
    margin-top: 2px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.nubank-logout-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    width: 100%;
    padding: 16px;
    background: var(--bg-card-hover);
    border-radius: 16px;
    color: #ef4444;
    text-decoration: none;
    font-size: 15px;
    font-weight: 600;
    transition: all 0.2s ease;
}

.nubank-logout-btn iconify-icon {
    font-size: 20px;
}

.nubank-logout-btn:active {
    background: #fee2e2;
    transform: scale(0.98);
}

/* Animação de itens ocultos pela busca */
.nubank-card.hidden,
.nubank-list-item.hidden,
.nubank-section.hidden {
    display: none;
}

/* Animação de entrada */
@keyframes slideUp {
    from {
        transform: translateY(100%);
        opacity: 0;
    }
    to {
        transform: translateY(0);
        opacity: 1;
    }
}

@media (max-width: 768px) {
    .mobile-bottom-nav {
        animation: slideUp 0.3s ease;
    }
}
</style>

<script>
// Scripts de Menu Mobile e Auto-Hide movidos para dashboard-utils.js
</script>
