<?php
mb_internal_encoding('UTF-8');

$configPath = dirname(__DIR__) . '/config/db.php';
if (file_exists($configPath)) {
    require_once($configPath);
}
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$usuarioNome = '';
if (isset($_SESSION['usuario']['nome'])) {
    $usuarioNome = ucwords(strtolower($_SESSION['usuario']['nome']));
}

// 🔹 Empresa logada
$empresaNome = $_SESSION['empresa']['nome'] ?? '';
$empresaApelido = '';

try {
    if (!empty($_SESSION['empresa']['id']) && isset($pdo)) {
        $stmt = $pdo->prepare("SELECT dsapelido FROM back.empresa WHERE cdempresa = :id");
        $stmt->execute([':id' => $_SESSION['empresa']['id']]);
        $empresa = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($empresa) {
            $empresaApelido = $empresa['dsapelido'];
        }
    }
} catch (Exception $e) {
    $empresaApelido = '';
}

// 🔹 Carrega empresas do usuário (para modal de troca no mobile)
$empresas = [];
try {
    if (isset($pdo) && isset($_SESSION['usuario']['id'])) {
        $usuarioId = $_SESSION['usuario']['id'];
        $stmt = $pdo->prepare("
            SELECT e.cdempresa, e.dsempresa, e.dsapelido
            FROM back.pessoaempresa pe
            JOIN back.empresa e ON e.cdempresa = pe.cdempresa
            WHERE pe.cdpessoa = :pessoa
            ORDER BY e.dsempresa
        ");
        $stmt->execute([':pessoa' => $usuarioId]);
        $empresas = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (Exception $e) {
    $empresas = [];
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<title><?= $titulo ?? 'Helm' ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="<?php echo $basePath; ?>/img/favicon.ico" type="image/x-icon">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
<link href="<?php echo $basePath; ?>/css/style.css" rel="stylesheet">
<link href="<?php echo $basePath; ?>/css/theme-clean.css" rel="stylesheet">

<script>
// 🔧 Variable global com o path base da aplicação
const APP_BASE_PATH = '<?php echo htmlspecialchars($basePath, ENT_QUOTES); ?>';
</script>

<style>
:root {
    --primary: #2563eb;
    --primary-dark: #1e40af;
    --secondary: #64748b;
    --success: #10b981;
    --danger: #ef4444;
    --warning: #f59e0b;
    --bg-primary: #f8fafc;
    --bg-secondary: #ffffff;
    --text-primary: #1e293b;
    --text-secondary: #64748b;
    --border: #e2e8f0;
}

/* ===== LOADER GLOBAL ===== */
.global-loader {
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, 0.55);
    backdrop-filter: blur(4px);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 3000;
}
.global-loader .loader-box {
    background: var(--bg-secondary);
    border: 1px solid var(--border);
    border-radius: 8px;
    padding: 18px 22px;
    display: flex;
    align-items: center;
    gap: 12px;
    color: var(--text-primary);
    box-shadow: 0 12px 30px rgba(0, 0, 0, 0.12);
}
.global-loader img {
    width: 44px;
    height: 44px;
}
.global-loader .spinner-border {
    width: 1.9rem;
    height: 1.9rem;
    border-width: 0.18rem;
    color: var(--primary);
}

/* ===== BASE ===== */
body {
    background: var(--bg-primary);
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', sans-serif;
    color: var(--text-primary);
    overflow-x: hidden;
}
.d-flex { display: flex; }

/* TOPBAR MOBILE (sem sidebar) */
#mobileTopbar {
    background: var(--bg-secondary);
    border-bottom: 1px solid var(--border);
    color: var(--text-primary);
    padding: 12px 16px;
    display: none;
    align-items: center;
    justify-content: space-between;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1100;
}

/* ===== MODAL STYLES ===== */
.modal-content {
    background: var(--bg-secondary);
    border: 1px solid var(--border);
    border-radius: 8px;
}
.modal-header {
    border-bottom: 1px solid var(--border);
    background: var(--bg-primary);
    color: var(--text-primary);
    font-weight: 600;
}
.modal-body {
    color: var(--text-primary);
    padding: 20px;
}
.empresa-list {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 12px;
    max-height: 60vh;
    overflow-y: auto;
}
.empresa-list::-webkit-scrollbar {
    width: 6px;
}
.empresa-list::-webkit-scrollbar-track {
    background: transparent;
}
.empresa-list::-webkit-scrollbar-thumb {
    background: rgba(0, 174, 239, 0.4);
    border-radius: 3px;
}
.empresa-list::-webkit-scrollbar-thumb:hover {
    background: rgba(0, 174, 239, 0.6);
}
.empresa-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-height: 48px;
    padding: 12px 16px;
    background: var(--bg-primary);
    border: 1px solid var(--border);
    color: var(--text-primary);
    text-decoration: none;
    border-radius: 6px;
    font-weight: 500;
    font-size: 1.05rem;
    transition: all 0.3s ease;
    cursor: pointer;
    text-align: center;
    word-break: break-word;
}
.empresa-btn:hover {
    background: var(--bg-secondary);
    border-color: var(--primary);
    color: var(--primary);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(37, 99, 235, 0.15);
}
.empresa-btn.active {
    background: rgba(37, 99, 235, 0.1);
    border-color: var(--primary);
    color: var(--primary);
    box-shadow: 0 0 12px rgba(37, 99, 235, 0.25);
}
@media (max-width: 576px) {
    .empresa-list {
        grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
        max-height: 72vh;
        gap: 10px;
    }
    .empresa-btn {
        font-size: 1.08rem;
        min-height: 44px;
    }
}

/* ===== SIDEBAR ===== */
.sidebar {
    width: 230px;
    height: 100vh;
    background: var(--bg-secondary);
    border-right: 1px solid var(--border);
    display: flex;
    flex-direction: column;
    transition: width 0.3s ease;
    box-shadow: none;
    position: fixed;
    left: 0;
    top: 0;
    overflow: hidden;
}
.sidebar.collapsed { width: 70px; }

/* Sidebar menu area with scroll */
.sidebar-menu {
    flex: 1;
    overflow-y: auto;
    overflow-x: hidden;
    padding-right: 4px;
    min-height: 0;
}

.sidebar-menu::-webkit-scrollbar {
    width: 6px;
}

.sidebar-menu::-webkit-scrollbar-track {
    background: transparent;
}

.sidebar-menu::-webkit-scrollbar-thumb {
    background: rgba(37, 99, 235, 0.3);
    border-radius: 3px;
}

.sidebar-menu::-webkit-scrollbar-thumb:hover {
    background: rgba(37, 99, 235, 0.5);
}

/* Sidebar footer with fixed logout */
.sidebar-footer {
    flex-shrink: 0;
    text-align: center;
    padding: 12px 0;
    border-top: 1px solid var(--border);
    background: var(--bg-primary);
    backdrop-filter: none;
}

/* ===== CABEÇALHO ===== */
.sidebar-header {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 25px 0 15px;
    border-bottom: 1px solid var(--border);
    flex-shrink: 0;
}
.sidebar-header a.logo-link {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 60px;
    height: 60px;
    border-radius: 50%;
    background: rgba(37, 99, 235, 0.08);
    transition: all 0.3s ease;
}
.sidebar-header a.logo-link:hover {
    box-shadow: 0 0 18px rgba(37, 99, 235, 0.25), inset 0 0 12px rgba(37, 99, 235, 0.1);
    transform: scale(1.1);
}
.sidebar-header img {
    width: 40px;
    height: auto;
    pointer-events: none;
}
.sidebar-header h5 {
    color: var(--primary);
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif;
    font-size: 1.1rem;
    font-weight: 700;
    margin-top: 8px;
    letter-spacing: 0px;
}

/* === Nome / Apelido da empresa === */
.empresa-nome, .empresa-apelido {
    color: var(--text-secondary);
    font-size: 0.9rem;
    margin-top: 4px;
    font-weight: 500;
    text-align: center;
}
.sidebar.collapsed .empresa-nome { display: none; }

/* Toggle (desktop only) */
#toggleSidebar {
    position: absolute;
    right: 15px;
    top: 18px;
    color: var(--text-secondary);
    font-size: 1.1rem;
    cursor: pointer;
    transition: color 0.3s;
}
#toggleSidebar:hover { color: var(--primary); }

