<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SON - Dashboard Analítico</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-annotation@1.0.2"></script>
    <style>
        :root {
            --primary-color: #3498db;
            --secondary-color: #2c3e50;
            --accent-color: #e74c3c;
            --success-color: #2ecc71;
            --warning-color: #f39c12;
            --light-color: #ecf0f1;
            --dark-color: #2c3e50;
            --gray-color: #95a5a6;
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f7fa;
            color: #333;
            line-height: 1.6;
        }

        .header-fixed {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            background-color: white;
            padding: 5px 15px;
            z-index: 1000;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
            height: 65px;
            gap: 10px;
        }
        
        .header-left {
            display: flex;
            align-items: center;
            gap: 8px;
            min-width: 280px;
        }
        
        .header-fixed img {
            height: 35px;
            margin-right: 10px;
        }
        
        .header-title {
            margin: 0;
            flex-grow: 1;
            text-align: center;
            color: var(--secondary-color);
            font-size: 1.3rem;
            font-weight: 600;
        }
        
        .user-initial {
            width: 35px;
            height: 35px;
            border-radius: 50%;
            background: #ccc;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            font-size: 1.1em;
        }
        
        .permission-badge {
            display: inline-block;
            padding: 3px 8px;
            border-radius: 20px;
            font-size: 0.75em;
            font-weight: 600;
        }
        
        .permission-admin {
            background-color: var(--primary-color);
            color: white;
        }
        
        .permission-user {
            background-color: var(--gray-color);
            color: white;
        }
        
        .permission-super-admin {
            background-color: var(--accent-color);
            color: white;
        }

        .user-menu-container {
            position: relative;
            display: inline-block;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 6px 10px;
            cursor: pointer;
            border-radius: 6px;
            transition: background-color 0.3s;
        }

        .user-info:hover {
            background-color: #f5f5f5;
        }

        .user-dropdown {
            position: absolute;
            top: 100%;
            right: 0;
            background: white;
            border: 1px solid #ddd;
            border-radius: 6px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.15);
            min-width: 180px;
            display: none;
            z-index: 1100;
            overflow: hidden;
        }

        .user-dropdown.show {
            display: block;
        }

        .user-dropdown a {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 10px 12px;
            text-decoration: none;
            color: #333;
            border-bottom: 1px solid #eee;
            transition: background-color 0.2s;
        }

        .user-dropdown a:hover {
            background-color: #f8f9fa;
        }

        .user-dropdown a:last-child {
            border-bottom: none;
            color: var(--accent-color);
        }

        .user-dropdown a:last-child:hover {
            background-color: #ffeaea;
        }

        .user-dropdown i {
            width: 16px;
            text-align: center;
        }

        .tenant-logo-container {
            margin-left: 10px;
            padding-left: 10px;
            border-left: 1px solid #eee;
        }

        .tenant-logo {
            width: 35px;
            height: 35px;
            border-radius: 6px;
            object-fit: cover;
            border: 2px solid #fff;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .logo-upload-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 2000;
            justify-content: center;
            align-items: center;
        }

        .logo-upload-content {
            background: white;
            padding: 20px;
            border-radius: 10px;
            width: 90%;
            max-width: 380px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.3);
        }

        .logo-upload-content h3 {
            margin-bottom: 12px;
            color: var(--secondary-color);
        }

        .logo-preview {
            width: 110px;
            height: 110px;
            border: 2px dashed #ddd;
            border-radius: 8px;
            margin: 12px auto;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
        }

        .logo-preview img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
        }

        .logo-upload-actions {
            display: flex;
            gap: 8px;
            justify-content: flex-end;
            margin-top: 15px;
        }

        .btn {
            padding: 7px 14px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-weight: 600;
            transition: background-color 0.3s;
        }

        .btn-primary {
            background: var(--primary-color);
            color: white;
        }

        .btn-primary:hover {
            background: #2980b9;
        }

        .btn-secondary {
            background: var(--gray-color);
            color: white;
        }

        .btn-secondary:hover {
            background: #7f8c8d;
        }

        .funil-selector {
            display: flex;
            align-items: center;
            gap: 6px;
            padding: 4px 10px;
            background: #f8f9fa;
            border-radius: 6px;
            border: 1px solid #e9ecef;
            white-space: nowrap;
        }

        .funil-selector h3 {
            margin: 0;
            font-size: 0.9em;
            color: #495057;
            font-weight: 600;
        }

        .funil-selector strong {
            color: var(--primary-color);
        }

        .funil-button {
            padding: 5px 10px;
            background: var(--primary-color);
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 0.85em;
            font-weight: 600;
            transition: background-color 0.3s;
        }

        .funil-button:hover {
            background: #2980b9;
        }

        .funil-dropdown {
            position: absolute;
            top: 100%;
            left: 0;
            background: white;
            border: 1px solid #ddd;
            border-radius: 6px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            min-width: 180px;
            display: none;
            z-index: 1100;
            overflow: hidden;
        }

        .funil-dropdown.show {
            display: block;
        }

        .funil-dropdown a {
            display: block;
            padding: 8px 12px;
            text-decoration: none;
            color: #333;
            border-bottom: 1px solid #eee;
            transition: background-color 0.2s;
        }

        .funil-dropdown a:hover {
            background-color: #f8f9fa;
            color: var(--primary-color);
        }

        .funil-dropdown a:last-child {
            border-bottom: none;
        }

        .header-center {
            flex: 1;
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 0 8px;
            min-width: 380px;
        }

        .header-right {
            display: flex;
            align-items: center;
            gap: 8px;
            min-width: 240px;
        }

        .filtros-container {
            display: flex;
            align-items: center;
            gap: 15px;
            padding: 6px 12px;
            background: #f8f9fa;
            border-radius: 6px;
            border: 1px solid #e9ecef;
        }

        .filtros-section {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .filtros-label {
            font-weight: 600;
            color: #495057;
            font-size: 0.85em;
            margin-right: 3px;
            white-space: nowrap;
        }

        .filtro-btn {
            padding: 6px 10px;
            border: 1px solid #dee2e6;
            background: white;
            border-radius: 5px;
            cursor: pointer;
            transition: all 0.3s ease;
            color: #6c757d;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
            font-size: 0.85em;
        }

        .filtro-btn:hover {
            background: #e9ecef;
            transform: translateY(-1px);
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .filtro-btn.active {
            background: var(--primary-color);
            color: white;
            border-color: var(--primary-color);
        }

        .filtro-status-atrasada.active {
            background: var(--accent-color);
            border-color: var(--accent-color);
        }

        .filtro-status-hoje.active {
            background: var(--warning-color);
            border-color: var(--warning-color);
        }

        .filtro-status-concluida.active {
            background: var(--success-color);
            border-color: var(--success-color);
        }
        
        .tooltip {
            position: relative;
            display: inline-block;
            overflow: visible;
        }

        .tooltip::after {
            content: attr(data-tooltip);
            position: absolute;
            bottom: auto;
            top: calc(100% + 6px);
            border-top: none;
            border-bottom: 12px solid #333;
            left: 50%;
            transform: translateX(-50%);
            background: #333;
            color: #fff;
            padding: 5px 8px;
            border-radius: 4px;
            font-size: 0.7rem;
            white-space: nowrap;
            opacity: 0;
            visibility: hidden;
            transition: opacity 0.2s ease, transform 0.2s ease;
            pointer-events: none;
            z-index: 1000;
        }

        .tooltip::before {
            content: '';
            position: absolute;
            bottom: 100%;
            left: 50%;
            transform: translateX(-50%);
            border-left: 5px solid transparent;
            border-right: 5px solid transparent;
            border-top: 5px solid #333;
            opacity: 0;
            visibility: hidden;
            transition: opacity 0.2s ease;
            pointer-events: none;
        }

        .tooltip:hover::after,
        .tooltip:hover::before {
            opacity: 1;
            visibility: visible;
        }

        .search-wrapper {
            position: relative;
            min-width: 220px;
        }

        #pesquisaCliente {
            padding: 6px 30px 6px 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 0.85em;
            width: 100%;
        }

        #contadorResultados {
            position: absolute;
            right: 8px;
            top: 50%;
            transform: translateY(-50%);
            background: var(--primary-color);
            color: white;
            padding: 2px 6px;
            border-radius: 10px;
            font-size: 0.65em;
            font-weight: bold;
            display: none;
            min-width: 18px;
            text-align: center;
        }

        .sidebar {
            position: fixed;
            right: 0;
            top: 65px;
            height: calc(100vh - 65px);
            width: 55px;
            background: white;
            box-shadow: 2px 0 10px rgba(0,0,0,0.2);
            z-index: 1001;
            transition: width 0.3s ease;
            overflow-x: hidden;
            display: flex;
            flex-direction: column;
        }

        .sidebar.expanded {
            width: 240px;
        }

        .sidebar-toggle {
            display: none;
            position: absolute;
            right: 8px;
            top: 8px;
            cursor: pointer;
            z-index: 1002;
        }

        .sidebar-menu {
            list-style: none;
            padding: 0;
            margin: 0;
            flex: 1;
        }

        .sidebar-menu li {
            border-bottom: 1px solid #eee;
        }

        .sidebar-menu a {
            display: flex;
            align-items: center;
            padding: 12px 15px;
            text-decoration: none;
            color: #333;
            white-space: nowrap;
            transition: background-color 0.3s;
        }

        .sidebar-menu a:hover {
            background-color: #f5f5f5;
        }

        .sidebar-menu i {
            width: 22px;
            height: 22px;
            margin-right: 12px;
            text-align: center;
            flex-shrink: 0;
        }

        .sidebar-menu .menu-text {
            opacity: 0;
            transition: opacity 0.2s ease 0.1s;
        }

        .sidebar.expanded .sidebar-menu .menu-text {
            opacity: 1;
        }

        .submenu-sidebar {
            max-height: 0;
            overflow: hidden;
            transition: max-height 0.3s ease;
            background-color: #f9f9f9;
        }

        .submenu-sidebar.active {
            max-height: 500px;
        }

        .submenu-sidebar a {
            padding-left: 45px;
            font-size: 0.85em;
        }

        .menu-item-sidebar {
            position: relative;
        }

        .menu-item-sidebar > a:after {
            content: "▶";
            margin-left: auto;
            font-size: 0.75em;
            transition: transform 0.3s;
        }

        .menu-item-sidebar > a.active:after {
            transform: rotate(90deg);
        }

        .main-content {
            margin-right: 55px;
            padding: 15px;
            transition: margin-right 0.3s ease;
        }

        .main-content.expanded {
            margin-right: 240px;
        }

        .sidebar-footer {
            text-align: center;
            font-size: 11px;
            color: #777;
            padding: 8px 0;
            background: #fafafa;
            border-top: 1px solid #eee;
        }

        .sidebar.expanded .sidebar-footer span {
            opacity: 1;
            transition: opacity 0.3s ease;
        }

        .sidebar .sidebar-footer span {
            opacity: 0.7;
        }

        .sidebar-watermark {
            padding: 12px 8px;
            text-align: center;
            border-top: 1px solid #eee;
            background: #fafafa;
            opacity: 0.6;
            transition: opacity 0.3s ease;
        }

        .sidebar-watermark:hover {
            opacity: 0.8;
        }

        .sidebar-watermark img {
            max-width: 100%;
            height: auto;
            max-height: 70px;
            object-fit: contain;
        }

        @media (max-width: 768px) {
            .header-fixed {
                padding: 5px 10px;
                height: 60px;
                gap: 5px;
            }
            
            .header-left {
                gap: 5px;
                min-width: auto;
            }
            
            .header-fixed img {
                height: 30px;
                margin-right: 5px;
            }
            
            .header-center {
                margin: 0 5px;
                min-width: auto;
            }
            
            .header-right {
                gap: 5px;
                min-width: auto;
            }
            
            .funil-selector {
                padding: 3px 6px;
                gap: 4px;
            }
            
            .filtros-container {
                gap: 8px;
                padding: 4px 8px;
            }
            
            .filtros-section {
                gap: 5px;
            }
            
            .search-wrapper {
                min-width: 150px;
            }
            
            .sidebar {
                top: 60px;
                height: calc(100vh - 60px);
            }
            
            .main-content {
                margin-right: 0;
                padding: 10px;
            }
            
            .sidebar-watermark img {
                max-height: 25px;
            }
        }
        
        .has-submenu .submenu {
            display: none;
            padding-left: 20px;
            background-color: #f5f5f5;
        }

        .has-submenu .submenu a {
            font-size: 14px;
            padding: 8px 10px;
            display: block;
        }

        .submenu-arrow {
            float: right;
            transition: transform 0.3s ease;
        }

        .submenu-open .submenu {
            display: block;
        }

        .submenu-open .submenu-arrow {
            transform: rotate(180deg);
        }

        /* Menu item desabilitado */
        .menu-item-disabled {
            opacity: 0.5;
            pointer-events: none;
            background-color: #f5f5f5;
        }
        
        .menu-item-disabled a {
            cursor: not-allowed;
        }
    </style>
