<?php
include 'verifica_login.php';
requer_admin();
include 'conexao.php';
$conn = conectar_banco();

// Buscar nome da aplicação e empresa da tabela config
$nome_aplicacao = '';
$empresa = '';
$sql_config = "SELECT nomedaaplicacao, empresa FROM config LIMIT 1";
$res_config = $conn->query($sql_config);
if ($res_config && $res_config->num_rows > 0) {
    $row_config = $res_config->fetch_assoc();
    $nome_aplicacao = $row_config['nomedaaplicacao'];
    $empresa = $row_config['empresa'];
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tela Principal - Administrador</title>
    <style>
        * { box-sizing: border-box; }
        body { font-family: 'Segoe UI', Arial, sans-serif; background: #f0f2f5; margin: 0; color: #1b1f24; }

        .app-layout { display: flex; min-height: 100vh; }

        .sidebar {
            width: 300px;
            background: linear-gradient(180deg, #0f2747 0%, #123b67 100%);
            color: #fff;
            font-size: 91%;
            padding: 18px 14px;
            overflow-y: auto;
            transition: width 0.25s ease, transform 0.25s ease;
            position: sticky;
            top: 0;
            height: 100vh;
        }

        .sidebar-header { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 14px; }
        .sidebar-title { font-weight: 700; font-size: 0.74rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

        .sidebar-info {
            background: rgba(255,255,255,0.1);
            border: 1px solid rgba(255,255,255,0.2);
            border-radius: 10px;
            padding: 10px;
            margin-bottom: 12px;
        }
        .sidebar-user { color: #e9f2ff; font-size: 0.57rem; margin-top: 6px; }

        .toggle-btn {
            border: 0;
            border-radius: 8px;
            background: rgba(255,255,255,0.16);
            color: #fff;
            width: 34px;
            height: 34px;
            cursor: pointer;
            font-size: 1rem;
        }

        .search-wrap { margin-bottom: 14px; }
        .search-input {
            width: 100%;
            padding: 10px 12px;
            border-radius: 8px;
            border: 1px solid rgba(255,255,255,0.25);
            background: rgba(255,255,255,0.12);
            color: #fff;
            outline: none;
        }
        .search-input::placeholder { color: rgba(255,255,255,0.75); }

        .menu-section { margin: 16px 0; }
        .menu-section h3 {
            margin: 0 0 8px 0;
            font-size: 0.57rem;
            text-transform: uppercase;
            letter-spacing: 0.06em;
            color: #b7d8ff;
            cursor: pointer;
            display: flex;
            justify-content: space-between;
            align-items: center;
            user-select: none;
        }
        .menu-section h3::after { content: '▾'; font-size: 0.62rem; transition: transform 0.2s ease; }
        .menu-section.collapsed h3::after { transform: rotate(-90deg); }
        .menu-section.collapsed .menu-list { display: none; }

        .menu-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 6px; }
        .menu-link {
            display: flex;
            align-items: center;
            gap: 10px;
            text-decoration: none;
            color: #fff;
            border-radius: 8px;
            padding: 10px 10px;
            transition: background 0.2s ease;
        }
        .menu-link:hover { background: rgba(255,255,255,0.14); }
        .menu-link.active { background: rgba(255,255,255,0.24); }
        .menu-emoji { min-width: 20px; text-align: center; }
        .menu-text { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

        .main-content {
            flex: 1;
            padding: 0;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            position: relative;
        }
        .mobile-toggle { display: none; }
        .mobile-fab {
            position: absolute;
            top: 10px;
            left: 10px;
            z-index: 1001;
        }

        .card { background: #fff; padding: 20px; border-radius: 10px; box-shadow: 0 4px 6px rgba(0,0,0,0.08); margin-bottom: 12px; }
        .sidebar-logout {
            display: flex;
            align-items: center;
            gap: 10px;
            text-decoration: none;
            color: #fff;
            border-radius: 8px;
            padding: 10px 10px;
            margin-top: 6px;
            background: rgba(211,47,47,0.8);
            transition: background 0.2s ease;
        }
        .sidebar-logout:hover { background: rgba(211,47,47,1); }

        .workspace-card {
            padding: 0;
            overflow: hidden;
            flex: 1;
            min-height: 0;
            margin: 0 6px 6px;
        }
        .tabs-bar {
            display: flex;
            gap: 6px;
            padding: 10px;
            background: #eef2f7;
            border-bottom: 1px solid #d9e0ea;
            overflow-x: auto;
        }
        .tab-item {
            display: inline-flex;
            align-items: center;
            border: 1px solid #cfd8e3;
            border-radius: 8px;
            background: #fff;
            min-width: 170px;
            max-width: 260px;
        }
        .tab-item.active { border-color: #125ea6; box-shadow: 0 0 0 1px #125ea6 inset; }
        .tab-button {
            border: 0;
            background: transparent;
            padding: 8px 10px;
            cursor: pointer;
            color: #16426a;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            flex: 1;
            text-align: left;
        }
        .tab-close {
            border: 0;
            border-left: 1px solid #e0e7f0;
            background: transparent;
            color: #7a8794;
            width: 30px;
            height: 100%;
            cursor: pointer;
            font-size: 1rem;
        }
        .tab-close:hover { background: #f5f7fb; color: #d32f2f; }
        .tab-content { position: relative; height: 100%; min-height: 0; background: #fff; }
        .tab-pane {
            position: absolute;
            inset: 0;
            width: 100%;
            height: 100%;
            border: 0;
            display: none;
            background: #fff;
        }
        .tab-pane.active { display: block; }
        .empty-state {
            position: absolute;
            inset: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #6c7a88;
            font-weight: 500;
            padding: 20px;
            text-align: center;
        }

        .app-layout.sidebar-collapsed .sidebar { width: 78px; }
        .app-layout.sidebar-collapsed .sidebar-title,
        .app-layout.sidebar-collapsed .sidebar-info,
        .app-layout.sidebar-collapsed .search-wrap,
        .app-layout.sidebar-collapsed .menu-section h3,
        .app-layout.sidebar-collapsed .menu-text { display: none; }
        .app-layout.sidebar-collapsed .menu-link { justify-content: center; }
        .app-layout.sidebar-collapsed .sidebar-logout { justify-content: center; }
        .app-layout.sidebar-collapsed .sidebar-logout .menu-text { display: none; }

        @media (max-width: 900px) {
            .sidebar {
                position: fixed;
                left: 0;
                transform: translateX(-100%);
                z-index: 1000;
                width: 280px;
            }
            .mobile-toggle { display: inline-flex; }
            .app-layout.sidebar-open .sidebar { transform: translateX(0); }
            .main-content { padding: 0; width: 100%; min-height: 100vh; }
            .workspace-card { margin: 0 5px 5px; }
            .mobile-fab { top: 12px; left: 12px; }
        }
    </style>
</head>
<body>
<div class="app-layout" id="appLayout">
    <aside class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <div class="sidebar-title">Menu Principal</div>
            <button class="toggle-btn" id="toggleSidebar" type="button" title="Abrir/Fechar menu">☰</button>
        </div>

        <div class="sidebar-info">
            <div class="sidebar-user">
                <strong><?= htmlspecialchars($_SESSION['usuario_nome']) ?></strong><br>
                <?= ucfirst($_SESSION['usuario_nivel']) ?>
            </div>
        </div>

        <div class="search-wrap">
            <input type="text" id="menuSearch" class="search-input" placeholder="Buscar opção no menu...">
        </div>

        <section class="menu-section" data-section="cadastros">
            <h3>Cadastros</h3>
            <ul class="menu-list">
                <li><a class="menu-link" href="empresas.php"><span class="menu-emoji">🏢</span><span class="menu-text">Empresas</span></a></li>
                <li><a class="menu-link" href="bases.php"><span class="menu-emoji">🗂️</span><span class="menu-text">Cadastro de Bases</span></a></li>
                <li><a class="menu-link" href="clientes_bms.php"><span class="menu-emoji">👥</span><span class="menu-text">Clientes BMS</span></a></li>
                <li><a class="menu-link" href="projetos.php"><span class="menu-emoji">🧩</span><span class="menu-text">Projetos</span></a></li>
                <li><a class="menu-link" href="departamentos.php"><span class="menu-emoji">📂</span><span class="menu-text">Modelos de Departamentos</span></a></li>
                <li><a class="menu-link" href="faixa_funcionarios.php"><span class="menu-emoji">👥</span><span class="menu-text">Modelos de Faixas de Funcionários</span></a></li>
                <li><a class="menu-link" href="usuarios.php"><span class="menu-emoji">👤</span><span class="menu-text">Gerenciar Usuários</span></a></li>
            </ul>
        </section>

        <section class="menu-section" data-section="importacoes-exportacoes">
            <h3>Importações/Exportações</h3>
            <ul class="menu-list">
                <li><a class="menu-link" href="importar_empresas.php"><span class="menu-emoji">📥</span><span class="menu-text">Importar Empresas</span></a></li>
                <li><a class="menu-link" href="importar_contatos_empresa.php"><span class="menu-emoji">📥</span><span class="menu-text">Importar Contatos</span></a></li>
                <li><a class="menu-link" href="exportar_csv.php"><span class="menu-emoji">📤</span><span class="menu-text">Exportar (CSV)</span></a></li>
            </ul>
        </section>

        <section class="menu-section" data-section="questionarios">
            <h3>Questionários</h3>
            <ul class="menu-list">
                <li><a class="menu-link" href="montagem_questionario.php"><span class="menu-emoji">📋</span><span class="menu-text">Montagem de Questionário</span></a></li>
                <li><a class="menu-link" href="gerenciar_status.php"><span class="menu-emoji">📌</span><span class="menu-text">Status do Questionário</span></a></li>
            </ul>
        </section>

        <section class="menu-section" data-section="pesquisas">
            <h3>Pesquisas</h3>
            <ul class="menu-list">
                <li><a class="menu-link" href="nova_pesquisa.php"><span class="menu-emoji">🧪</span><span class="menu-text">Pesquisas (Criação)</span></a></li>
                <li><a class="menu-link" href="pesquisas.php"><span class="menu-emoji">📑</span><span class="menu-text">Pesquisas (Consulta)</span></a></li>
                <li><a class="menu-link" href="portal_cliente.php"><span class="menu-emoji">🎯</span><span class="menu-text">Portal do Cliente</span></a></li>
            </ul>
        </section>

        <section class="menu-section" data-section="analises">
            <h3>Análises e Controle</h3>
            <ul class="menu-list">
                <li><a class="menu-link" href="bi.php"><span class="menu-emoji">📊</span><span class="menu-text">BI</span></a></li>
                <li><a class="menu-link" href="registro_logs.php"><span class="menu-emoji">📝</span><span class="menu-text">Registro de Logs</span></a></li>
                <li><a class="menu-link" href="classificacao_leads.php"><span class="menu-emoji">📈</span><span class="menu-text">Modelos de Classificação de Leads</span></a></li>
                <li><a class="menu-link" href="gerenciar_contato_status.php"><span class="menu-emoji">✅</span><span class="menu-text">Modelos de Status do Contato</span></a></li>
                <li><a class="menu-link" href="#" data-action="reload"><span class="menu-emoji">🔄</span><span class="menu-text">Atualizar Tela</span></a></li>
            </ul>
        </section>

        <a class="sidebar-logout" href="logout.php"><span class="menu-emoji">🚪</span><span class="menu-text">Sair</span></a>
    </aside>

    <main class="main-content">
        <button class="toggle-btn mobile-toggle mobile-fab" id="mobileToggle" type="button" title="Abrir menu">☰</button>

        <div class="card workspace-card">
            <div class="tabs-bar" id="tabsNav"></div>
            <div class="tab-content" id="tabContent">
                <div class="empty-state" id="emptyState">Clique em uma opção do menu lateral para abrir em abas.</div>
            </div>
        </div>
    </main>
</div>

<script>
    (function () {
        const appLayout = document.getElementById('appLayout');
        const sidebarToggle = document.getElementById('toggleSidebar');
        const mobileToggle = document.getElementById('mobileToggle');
        const searchInput = document.getElementById('menuSearch');
        const menuSections = document.querySelectorAll('.menu-section');
        const menuLinks = document.querySelectorAll('.menu-link');
        const tabsNav = document.getElementById('tabsNav');
        const tabContent = document.getElementById('tabContent');
        const emptyState = document.getElementById('emptyState');
        const openTabs = new Map();

        const registrarCliqueMenu = (opcaoMenu, destino) => {
            const params = new URLSearchParams();
            params.append('opcao_menu', opcaoMenu || 'Opcao sem nome');
            params.append('destino', destino || '');

            fetch('registrar_log_menu.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
                body: params.toString()
            }).catch(() => {
                // Falha no log nao deve bloquear a navegacao do menu.
            });
        };

        const applyTitleScaleToFrame = (frame) => {
            try {
                const doc = frame.contentDocument || frame.contentWindow.document;
                if (!doc) return;

                let styleEl = doc.getElementById('copilot-title-scale-style');
                if (!styleEl) {
                    styleEl = doc.createElement('style');
                    styleEl.id = 'copilot-title-scale-style';
                    styleEl.textContent = `
                        h1, h2, h3, h4, h5, h6 {
                            font-size: calc(1em * 0.7) !important;
                        }
                    `;
                    (doc.head || doc.documentElement).appendChild(styleEl);
                }
            } catch (error) {
                // Ignora casos onde não seja possível acessar o iframe.
            }
        };

        const initializeAccordion = () => {
            menuSections.forEach((section) => {
                section.classList.add('collapsed');
                const header = section.querySelector('h3');
                if (!header) return;

                header.setAttribute('role', 'button');
                header.setAttribute('tabindex', '0');

                const toggle = () => section.classList.toggle('collapsed');
                header.addEventListener('click', toggle);
                header.addEventListener('keydown', (event) => {
                    if (event.key === 'Enter' || event.key === ' ') {
                        event.preventDefault();
                        toggle();
                    }
                });
            });
        };

        const isMobile = () => window.matchMedia('(max-width: 900px)').matches;

        const setCollapsed = (collapsed) => {
            appLayout.classList.toggle('sidebar-collapsed', collapsed);
            localStorage.setItem('menuCollapsed', collapsed ? '1' : '0');
        };

        const toggleSidebar = () => {
            if (isMobile()) {
                appLayout.classList.toggle('sidebar-open');
                return;
            }
            setCollapsed(!appLayout.classList.contains('sidebar-collapsed'));
        };

        const filterMenu = (term) => {
            const query = term.trim().toLowerCase();
            menuSections.forEach((section) => {
                const links = section.querySelectorAll('.menu-link');

                if (!query) {
                    links.forEach((link) => {
                        link.parentElement.style.display = '';
                    });
                    section.style.display = '';
                    return;
                }

                let hasVisible = false;

                links.forEach((link) => {
                    const text = link.textContent.toLowerCase();
                    const show = !query || text.includes(query);
                    link.parentElement.style.display = show ? '' : 'none';
                    if (show) hasVisible = true;
                });

                section.style.display = hasVisible ? '' : 'none';
                if (hasVisible) {
                    section.classList.remove('collapsed');
                }
            });
        };

        initializeAccordion();

        const setActiveMenu = (url) => {
            menuLinks.forEach((link) => {
                const href = link.getAttribute('href');
                const isAction = link.dataset.action;
                link.classList.toggle('active', !isAction && href === url);
            });
        };

        const activateTab = (url) => {
            openTabs.forEach((tabData, tabUrl) => {
                const active = tabUrl === url;
                tabData.tabItem.classList.toggle('active', active);
                tabData.frame.classList.toggle('active', active);
            });
            emptyState.style.display = openTabs.size ? 'none' : 'flex';
            setActiveMenu(url);
        };

        const closeTab = (url) => {
            const tabData = openTabs.get(url);
            if (!tabData) return;

            const wasActive = tabData.tabItem.classList.contains('active');
            tabData.tabItem.remove();
            tabData.frame.remove();
            openTabs.delete(url);

            if (!openTabs.size) {
                emptyState.style.display = 'flex';
                setActiveMenu('');
                return;
            }

            if (wasActive) {
                const lastUrl = Array.from(openTabs.keys()).pop();
                activateTab(lastUrl);
            }
        };

        const isPrincipalScreenUrl = (rawUrl) => {
            try {
                const parsed = new URL(rawUrl, window.location.href);
                const fileName = parsed.pathname.split('/').pop().toLowerCase();
                return fileName === 'principal.php' || fileName === 'principal_administrador.php' || fileName === 'principal_operador.php';
            } catch (error) {
                return false;
            }
        };

        const openOrFocusTab = (url, title) => {
            if (openTabs.has(url)) {
                activateTab(url);
                return;
            }

            const tabItem = document.createElement('div');
            tabItem.className = 'tab-item';

            const tabButton = document.createElement('button');
            tabButton.type = 'button';
            tabButton.className = 'tab-button';
            tabButton.textContent = title;
            tabButton.title = title;

            const closeButton = document.createElement('button');
            closeButton.type = 'button';
            closeButton.className = 'tab-close';
            closeButton.textContent = '×';
            closeButton.title = 'Fechar aba';

            tabButton.addEventListener('click', () => activateTab(url));
            closeButton.addEventListener('click', (event) => {
                event.stopPropagation();
                closeTab(url);
            });

            tabItem.appendChild(tabButton);
            tabItem.appendChild(closeButton);
            tabsNav.appendChild(tabItem);

            const frame = document.createElement('iframe');
            frame.className = 'tab-pane';
            frame.src = url;
            frame.title = title;
            tabContent.appendChild(frame);

            frame.addEventListener('load', () => {
                let currentFrameUrl = '';
                try {
                    currentFrameUrl = frame.contentWindow.location.href;
                } catch (error) {
                    return;
                }

                applyTitleScaleToFrame(frame);

                if (isPrincipalScreenUrl(currentFrameUrl)) {
                    closeTab(url);
                }
            });

            openTabs.set(url, { tabItem, frame });
            activateTab(url);
        };

        sidebarToggle.addEventListener('click', toggleSidebar);
        mobileToggle.addEventListener('click', toggleSidebar);
        searchInput.addEventListener('input', (event) => filterMenu(event.target.value));

        menuLinks.forEach((link) => {
            link.addEventListener('click', (event) => {
                const action = link.dataset.action;
                const href = link.getAttribute('href');

                if (action === 'reload') {
                    event.preventDefault();
                    const textNodeReload = link.querySelector('.menu-text');
                    registrarCliqueMenu(textNodeReload ? textNodeReload.textContent.trim() : 'Atualizar Tela', 'reload');
                    location.reload();
                    return;
                }

                if (!href || href === '#') {
                    return;
                }

                event.preventDefault();
                const textNode = link.querySelector('.menu-text');
                const title = textNode ? textNode.textContent.trim() : 'Aba';
                registrarCliqueMenu(title, href);
                openOrFocusTab(href, title);

                if (isMobile()) {
                    appLayout.classList.remove('sidebar-open');
                }
            });
        });

        window.addEventListener('resize', () => {
            if (!isMobile()) {
                appLayout.classList.remove('sidebar-open');
            }
        });

        if (localStorage.getItem('menuCollapsed') === '1' && !isMobile()) {
            setCollapsed(true);
        }
    })();
</script>
</body>
</html>