/* ===== LINKS ===== */
.sidebar a {
    display: flex;
    align-items: center;
    color: var(--text-secondary);
    padding: 10px 18px;
    text-decoration: none;
    border-radius: 6px;
    transition: all 0.25s ease;
}
.sidebar a:hover {
    background: var(--bg-primary);
    color: var(--primary);
    box-shadow: none;
    transform: none;
}
.sidebar a i {
    width: 24px;
    text-align: center;
    font-size: 1.2rem;
}
.sidebar.collapsed a {
    justify-content: center;
    padding: 12px 0;
}
.sidebar.collapsed .txt { display: none; }

/* ===== SUBMENUS ===== */
.sidebar .collapse {
    padding-left: 12px;
    transition: all 0.3s ease;
}
.sidebar.collapsed .collapse {
    position: absolute;
    left: 70px;
    top: auto;
    width: 230px;
    background: rgba(13,27,42,0.95);
    border-radius: 12px;
    box-shadow: 0 4px 25px rgba(0,0,0,0.6);
    backdrop-filter: blur(8px);
    z-index: 2000;
    opacity: 0;
    transform: translateX(15px);
    pointer-events: none;
    transition: opacity 0.25s ease, transform 0.25s ease;
}
.sidebar.collapsed .collapse.show {
    opacity: 1;
    transform: translateX(0);
    pointer-events: auto;
}