</head>
<body>
    <?php
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }

    $current_page = basename($_SERVER['PHP_SELF']);
    $is_index_page = ($current_page === 'index.php');

    $funil_info = ['nome' => 'Funil Principal'];
    $funis_disponiveis = [];
    $tenant_logo = null;
    
    // Variáveis para controle das funcionalidades do tenant
    $func_telefonia = false;
    $func_landing_page = false;
    $func_chat = false;
    $func_formularios = false;
    $max_usuarios_func = 2;
    $usuarios_ativos = 0;

    if (isset($_SESSION['tenant_id'])) {
        if (isset($conn) && $conn instanceof mysqli && $conn->ping()) {
            // Buscar dados do tenant incluindo as funcionalidades
            $tenant_stmt = $conn->prepare("
                SELECT t.logo_path, 
                       t.func_telefonia, 
                       t.func_landing_page, 
                       t.func_chat, 
                       t.func_formularios,
                       t.max_usuarios_func,
                       t.usuarios_ativos
                FROM tenants t 
                WHERE t.id = ?
            ");
            $tenant_stmt->bind_param("i", $_SESSION['tenant_id']);
            $tenant_stmt->execute();
            $tenant_result = $tenant_stmt->get_result();
            
            if ($tenant_row = $tenant_result->fetch_assoc()) {
                $tenant_logo = $tenant_row['logo_path'];
                $func_telefonia = (bool)$tenant_row['func_telefonia'];
                $func_landing_page = (bool)$tenant_row['func_landing_page'];
                $func_chat = (bool)$tenant_row['func_chat'];
                $func_formularios = (bool)$tenant_row['func_formularios'];
                $max_usuarios_func = (int)$tenant_row['max_usuarios_func'];
                $usuarios_ativos = (int)$tenant_row['usuarios_ativos'];
                
                if ($tenant_logo && !file_exists($tenant_logo)) {
                    $tenant_logo = null;
                    $update_stmt = $conn->prepare("UPDATE tenants SET logo_path = NULL WHERE id = ?");
                    $update_stmt->bind_param("i", $_SESSION['tenant_id']);
                    $update_stmt->execute();
                }
            }
            $tenant_stmt->close();
            
        } else {
            require_once 'conexao.php';
            
            if (isset($conn) && $conn instanceof mysqli && !$conn->connect_error) {
                try {
                    // Buscar dados do tenant incluindo as funcionalidades
                    $tenant_stmt = $conn->prepare("
                        SELECT t.logo_path, 
                               t.func_telefonia, 
                               t.func_landing_page, 
                               t.func_chat, 
                               t.func_formularios,
                               t.max_usuarios_func,
                               t.usuarios_ativos
                        FROM tenants t 
                        WHERE t.id = ?
                    ");
                    $tenant_stmt->bind_param("i", $_SESSION['tenant_id']);
                    $tenant_stmt->execute();
                    $tenant_result = $tenant_stmt->get_result();
                    
                    if ($tenant_row = $tenant_result->fetch_assoc()) {
                        $tenant_logo = $tenant_row['logo_path'];
                        $func_telefonia = (bool)$tenant_row['func_telefonia'];
                        $func_landing_page = (bool)$tenant_row['func_landing_page'];
                        $func_chat = (bool)$tenant_row['func_chat'];
                        $func_formularios = (bool)$tenant_row['func_formularios'];
                        $max_usuarios_func = (int)$tenant_row['max_usuarios_func'];
                        $usuarios_ativos = (int)$tenant_row['usuarios_ativos'];
                        
                        if ($tenant_logo && !file_exists($tenant_logo)) {
                            $tenant_logo = null;
                            $update_stmt = $conn->prepare("UPDATE tenants SET logo_path = NULL WHERE id = ?");
                            $update_stmt->bind_param("i", $_SESSION['tenant_id']);
                            $update_stmt->execute();
                        }
                    }
                    $tenant_stmt->close();
                    
                } catch (Exception $e) {
                    error_log("Erro ao buscar dados do tenant: " . $e->getMessage());
                    $tenant_logo = null;
                }
            }
        }
    }

    if ($is_index_page) {
        if (!isset($conn) || !$conn instanceof mysqli || !$conn->ping()) {
            require_once 'conexao.php';
        }
        
        $tenant_id = $_SESSION['tenant_id'] ?? null;
        $usuario_id = $_SESSION['usuario_id'] ?? null;
        $permissao = $_SESSION['permissao'] ?? 'usuario';
        $is_admin = ($permissao === 'admin');
        $is_super_admin = ($permissao === 'super_admin');
        
        if ($tenant_id && $usuario_id && isset($conn) && $conn instanceof mysqli) {
            if ($is_admin || $is_super_admin) {
                $stmt = $conn->prepare("SELECT id, nome, padrao FROM funis WHERE tenant_id = ? AND ativo = TRUE ORDER BY nome ASC");
                $stmt->bind_param("i", $tenant_id);
            } else {
                $stmt = $conn->prepare("SELECT f.id, f.nome, f.padrao FROM funis f 
                                       JOIN permissoes_funis pf ON f.id = pf.funil_id 
                                       WHERE f.tenant_id = ? AND pf.usuario_id = ? AND pf.visualizar = 1 AND f.ativo = TRUE
                                       ORDER BY f.nome ASC");
                $stmt->bind_param("ii", $tenant_id, $usuario_id);
            }
            
            $stmt->execute();
            $result = $stmt->get_result();
            while ($row = $result->fetch_assoc()) {
                $funis_disponiveis[] = $row;
            }
            $stmt->close();
            
            $funil_id = $_GET['funil'] ?? $_SESSION['funil_ativo'] ?? null;
            
            if (!$funil_id && !empty($funis_disponiveis)) {
                foreach ($funis_disponiveis as $funil) {
                    if ($funil['padrao']) {
                        $funil_id = $funil['id'];
                        break;
                    }
                }
                
                if (!$funil_id) {
                    foreach ($funis_disponiveis as $funil) {
                        if (strtolower($funil['nome']) === 'funil padrao' || strtolower($funil['nome']) === 'funil padrão') {
                            $funil_id = $funil['id'];
                            break;
                        }
                }
                }
                
                if (!$funil_id) {
                    $funil_id = $funis_disponiveis[0]['id'];
                }
            }
            
            if ($funil_id) {
                $sql_funil = "SELECT nome FROM funis WHERE id = ?";
                $stmt_funil = $conn->prepare($sql_funil);
                $stmt_funil->bind_param("i", $funil_id);
                $stmt_funil->execute();
                $result_funil = $stmt_funil->get_result();
                $funil_info = $result_funil->fetch_assoc() ?? ['nome' => 'Funil Principal'];
                $stmt_funil->close();
            }
        }
    }
    ?>

    <div class="header-fixed">
        <div class="header-left">
           <a href="index.php">
               <img src="son_semtexto.png" alt="Logo TVITEC" style="height:80px; margin-right: 8px;">
           </a>
            
            <?php if ($is_index_page): ?>
            <div class="funil-selector">
                <h3>Funil: <strong><?php echo htmlspecialchars($funil_info['nome']); ?></strong></h3>
                <div style="position: relative;">
                    <button class="funil-button" onclick="toggleFunilDropdown()">
                        Trocar ▼
                    </button>
                    <div id="funilDropdown" class="funil-dropdown">
                        <?php foreach ($funis_disponiveis as $funil): ?>
                            <a href="index.php?funil=<?php echo $funil['id']; ?>"><?php echo htmlspecialchars($funil['nome']); ?></a>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </div>

        <?php if ($is_index_page): ?>
            <div class="header-center">
                <div class="filtros-container">
                    <div class="filtros-section">
                        <span class="filtros-label">Status:</span>
                        <button class="filtro-btn filtro-status-atrasada tooltip" data-status="atrasada" data-tooltip="Atrasadas">
                            <i class="fas fa-exclamation-triangle"></i>
                        </button>
                        <button class="filtro-btn filtro-status-hoje tooltip" data-status="hoje" data-tooltip="Para Hoje">
                            <i class="fas fa-clock"></i>
                        </button>
                        <button class="filtro-btn filtro-status-futura tooltip" data-status="futura" data-tooltip="Futuras">
                            <i class="fas fa-calendar"></i>
                        </button>
                        <button class="filtro-btn filtro-status-concluida tooltip" data-status="concluida" data-tooltip="Concluídas">
                            <i class="fas fa-check"></i>
                        </button>
                       
                        <button class="filtro-btn filtro-tipo-outros tooltip" data-status="todos" data-tooltip="Mostrar Todos">
                            <i class="fas fa-eye"></i>
                        </button>
                    </div>
                </div>
            </div>

            <div class="header-right">
                <div class="search-wrapper">
                    <input type="text" id="pesquisaCliente" placeholder="Pesquisar clientes..." style="width: 100%;">
                    <span id="contadorResultados"></span>
                </div>
            </div>
        <?php else: ?>
            <div class="header-center" style="flex: 1;"></div>
            <div class="header-right" style="min-width: 200px;"></div>
        <?php endif; ?>

        <div class="user-menu-container">
            <div class="user-info" id="userMenuTrigger">
                <?php
                $permissao = $_SESSION['permissao'] ?? 'usuario';
                $nome = $_SESSION['nome_usuario'] ?? 'Usuário';
                ?>
                
                <div style="text-align:left; min-width: 120px;">
                    <div style="font-weight: bold; color: #333; font-size: 1em;">
                        <?php echo htmlspecialchars($nome); ?>
                    </div>
                    <div style="font-size: 0.85em; color: #555; white-space: nowrap;">
                        <?php echo htmlspecialchars($_SESSION['email_usuario'] ?? ''); ?>
                    </div>
                </div>
                
                <?php if ($tenant_logo && file_exists($tenant_logo)): ?>
                    <div class="tenant-logo-container">
                        <img src="<?php echo htmlspecialchars($tenant_logo); ?>" alt="Logo Tenant" class="tenant-logo">
                    </div>
                <?php endif; ?>
                
                <i class="fas fa-chevron-down" style="font-size: 0.85em; color: #777;"></i>
            </div>
            <div class="user-dropdown" id="userDropdown">
                <?php 
                $permissao = $_SESSION['permissao'] ?? 'usuario';
                if (in_array($permissao, ['admin', 'super_admin'])): 
                ?>
                <a href="javascript:void(0);" onclick="openLogoUpload()">
                    <i class="fas fa-image"></i> Alterar Logo
                </a>
                <?php endif; ?>

                <a href="perfil_usuario.php">
                    <i class="fas fa-id-card"></i> Perfil
                </a>

                <a href="suporte.php">
                    <i class="fas fa-headset"></i> Suporte
                </a>

                <a href="documentacao.php">
                    <i class="fas fa-book"></i> Documentação
                </a>

                <a href="treinamento.php">
                    <i class="fas fa-chalkboard-teacher"></i> Treinamento
                </a>

                <!-- SUBMENU TELEFONIA - Aparece apenas se funcionalidade liberada -->
                <?php if ($func_telefonia): ?>
                <div class="dropdown-item has-submenu">
                    <a href="javascript:void(0);" onclick="toggleTelefonia()">
                        <i class="fas fa-phone"></i> Telefonia
                        <i class="fas fa-chevron-down submenu-arrow"></i>
                    </a>

                    <div class="submenu" id="telefoniaSubmenu">
                        <a href="javascript:void(0);" onclick="abrirTelefone()">
                            Telefone
                        </a>
                        <a href="https://son.tvitecnologia.com.br/telefonia/relatorio_telefonia.html" target="_blank">
                            Relatório
                        </a>
                    </div>
                </div>
                <?php endif; ?>

                <a href="logout.php">
                    <i class="fas fa-sign-out-alt"></i> Sair
                </a>
            </div>
        </div>
    </div>

<?php
if (!isset($_SESSION['logado']) || $_SESSION['logado'] !== true) {
    return;
}

$permissao = $_SESSION['permissao'] ?? 'usuario';
$is_admin = in_array($permissao, ['admin', 'super_admin']);
?>

<div class="sidebar">
    <div class="sidebar-toggle">
        <i class="fas fa-bars"></i>
    </div>
    <ul class="sidebar-menu">
        <li><a href="index.php"><i class="fas fa-home"></i> <span class="menu-text">Início</span></a></li>

        <?php if ($is_admin): ?>
            <li class="menu-item-sidebar">
                <a href="javascript:void(0);" class="submenu-trigger"><i class="fas fa-cog"></i> <span class="menu-text">Administração</span></a>
                <div class="submenu-sidebar">
                    <a href="cadastrar_usuario.php"><i class="fas fa-plus"></i> <span class="menu-text">Cadastrar Usuário</span></a>
                    <a href="gerenciar_usuarios.php"><i class="fas fa-users-cog"></i> <span class="menu-text">Gerenciar Usuários</span></a>
                 <?php /* ?>  <a href="/integracao_legada/configurar_redirecionamento.php"><i class="fas fa-exchange-alt"></i> <span class="menu-text">Integração</span></a> <?php */ ?>
                </div>
            </li>
        <?php endif; ?>

        <li class="menu-item-sidebar">
            <a href="javascript:void(0);" class="submenu-trigger"><i class="fas fa-tasks"></i> <span class="menu-text">Atividades</span></a>
            <div class="submenu-sidebar">
                <a href="cadastrar_atividade.php"><i class="fas fa-pencil-alt"></i> <span class="menu-text">Cadastrar Tipo</span></a>
                <a href="consulta_atividades.php"><i class="fas fa-search"></i> <span class="menu-text">Consulta</span></a>
                <a href="lista_atividades.php"><i class="fas fa-list"></i> <span class="menu-text">Tipos de Atividades</span></a>
            </div>
        </li>

        <li class="menu-item-sidebar">
            <a href="javascript:void(0);" class="submenu-trigger"><i class="fas fa-chart-line"></i> <span class="menu-text">Análise</span></a>
            <div class="submenu-sidebar">
                <a href="mapa_vendas.php"><i class="fas fa-map-marker-alt"></i> <span class="menu-text">Georreferenciada</span></a>
                <a href="dashboard_clientes.php"><i class="fas fa-chart-bar"></i> <span class="menu-text">Gráfica</span></a>
            </div>
        </li>

        <li><a href="calendario.php"><i class="fas fa-calendar"></i> <span class="menu-text">Calendário</span></a></li>
        
        <!-- Chat - Aparece apenas se funcionalidade liberada -->
        <?php if ($func_chat): ?>
        <li><a href="chat.php"><i class="fas fa-comment"></i> <span class="menu-text">Chat</span></a></li>
        <?php endif; ?>

      <?php if (in_array($permissao, ['usuario', 'vendedor', 'admin', 'super_admin'])): ?>
    
    <li class="menu-item-sidebar">
        <a href="javascript:void(0);" class="submenu-trigger">
            <i class="fas fa-users"></i> 
            <span class="menu-text">Clientes</span>
        </a>
        <div class="submenu-sidebar">
            <a href="clientes_perdidos.php">
                <i class="fas fa-user-times"></i>
                <span class="menu-text">Clientes Perdidos</span>
            </a>
            <a href="lista_clientes.php">
                <i class="fas fa-list"></i> 
                <span class="menu-text">Listar Clientes</span>
            </a>
            <a href="cadastrar_cliente.php">
                <i class="fas fa-plus"></i> 
                <span class="menu-text">Novo Cliente</span>
            </a>
        </div>
    </li>

    <!-- Landing Pages - Aparece apenas se funcionalidade liberada -->
    <?php if ($func_landing_page): ?>
    <li class="menu-item-sidebar">
        <a href="javascript:void(0);" class="submenu-trigger">
            <i class="fas fa-bullhorn"></i> 
            <span class="menu-text">Landing Pages</span>
        </a>
        <div class="submenu-sidebar">
             <a href="landing_pages.php">    <i class="fas fa-plus"></i> <span class="menu-text">Cadastrar LP</span></a>
             <a href="lista_lp.php"><i class="fas fa-list"></i> <span class="menu-text">Listar LP</span></a>
        </div>
    </li>
    <?php endif; ?>

<?php endif; ?>
        
        <?php if (in_array($permissao, ['usuario', 'vendedor', 'admin', 'super_admin'])): ?>
            <li class="menu-item-sidebar">
                <a href="javascript:void(0);" class="submenu-trigger">
                    <i class="fas fa-envelope-open-text"></i> 
                    <span class="menu-text">E-mails</span>
                </a>
                <div class="submenu-sidebar">
                    <a href="enviar_email.php">
                        <i class="fas fa-paper-plane"></i> 
                        <span class="menu-text">Enviar E-mail</span>
                    </a>
                     <a href="templates_email.php">
                        <i class="fas fa-folder-open"></i> 
                        <span class="menu-text">Templates E-mail</span>
                    </a>
                     <a href="editar_assinatura.php">
                        <i class="fas fa-signature"></i> 
                        <span class="menu-text">Editar Assinatura</span>
                    </a>
                </div>
            </li>
        <?php endif; ?>

        <li><a href="fluxos_automatizados.php"><i class="fas fa-project-diagram" aria-hidden="true"></i><span class="menu-text">Fluxos</span></a></li>

        <!-- Formulários - Aparece apenas se funcionalidade liberada -->
        <?php if ($func_formularios): ?>
        <li class="menu-item-sidebar">
            <a href="javascript:void(0);" class="submenu-trigger"><i class="fas fa-file-alt"></i> <span class="menu-text">Formulários</span></a>
            <div class="submenu-sidebar">
                <a href="cadastrar_formulario.php"><i class="fas fa-plus"></i> <span class="menu-text">Cadastrar formulário</span></a>
                <a href="lista_formularios.php"><i class="fas fa-list"></i> <span class="menu-text">Listar Formulários</span></a>
                <a href="enviar_formulario_massa.php" class="menu-btn-primary"><i class="fas fa-envelope-open-text"></i> Envio em Massa</a>            
            </div>
        </li>
        <?php endif; ?>
        
        <li><a href="funis.php"><i class="fas fa-filter"></i> <span class="menu-text">Gerenciar Funis</span></a></li>

        <li class="menu-item-sidebar">
            <a href="javascript:void(0);" class="submenu-trigger"><i class="fas fa-globe"></i> <span class="menu-text">Origens</span></a>
            <div class="submenu-sidebar">
                <a href="cadastrar_origem.php"><i class="fas fa-plus"></i> <span class="menu-text">Cadastrar Origem</span></a>
                <a href="lista_origens.php"><i class="fas fa-list"></i> <span class="menu-text">Listar Origens</span></a>
            </div>
        </li>

        <li class="menu-item-sidebar">
            <a href="javascript:void(0);" class="submenu-trigger"><i class="fas fa-box"></i> <span class="menu-text">Produtos</span></a>
            <div class="submenu-sidebar">
                <a href="cadastrar_produto.php"><i class="fas fa-plus"></i> <span class="menu-text">Cadastrar Produto</span></a>
                <a href="lista_produtos.php"><i class="fas fa-list"></i> <span class="menu-text">Listar Produtos</span></a>
                
            </div>
        </li>

        <li class="sidebar-footer">
            <span>Versão 0.1.0</span>
            <div class="sidebar-watermark">
                <img src="tvitec_watermark.png" alt="Marca d'água">
            </div>
        </li>
    </ul>
</div>

<main class="main-content">
    <!-- Seu conteúdo aqui -->
</main>

<div class="logo-upload-modal" id="logoUploadModal">
    <div class="logo-upload-content">
        <h3>Alterar Logo do Tenant</h3>
        
        <div class="logo-preview" id="logoPreview">
            <span style="color: #999;">Prévia do logo</span>
        </div>
        
        <input type="file" id="tenantLogo" accept="image/jpeg,image/png,image/gif,image/webp" 
               onchange="previewLogo(this)" style="margin: 8px 0;">
        
        <div style="font-size: 0.75em; color: #666; margin-bottom: 12px;">
            Formatos suportados: JPG, PNG, GIF, WebP (Máx: 5MB)
        </div>
        
        <div class="logo-upload-actions">
            <button class="btn btn-secondary" onclick="closeLogoUpload()">Cancelar</button>
            <button class="btn btn-primary" onclick="uploadLogo()">Salvar Logo</button>
        </div>
    </div>
</div>

<!-- POPUP TELEFONE -->
<div id="popupTelefone" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:9999; justify-content:center; align-items:center;">
    
    <div style="background:#fff; width:400px; max-width:95%; border-radius:8px; padding:20px; position:relative;">
        
        <button onclick="fecharTelefone()" 
                style="position:absolute; top:10px; right:10px; background:none; border:none; font-size:18px; cursor:pointer;">
            &times;
        </button>

        <h3 style="margin-top:0;">📞 Telefone</h3>

        <!-- Aqui você pode colocar seu iframe ou sistema de telefone -->
        <iframe src="/telefonia/index.html" 
                style="width:100%; height:400px; border:none;">
        </iframe>

    </div>
</div>

<script>
let telefoneJanela = null;

function abrirTelefone() {
    if (telefoneJanela && !telefoneJanela.closed) {
        telefoneJanela.focus();
        return;
    }

    const largura = 450;
    const altura = 650;

    const esquerda = (screen.width / 2) - (largura / 2);
    const topo = (screen.height / 2) - (altura / 2);

    telefoneJanela = window.open(
        "/telefonia/index.html",
        "JanelaTelefone",
        `width=${largura},
         height=${altura},
         top=${topo},
         left=${esquerda},
         resizable=yes`
    );
}

document.addEventListener('DOMContentLoaded', function() {
    const sidebar = document.querySelector('.sidebar');
    const mainContent = document.querySelector('.main-content');
    const sidebarToggle = document.querySelector('.sidebar-toggle');
    const submenuTriggers = document.querySelectorAll('.submenu-trigger');
    
    if (window.innerWidth > 768) {
        sidebar.addEventListener('mouseenter', function() {
            sidebar.classList.add('expanded');
            mainContent.classList.add('expanded');
        });
        
        sidebar.addEventListener('mouseleave', function() {
            sidebar.classList.remove('expanded');
            mainContent.classList.remove('expanded');
        });
    }
    
    if (sidebarToggle) {
        sidebarToggle.addEventListener('click', function() {
            sidebar.classList.toggle('expanded');
        });
    }
    
    submenuTriggers.forEach(trigger => {
        trigger.addEventListener('click', function(e) {
            e.preventDefault();
            
            document.querySelectorAll('.submenu-sidebar.active').forEach(openSubmenu => {
                if (openSubmenu !== this.nextElementSibling) {
                    openSubmenu.classList.remove('active');
                    openSubmenu.previousElementSibling.classList.remove('active');
                }
            });
            
            const submenu = this.nextElementSibling;
            if (submenu && submenu.classList.contains('submenu-sidebar')) {
                this.classList.toggle('active');
                submenu.classList.toggle('active');
            }
        });
    });

    const userMenuTrigger = document.getElementById('userMenuTrigger');
    const userDropdown = document.getElementById('userDropdown');

    if (userMenuTrigger && userDropdown) {
        userMenuTrigger.addEventListener('click', function(e) {
            e.stopPropagation();
            userDropdown.classList.toggle('show');
        });

        document.addEventListener('click', function() {
            userDropdown.classList.remove('show');
        });

        userDropdown.addEventListener('click', function(e) {
            e.stopPropagation();
        });
    }

    <?php if ($is_index_page): ?>
    const filtroBtns = document.querySelectorAll('.filtro-btn');
    
    filtroBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            filtroBtns.forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            const status = this.getAttribute('data-status');
            console.log('Filtrar por:', status);
        });
    });

    const pesquisaCliente = document.getElementById('pesquisaCliente');
    const contadorResultados = document.getElementById('contadorResultados');
    
    if (pesquisaCliente && contadorResultados) {
        let timeoutPesquisa;
        
        pesquisaCliente.addEventListener('input', function() {
            const termo = this.value.trim();
            
            clearTimeout(timeoutPesquisa);
            
            if (termo.length > 0) {
                contadorResultados.textContent = "...";
                contadorResultados.style.display = 'inline-block';
                
                timeoutPesquisa = setTimeout(() => {
                    const clientesNaPagina = document.querySelectorAll('.cliente-item, .card-cliente, [data-cliente]');
                    let resultados = 0;
                    
                    if (clientesNaPagina.length > 0) {
                        clientesNaPagina.forEach(cliente => {
                            const textoCliente = cliente.textContent.toLowerCase();
                            if (textoCliente.includes(termo.toLowerCase())) {
                                resultados++;
                            }
                        });
                    } else {
                        resultados = Math.min(termo.length * 2, 50);
                    }
                    
                    contadorResultados.textContent = resultados;
                    contadorResultados.style.display = 'inline-block';
                    
                }, 300);
                
            } else {
                contadorResultados.style.display = 'none';
            }
        });
        
        pesquisaCliente.addEventListener('blur', function() {
            setTimeout(() => {
                if (this.value.trim() === '') {
                    contadorResultados.style.display = 'none';
                }
            }, 200);
        });
    }
    <?php endif; ?>
});

