<?php
/**
 * Sidebar Dinamico - BarberFlow SaaS
 * Renderiza menu baseado no business_type da loja
 */

require_once __DIR__ . '/business-config.php';
require_once __DIR__ . '/landing-functions.php';

// Carregar configurações de logo
$pdoLogo = getDB();
$dashboardLogo = getLandingConfig($pdoLogo, 'header_logo', '');
$dashboardLogoType = getLandingConfig($pdoLogo, 'header_logo_type', 'text');
$dashboardLogoText = getLandingConfig($pdoLogo, 'header_logo_text', 'MontaLoja');
$dashboardLogoDark = getLandingConfig($pdoLogo, 'header_logo_dark', '');

// Determinar pagina atual
$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", "clientes", etc
}

// Fix para WhatsApp (detectar pasta)
if (strpos($scriptPath, '/pages/dashboard/whatsapp/') !== false) {
    $currentPage = 'whatsapp';
}

// Buscar dados do usuario se nao existirem
$pdo = getDB();
$userId = $_SESSION['user_id'] ?? null;
$storeId = $_SESSION['store_id'] ?? null;

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

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

$userName = $user['name'] ?? 'Usuario';
$userRole = $user['role'] ?? 'owner';
$storeName = $store['name'] ?? 'Minha Loja';
$storeSlug = $store['slug'] ?? '';
$businessType = $store['business_type'] ?? 'service';

// Salvar na sessao para uso em outras paginas
$_SESSION['business_type'] = $businessType;

// Obter configuracao do menu baseado no tipo de negocio
$menuConfig = getMenuItems($businessType);
$primaryAction = getPrimaryAction($businessType);
$businessConfig = getBusinessConfig($businessType);

$roleLabels = [
    'owner' => 'Proprietario',
    'admin' => 'Administrador',
    'barber' => 'Barbeiro',
    'employee' => 'Funcionario',
    'manager' => 'Gerente'
];
$roleLabel = $roleLabels[$userRole] ?? 'Usuario';

$sectionLabels = [
    'principal' => 'Menu Principal',
    'financeiro' => 'Financeiro',
    'configuracoes' => 'Configuracoes'
];
?>
<!-- Sidebar -->
<aside class="sidebar">
    <div class="sidebar-header">
        <a href="/dashboard.php" class="sidebar-logo">
            <?php if ($dashboardLogoType === 'image' && !empty($dashboardLogo)): ?>
                <!-- Logo para modo claro -->
                <img src="<?php echo htmlspecialchars($dashboardLogo); ?>" 
                     alt="<?php echo htmlspecialchars($dashboardLogoText); ?>" 
                     class="logo-light"
                     style="max-height: 32px; width: auto; object-fit: contain; margin-right: 0.5rem;">
                <?php if (!empty($dashboardLogoDark)): ?>
                <!-- Logo para modo escuro -->
                <img src="<?php echo htmlspecialchars($dashboardLogoDark); ?>" 
                     alt="<?php echo htmlspecialchars($dashboardLogoText); ?>" 
                     class="logo-dark"
                     style="max-height: 32px; width: auto; object-fit: contain; margin-right: 0.5rem;">
                <?php endif; ?>
            <?php else: ?>
                <iconify-icon icon="<?php echo $businessConfig['icon']; ?>"></iconify-icon>
                <?php echo htmlspecialchars($dashboardLogoText); ?>
            <?php endif; ?>
        </a>
        <span class="business-badge"><?php echo $businessConfig['label']; ?></span>
    </div>

    <!-- Botao de Acao Principal -->
    <div class="sidebar-action">
        <a href="<?php echo $primaryAction['url']; ?>" class="btn-primary-action">
            <iconify-icon icon="<?php echo $primaryAction['icon']; ?>"></iconify-icon>
            <?php echo $primaryAction['label']; ?>
        </a>
    </div>

    <nav class="sidebar-nav">
        <?php foreach ($menuConfig as $sectionKey => $items): ?>
        <div class="nav-section">
            <div class="nav-section-title"><?php echo $sectionLabels[$sectionKey] ?? ucfirst($sectionKey); ?></div>
            <?php foreach ($items as $item): ?>
            <a href="<?php echo $item['url']; ?>" class="nav-item <?php echo $currentPage === $item['page'] ? 'active' : ''; ?>">
                <iconify-icon icon="<?php echo $item['icon']; ?>"></iconify-icon>
                <?php echo $item['label']; ?>
            </a>
            <?php endforeach; ?>
        </div>
        <?php endforeach; ?>
    </nav>

    <div class="sidebar-footer">
        <?php if (!empty($storeSlug)): ?>
        <a href="<?php echo get_store_url($store ?? []); ?>" target="_blank" class="store-preview-link">
            <iconify-icon icon="solar:eye-bold"></iconify-icon>
            <span>Ver Loja</span>
            <iconify-icon icon="solar:arrow-right-up-linear"></iconify-icon>
        </a>
        <?php endif; ?>

        <div class="user-menu">
            <div class="user-avatar"><?php echo strtoupper(substr($userName, 0, 1)); ?></div>
            <div class="user-info">
                <div class="user-name"><?php echo htmlspecialchars($userName); ?></div>
                <div class="user-role"><?php echo $roleLabel; ?></div>
            </div>
            <a href="/logout.php" title="Sair" class="logout-btn">
                <iconify-icon icon="solar:logout-2-bold"></iconify-icon>
            </a>
        </div>
    </div>
</aside>

<!-- Mobile Menu Toggle Button -->
<button class="mobile-menu-toggle" id="mobileMenuToggle" aria-label="Abrir menu">
    <iconify-icon icon="solar:hamburger-menu-bold"></iconify-icon>
</button>

<!-- Sidebar Overlay -->
<div class="sidebar-overlay" id="sidebarOverlay"></div>

<script>
// Mobile Menu Toggle
(function() {
    const mobileMenuToggle = document.getElementById('mobileMenuToggle');
    const sidebar = document.querySelector('.sidebar');
    const sidebarOverlay = document.getElementById('sidebarOverlay');

    if (mobileMenuToggle && sidebar) {
        mobileMenuToggle.addEventListener('click', function() {
            sidebar.classList.toggle('open');
            sidebarOverlay.classList.toggle('active');
            // Trocar ícone
            const icon = mobileMenuToggle.querySelector('iconify-icon');
            if (sidebar.classList.contains('open')) {
                icon.setAttribute('icon', 'solar:close-circle-bold');
            } else {
                icon.setAttribute('icon', 'solar:hamburger-menu-bold');
            }
        });
    }

    if (sidebarOverlay) {
        sidebarOverlay.addEventListener('click', function() {
            sidebar.classList.remove('open');
            sidebarOverlay.classList.remove('active');
            const icon = mobileMenuToggle.querySelector('iconify-icon');
            icon.setAttribute('icon', 'solar:hamburger-menu-bold');
        });
    }

    // Fechar sidebar ao clicar em item do menu (mobile)
    const navItems = document.querySelectorAll('.sidebar .nav-item');
    navItems.forEach(function(item) {
        item.addEventListener('click', function() {
            if (window.innerWidth <= 1024) {
                sidebar.classList.remove('open');
                sidebarOverlay.classList.remove('active');
                const icon = mobileMenuToggle.querySelector('iconify-icon');
                icon.setAttribute('icon', 'solar:hamburger-menu-bold');
            }
        });
    });
})();
</script>

<style>
/* Sidebar footer fixo */
.sidebar-footer {
    margin-top: auto;
    border-top: 1px solid var(--border);
    padding: 0.75rem;
}
</style>