/* ===== USUÁRIO E LOGOUT ===== */
.user-info {
    text-align: center;
    padding: 10px 0;
    color: var(--text-primary);
}
.user-info .welcome {
    color: var(--text-secondary);
    font-size: 0.85rem;
}
.user-info .username {
    font-weight: 600;
    color: var(--text-primary);
}
.user-info .welcome::after { content: " 👋"; }
.sidebar.collapsed .user-info { display: none; }

.btn-logout {
    text-align: left;
    padding: 10px 15px;
    color: var(--text-secondary);
    transition: all 0.3s;
}
.btn-logout:hover {
    color: var(--danger);
    background: var(--bg-primary);
}
.sidebar.collapsed .btn-logout {
    text-align: center;
}
.sidebar.collapsed .btn-logout .txt { display: none; }

/* ===== CONTEÚDO ===== */
#content {
    flex-grow: 1;
    background-color: var(--bg-primary);
    color: var(--text-primary);
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
    padding: 25px;
    min-height: 100vh;
    width: 100%;
}

/* ===== MOBILE ===== */
@media (max-width: 768px) {
    #mobileTopbar { display: flex !important; }
    .sidebar {
        display: none !important;
    }
    .d-flex {
        margin-left: 0 !important;
    }
    .sidebar-header {
        padding-top: 15px;
    }
    .sidebar-header h5 {
        font-size: 0.8rem;
        margin-top: 6px;
    }
    #toggleSidebar { display: none !important; }
    #content {
        margin-left: 0 !important;
        border-radius: 0;
        padding-top: 60px;
    }
    .empresa-nome { display: none !important; }
    .empresa-apelido { display: block !important; }
}

/* ===== POPOVER STYLES (Improved Readability) ===== */
.popover {
    background-color: var(--bg-secondary) !important;
    border: 1px solid var(--border) !important;
    border-radius: 8px !important;
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12) !important;
}

.popover-header {
    background-color: var(--bg-primary) !important;
    border-bottom: 1px solid var(--border) !important;
    color: var(--text-primary) !important;
    font-weight: 600 !important;
    font-size: 14px !important;
    padding: 10px 12px !important;
}

.popover-body {
    color: var(--text-primary) !important;
    font-size: 13px !important;
    padding: 10px 12px !important;
    font-weight: 500 !important;
    line-height: 1.5;
}
</style>
</head>
<body>
<div id="globalLoader" class="global-loader d-none">
    <div class="loader-box">
        <img src="<?php echo $basePath; ?>/img/helm-icon.png" alt="Carregando">
        <div class="spinner-border" role="status" aria-hidden="true"></div>
        <span>Carregando...</span>
    </div>
</div>
<div id="mobileTopbar" class="d-md-none">
    <div class="d-flex flex-column">
        <span class="small">Usuário: <strong><?= htmlspecialchars($usuarioNome ?: 'N/D') ?></strong></span>
        <span class="small">Empresa: <strong><?= htmlspecialchars($empresaApelido ?: $empresaNome) ?></strong></span>
    </div>
    <div class="d-flex gap-2">
        <button class="btn btn-sm btn-outline-primary troca-empresa-btn-mobile" data-bs-toggle="modal" data-bs-target="#modalTrocaEmpresa">
            <i class="bi bi-arrow-left-right"></i>
        </button>
        <a href="?m=logout" class="btn btn-sm btn-outline-danger">
            <i class="bi bi-box-arrow-right"></i>
        </a>
    </div>
</div>