function toggleFunilDropdown() {
    const dropdown = document.getElementById('funilDropdown');
    dropdown.classList.toggle('show');
}

document.addEventListener('click', function(e) {
    const dropdown = document.getElementById('funilDropdown');
    const button = document.querySelector('.funil-button');
    
    if (dropdown && button && !dropdown.contains(e.target) && !button.contains(e.target)) {
        dropdown.classList.remove('show');
    }
});

function openLogoUpload() {
    document.getElementById('logoUploadModal').style.display = 'flex';
    document.getElementById('userDropdown').classList.remove('show');
}

function closeLogoUpload() {
    document.getElementById('logoUploadModal').style.display = 'none';
    document.getElementById('tenantLogo').value = '';
    document.getElementById('logoPreview').innerHTML = '<span style="color: #999;">Prévia do logo</span>';
}

function previewLogo(input) {
    const preview = document.getElementById('logoPreview');
    
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        
        reader.onload = function(e) {
            preview.innerHTML = `<img src="${e.target.result}" alt="Prévia do Logo">`;
        }
        
        reader.readAsDataURL(input.files[0]);
    }
}

function uploadLogo() {
    const fileInput = document.getElementById('tenantLogo');
    const file = fileInput.files[0];
    
    if (!file) {
        alert('Por favor, selecione um arquivo');
        return;
    }
    
    if (file.size > 5 * 1024 * 1024) {
        alert('O arquivo é muito grande. Tamanho máximo: 5MB');
        return;
    }
    
    const uploadBtn = document.querySelector('.logo-upload-actions .btn-primary');
    const originalText = uploadBtn.textContent;
    uploadBtn.textContent = 'Enviando...';
    uploadBtn.disabled = true;
    
    const formData = new FormData();
    formData.append('tenant_logo', file);
    
    fetch('upload_tenant_logo.php', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Erro na rede: ' + response.status);
        }
        return response.json();
    })
    .then(data => {
        console.log('Resposta do servidor:', data);
        if (data.success) {
            alert('Logo atualizado com sucesso!');
            closeLogoUpload();
            location.reload();
        } else {
            alert('Erro: ' + data.message);
            uploadBtn.textContent = originalText;
            uploadBtn.disabled = false;
        }
    })
    .catch(error => {
        console.error('Erro:', error);
        alert('Erro ao fazer upload do logo. Verifique o console para mais detalhes.');
        uploadBtn.textContent = originalText;
        uploadBtn.disabled = false;
    });
}

document.addEventListener('click', function(e) {
    const modal = document.getElementById('logoUploadModal');
    if (e.target === modal) {
        closeLogoUpload();
    }
});

function toggleTelefonia() {
    const item = document.querySelector('.has-submenu');
    item.classList.toggle('submenu-open');
}
</script>

</body>
</html>