<div class="d-flex" style="margin-left: 230px;">
    <!-- SIDEBAR -->
    <nav id="sidebar" class="sidebar d-flex flex-column">
        <div class="sidebar-header">
            <a href="?m=home" class="logo-link">
                <img src="<?php echo $basePath; ?>/img/helm-icon.png" alt="Helm Logo">
            </a>
            <h5>Helm</h5>

            <!-- Nome completo da empresa (desktop) -->
            <p class="empresa-nome d-none d-md-block">
                <a href="/orcamento/public/troca.php" class="text-decoration-none fw-semibold" style="color: var(--text-secondary);">
                    <?= htmlspecialchars($empresaNome) ?>
                    <i class="bi bi-arrow-repeat ms-1"></i>
                </a>
            </p>

            <!-- Apelido (mobile e recolhido) -->
            <p class="empresa-apelido d-md-none">
                <a href="#" class="text-decoration-none fw-semibold troca-empresa-mobile" style="color: var(--text-secondary);">
                    <i class="bi bi-arrow-left-right me-1"></i>
                    <?= htmlspecialchars($empresaApelido ?: $empresaNome) ?>
                </a>
            </p>

            <div id="toggleSidebar">☰</div>
        </div>

        <!-- ======= MENUS (SCROLLABLE) ======= -->
        <div class="sidebar-menu">
            <ul class="list-unstyled ps-2 mt-3">
                <li><a href="?m=home"><i class="bi bi-house"></i> <span class="txt">Início</span></a></li>

                <li>
                    <a class="dropdown-toggle" href="#cadastros"><i class="bi bi-folder"></i> <span class="txt">Cadastros</span></a>
                    <ul class="collapse list-unstyled" id="cadastros">
                        <li><a href="?m=empresas"><i class="bi bi-building"></i> Empresas</a></li>
                        <li><a href="?m=pessoas"><i class="bi bi-people"></i> Pessoas</a></li>
                        <li><a href="?m=moedas"><i class="bi bi-currency-exchange"></i> Moedas</a></li>
                        <li><a href="?m=cotacao"><i class="bi bi-cash-coin"></i> Cotação</a></li>
                        <li><a href="?m=exercicios"><i class="bi bi-calendar3"></i> Exercício</a></li>
                        <li><a href="?m=plano_contabil"><i class="bi bi-diagram-3"></i> Plano de Contas</a></li>
						<li><a href="?m=centro_custo"><i class="bi bi-journal-text"></i> Centro de Custo</a></li>
						<li><a href="?m=variaveis"><i class="bi bi-calculator"></i> Variáveis</a></li>
                        <li><a href="?m=calendario"><i class="bi bi-calendar-event"></i> Calendário</a></li>
                    </ul>
                </li>

                <li>
                    <a class="dropdown-toggle" href="#orcamento"><i class="bi bi-pie-chart"></i> <span class="txt">Orçamento</span></a>
                    <ul class="collapse list-unstyled" id="orcamento">
                        <li><a href="?m=orcamento"><i class="bi bi-graph-up"></i> Planejamento</a></li>
                        <li><a href="?m=realizado"><i class="bi bi-graph-down"></i> Realizado</a></li>
                    </ul>
                </li>

                <li>
                    <a class="dropdown-toggle" href="#metas"><i class="bi bi-bullseye"></i> <span class="txt">Metas</span></a>
                    <ul class="collapse list-unstyled" id="metas">
                        <li><a href="?m=metas_planejamento"><i class="bi bi-calendar2-check"></i> Planejamento</a></li>
                        <li><a href="?m=metas_acompanhamento"><i class="bi bi-trophy"></i> Acompanhamento</a></li>
                    </ul>
                </li>

                <li>
                    <a class="dropdown-toggle" href="#relatorios"><i class="bi bi-bar-chart-line"></i> <span class="txt">Relatórios</span></a>
                    <ul class="collapse list-unstyled" id="relatorios">
                        <li><a href="?m=indicadores"><i class="bi bi-clipboard-data"></i> Indicadores</a></li>
                        <li><a href="?m=previsto_realizado"><i class="bi bi-file-earmark-bar-graph"></i> Previsto x Realizado</a></li>
                    </ul>
                </li>

                <li>
                    <a class="dropdown-toggle" href="#config"><i class="bi bi-gear"></i> <span class="txt">Configurações</span></a>
                    <ul class="collapse list-unstyled" id="config">
                        <li><a href="?m=parametros"><i class="bi bi-sliders"></i> Parâmetros</a></li>
                        <li><a href="?m=integracoes"><i class="bi bi-database-gear"></i> Integrações</a></li>
                        <li><a href="?m=permissoes"><i class="bi bi-shield-lock"></i> Permissões</a></li>
                    </ul>
                </li>
            </ul>
        </div>

        <!-- ======= FOOTER (FIXED LOGOUT) ======= -->
        <div class="sidebar-footer">
            <?php if ($usuarioNome): ?>
            <div class="user-info mb-2">
                <div class="welcome">Bem-vindo,</div>
                <div class="username"><?= htmlspecialchars($usuarioNome) ?></div>
            </div>
            <?php endif; ?>
            <a href="?m=logout" class="btn-logout d-block">
                <i class="bi bi-box-arrow-right fs-5"></i> <span class="txt">Sair</span>
            </a>
        </div>
    </nav>

    <!-- CONTEÚDO -->
    <div class="flex-grow-1" id="content">
        <?= $conteudo ?? '<h3>Bem-vindo ao Helm</h3>' ?>
    </div>
</div>

<!-- MODAL TROCA EMPRESA (MOBILE) -->
<div class="modal fade" id="modalTrocaEmpresa" tabindex="-1" aria-labelledby="modalTrocaEmpresaLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTrocaEmpresaLabel">Selecionar Empresa</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="empresa-list" id="listaEmpresas"></div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', () => {
    const loader = document.getElementById('globalLoader');
    const showLoader = () => loader && loader.classList.remove('d-none');
    const hideLoader = () => loader && loader.classList.add('d-none');

    const sidebar = document.getElementById('sidebar');
    const toggleSidebar = document.getElementById('toggleSidebar');
    const isMobile = () => window.innerWidth <= 768;

    if (isMobile()) sidebar.classList.add('collapsed');

    toggleSidebar.addEventListener('click', () => {
        if (!isMobile()) sidebar.classList.toggle('collapsed');
    });

    document.querySelectorAll('.sidebar .dropdown-toggle').forEach(btn => {
        btn.addEventListener('click', e => {
            e.preventDefault();
            const target = document.querySelector(btn.getAttribute('href'));
            if (!target.classList.contains('show')) {
                document.querySelectorAll('.sidebar .collapse.show').forEach(open => open.classList.remove('show'));
                target.classList.add('show');
            } else {
                target.classList.remove('show');
            }
        });
    });

    // Fecha submenus abertos ao clicar fora da sidebar (evita sobreposição no conteúdo)
    document.addEventListener('click', (e) => {
        if (isMobile()) return;
        if (!sidebar.contains(e.target)) {
            document.querySelectorAll('.sidebar .collapse.show').forEach(open => open.classList.remove('show'));
        }
    });

    window.addEventListener('resize', () => {
        if (isMobile()) sidebar.classList.add('collapsed');
        else sidebar.classList.remove('collapsed');
    });

    // Loader em navegações
    window.addEventListener('beforeunload', () => {
        showLoader();
    });

    document.querySelectorAll('a[href]').forEach(link => {
        const href = link.getAttribute('href') || '';
        const toggle = link.getAttribute('data-bs-toggle');
        if (href.startsWith('#') || toggle) return;
        link.addEventListener('click', () => {
            showLoader();
        });
    });

    // ======= TROCA EMPRESA MOBILE =======
    const trocaEmpresaLink = document.querySelector('.troca-empresa-mobile');
    const trocaEmpresaBtn = document.querySelector('.troca-empresa-btn-mobile');
    const modalTrocaEmpresa = document.getElementById('modalTrocaEmpresa');
    const listaEmpresas = document.getElementById('listaEmpresas');
    
    // Pega as empresas do PHP (mesmo array do troca.php)
    const empresas = <?= json_encode($empresas ?? [], JSON_UNESCAPED_UNICODE) ?>;
    const modal = new bootstrap.Modal(modalTrocaEmpresa);

    function abrirModalTroca() {
        // Limpa lista anterior
        listaEmpresas.innerHTML = '';
        
        // Preenche a lista de empresas (mesma lógica do troca.php)
        if (empresas && empresas.length > 0) {
            empresas.forEach(emp => {
                const btn = document.createElement('button');
                btn.type = 'button';
                btn.className = 'empresa-btn';
                btn.textContent = emp.dsempresa;
                btn.onclick = async (e) => {
                    e.preventDefault();
                    // Submete o formulário (mesma lógica do troca.php)
                    const form = document.createElement('form');
                    form.method = 'POST';
                    form.action = '/orcamento/public/troca.php';
                    form.innerHTML = `
                        <input type="hidden" name="empresa_id" value="${emp.cdempresa}">
                        <input type="hidden" name="empresa_nome" value="${emp.dsempresa}">
                    `;
                    document.body.appendChild(form);
                    form.submit();
                };
                listaEmpresas.appendChild(btn);
            });
        } else {
            listaEmpresas.innerHTML = '<p class="text-center text-muted">Nenhuma empresa disponível</p>';
        }
        
        // Mostra o modal
        modal.show();
    }

    if (trocaEmpresaLink) {
        trocaEmpresaLink.addEventListener('click', (e) => {
            e.preventDefault();
            abrirModalTroca();
        });
    }

    if (trocaEmpresaBtn) {
        trocaEmpresaBtn.addEventListener('click', abrirModalTroca);
    }
});
</script>
</body>
</html>
