<?php
/**
 * Área do Usuário - Checkout Pro 2025
 * 
 * Dashboard completo para usuários comuns (não administradores)
 */

session_start();

// Incluir helper de autenticação
require_once __DIR__ . '/../backend/auth_helper.php';

// Verifica se o usuário está logado e é usuário comum
// Se for admin, redireciona para dashboard admin
requer_usuario('/dashboard/index.php');

// Obter dados do usuário logado
$usuario = usuario_logado();
$nome_usuario = $usuario['nome'] ?? 'Usuário';
$currentPage = isset($_GET['page']) ? $_GET['page'] : 'home';
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Área do Usuário | Checkout Pro</title>
    
    <!-- Carregar configurações White Label (CSS dinâmico e logos) -->
    <?php 
    require __DIR__ . '/../config/config_db.php';
    require_once __DIR__ . '/includes/load_settings.php'; 
    ?>
    
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600;700;800&display=swap">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
        /* =========================================
           1. VARIÁVEIS E TEMA
           ========================================= */
        :root {
            --bg-body: #f3f4f6;
            --bg-card: #ffffff;
            --bg-header: #ffffff;
            --bg-sidebar: linear-gradient(180deg, #667eea, #764ba2);
            --text-main: #1f2937;
            --text-muted: #6b7280;
            --text-sidebar: #e0e7ff;
            --border-color: rgba(0,0,0,0.06);
            --shadow-soft: 0 4px 20px rgba(0,0,0,0.05);
            --title-gradient: linear-gradient(to right, #667eea, #764ba2);
            --logout-color: #f87171;
            
            --sidebar-width: 260px;
            --sidebar-collapsed: 75px;
            --header-height: 70px;
            --transition: 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
        }

        [data-theme="dark"] {
            --bg-body: #020617;
            --bg-card: #0f172a;
            --bg-header: #0f172a;
            --bg-sidebar: linear-gradient(180deg, #020617, #0f172a); 
            --text-main: #ffffff;
            --text-muted: #94a3b8;
            --text-sidebar: #ffffff;
            --border-color: rgba(255,255,255,0.08);
            --shadow-soft: 0 4px 25px rgba(0,0,0,0.5);
            --title-gradient: linear-gradient(to right, #22d3ee, #818cf8);
        }

        /* CORREÇÃO: Sidebar no Modo Dark */
        [data-theme="dark"] #sidebar {
            background: linear-gradient(180deg, #020617, #0f172a) !important;
            border-right: 1px solid rgba(255, 255, 255, 0.08) !important;
        }

        /* Garantir que textos do menu continuem legíveis no modo dark */
        [data-theme="dark"] #sidebar .nav-link {
            color: #ffffff !important;
        }

        [data-theme="dark"] #sidebar .nav-link:hover {
            color: #ffffff !important;
        }

        [data-theme="dark"] #sidebar .logo-box {
            border-bottom-color: rgba(255, 255, 255, 0.08) !important;
        }

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

        body {
            font-family: 'Montserrat', sans-serif;
            background-color: var(--bg-body);
            color: var(--text-main);
            width: 100%; min-height: 100vh;
            overflow-x: hidden;
            transition: background-color 0.4s ease, color 0.4s ease;
        }

        a { text-decoration: none; color: inherit; }
        ul { list-style: none; }

        /* =========================================
           2. SIDEBAR
           ========================================= */
        #sidebar {
            position: fixed; top: 0; left: 0; bottom: 0;
            width: var(--sidebar-width);
            background: var(--bg-sidebar);
            z-index: 1000;
            display: flex; flex-direction: column;
            transition: width var(--transition), transform var(--transition);
            box-shadow: 5px 0 15px rgba(0,0,0,0.1);
            overflow: hidden;
            white-space: nowrap;
        }

        body.sidebar-collapsed #sidebar {
            width: var(--sidebar-collapsed);
        }

        .logo-box {
            height: 90px;
            display: flex; align-items: center; 
            padding: 10px 15px;
            border-bottom: 1px solid rgba(255,255,255,0.05);
            background: rgba(0,0,0,0.1);
            justify-content: center;
            overflow: hidden;
        }
        
        .logo-box img { 
            width: auto;
            height: 100%;
            max-width: 100%;
            object-fit: contain;
            background: transparent;
            filter: drop-shadow(0 4px 6px rgba(0,0,0,0.3));
            transition: var(--transition);
        }
        
        body.sidebar-collapsed .nav-link span,
        body.sidebar-collapsed .nav-link .arrow-icon {
            opacity: 0; pointer-events: none; display: none;
        }
        
        body.sidebar-collapsed .logo-box { padding: 5px; }

        .menu-list { flex: 1; padding-top: 20px; overflow-y: auto; overflow-x: hidden; display: flex; flex-direction: column; }
        
        .nav-item { position: relative; }

        .nav-link {
            display: flex; align-items: center;
            height: 50px; padding: 0 20px;
            color: var(--text-sidebar);
            opacity: 0.8; font-weight: 600; font-size: 14px;
            transition: 0.2s; border-left: 4px solid transparent;
        }

        .nav-link:hover { background: rgba(255,255,255,0.1); opacity: 1; color: #fff; }
        
        .nav-link.active {
            background: rgba(255,255,255,0.15); opacity: 1; 
            color: #00e0c6; border-left-color: #00e0c6;
        }

        .nav-link i { font-size: 18px; min-width: 40px; text-align: center; }

        .submenu { background: rgba(0,0,0,0.2); max-height: 0; overflow: hidden; transition: 0.4s ease; }
        .submenu.open { max-height: 300px; }
        .submenu a { padding-left: 65px; height: 40px; display: flex; align-items: center; font-size: 13px; color: rgba(255,255,255,0.7); }
        .submenu a:hover { color: #fff; background: rgba(255,255,255,0.05); }

        .logout-item { margin-top: auto; border-top: 1px solid rgba(255,255,255,0.05); }
        .logout-link { color: var(--logout-color) !important; opacity: 1; }
        .logout-link:hover { background: rgba(220, 38, 38, 0.2) !important; color: #fff !important; }

        /* =========================================
           3. MAIN CONTENT
           ========================================= */
        .main-wrapper {
            margin-left: var(--sidebar-width);
            transition: margin-left var(--transition);
            min-height: 100vh;
            display: flex; flex-direction: column;
        }

        body.sidebar-collapsed .main-wrapper {
            margin-left: var(--sidebar-collapsed);
        }

        #topbar {
            height: var(--header-height);
            background: var(--bg-header);
            display: flex; align-items: center; justify-content: space-between;
            padding: 0 30px;
            box-shadow: var(--shadow-soft);
            position: sticky; top: 0; z-index: 900;
            border-bottom: 1px solid var(--border-color);
        }

        .header-left { display: flex; align-items: center; gap: 20px; }

        .toggle-btn {
            background: none; border: none; font-size: 22px;
            color: var(--text-muted); cursor: pointer;
            width: 45px; height: 45px; border-radius: 8px;
            display: flex; align-items: center; justify-content: center;
            transition: 0.3s;
        }
        .toggle-btn:hover { background: rgba(0,0,0,0.05); color: var(--text-main); }

        .page-title h1 {
            font-size: 24px; font-weight: 800; text-transform: uppercase;
            background: var(--title-gradient);
            -webkit-background-clip: text; -webkit-text-fill-color: transparent;
            background-clip: text;
        }
        
        /* CORREÇÃO: Quando cor customizada for aplicada, remover efeito de gradiente */
        .page-title h1[style*="color"] {
            background: none !important;
            -webkit-background-clip: unset !important;
            -webkit-text-fill-color: unset !important;
            background-clip: unset !important;
        }

        .top-actions { display: flex; align-items: center; gap: 15px; }

        .theme-toggle {
            width: 40px; height: 40px; border-radius: 10px;
            border: 1px solid var(--border-color);
            background: var(--bg-body); color: var(--text-main);
            display: flex; align-items: center; justify-content: center;
            cursor: pointer; transition: 0.3s;
        }
        .theme-toggle:hover { border-color: #6366f1; color: #6366f1; }

        .user-badge {
            display: flex; align-items: center; gap: 10px; font-weight: 600; font-size: 14px;
            padding: 6px 15px; border-radius: 30px;
            background: rgba(128, 128, 128, 0.05);
            border: 1px solid var(--border-color);
        }

        #content { 
            padding: 30px; 
            animation: fadeIn 0.5s ease; 
            width: 100%; 
            display: block !important;
            opacity: 1 !important;
            visibility: visible !important;
            min-height: 400px;
            background-color: transparent;
        }

        [data-theme="dark"] #content {
            background-color: transparent;
            color: var(--text-main);
        }

        #content * {
            color: inherit;
        }

        [data-theme="dark"] #content * {
            color: var(--text-main);
        }
        @keyframes fadeIn { 
            from { opacity: 0; transform: translateY(10px); } 
            to { opacity: 1; transform: translateY(0); } 
        }

        .card { background: var(--bg-card); color: var(--text-main); border: 1px solid var(--border-color); border-radius: 8px; box-shadow: var(--shadow-soft); }
        input, select, textarea { background: var(--bg-body); color: var(--text-main); border: 1px solid var(--border-color); border-radius: 6px; }

        /* =========================================
           4. RESPONSIVIDADE (MOBILE)
           ========================================= */
        @media (max-width: 768px) {
            #sidebar {
                transform: translateX(-100%);
                width: 280px;
            }
            
            body.sidebar-mobile-open #sidebar {
                transform: translateX(0);
            }

            .main-wrapper { margin-left: 0 !important; }
            
            #mobile-overlay {
                display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0;
                background: rgba(0,0,0,0.6); z-index: 999;
                backdrop-filter: blur(3px);
            }
            body.sidebar-mobile-open #mobile-overlay { display: block; }

            #topbar { padding: 0 15px; }
            .page-title h1 { font-size: 16px; }
            .user-badge span { display: none; }
            
            body.sidebar-collapsed .nav-link span {
                display: block !important; opacity: 1 !important;
            }
            
            .logo-box img { height: auto; width: 60%; max-height: 90%; }
        }
    </style>
</head>
<body>

    <div id="mobile-overlay" onclick="toggleSidebar()"></div>

    <nav id="sidebar">
        <div class="logo-box">
            <?php 
            // Garantir que getSystemSetting está disponível
            if (!function_exists('getSystemSetting')) {
                require_once __DIR__ . '/../backend/settings_helper.php';
            }
            // Limpar cache para garantir valor atualizado
            if (function_exists('clearSettingsCache')) {
                clearSettingsCache();
            }
            // Buscar logo do sidebar do usuário diretamente do banco (sem cache)
            $logo_sidebar = '';
            try {
                if (isset($pdo)) {
                    $stmt_logo = $pdo->prepare("SELECT setting_value FROM system_settings WHERE setting_key = 'logo_sidebar_user' LIMIT 1");
                    $stmt_logo->execute();
                    $result_logo = $stmt_logo->fetch(PDO::FETCH_ASSOC);
                    if ($result_logo && !empty($result_logo['setting_value'])) {
                        $logo_sidebar = trim($result_logo['setting_value']);
                    }
                }
            } catch (PDOException $e) {
                error_log("Erro ao buscar logo sidebar user: " . $e->getMessage());
            }
            
            // Exibir APENAS a imagem configurada - SEM fallback para imagem padrão
            if (!empty($logo_sidebar)): 
                // Garantir caminho correto - remover espaços e garantir barra inicial
                $logo_path = trim($logo_sidebar);
                // Se não começar com /, adicionar (exceto se for URL completa)
                if (!filter_var($logo_path, FILTER_VALIDATE_URL) && strpos($logo_path, '/') !== 0) {
                    $logo_path = '/' . ltrim($logo_path, '/');
                }
            ?>
                <img src="<?= htmlspecialchars($logo_path, ENT_QUOTES, 'UTF-8'); ?>" alt="Logo" style="max-width: 100%; height: auto; object-fit: contain;">
            <?php else: ?>
                <!-- Sem logo configurada - não exibir nada -->
            <?php endif; ?>
        </div>

        <div class="menu-list">
            <div class="nav-item">
                <a href="?page=home" class="nav-link <?php echo $currentPage == 'home' ? 'active' : ''; ?>">
                    <i class="fas fa-home"></i> <span>Início</span>
                </a>
            </div>

            <div class="nav-item">
                <a href="?page=meus_produtos" class="nav-link <?php echo $currentPage == 'meus_produtos' ? 'active' : ''; ?>">
                    <i class="fas fa-box-open"></i> <span>Meus Produtos</span>
                </a>
            </div>

            <div class="nav-item">
                <a href="?page=minhas_compras" class="nav-link <?php echo $currentPage == 'minhas_compras' ? 'active' : ''; ?>">
                    <i class="fas fa-shopping-bag"></i> <span>Minhas Compras</span>
                </a>
            </div>

            <div class="nav-item">
                <a href="javascript:void(0);" class="nav-link has-submenu-link" onclick="toggleSubmenu(this)">
                    <i class="fas fa-handshake"></i> <span>Afiliação</span>
                    <i class="fas fa-chevron-down arrow-icon" style="margin-left: auto; font-size: 10px;"></i>
                </a>
                <div class="submenu">
                    <a href="?page=afiliacao_marketplace">Marketplace</a>
                    <a href="?page=minhas_vendas_afiliado">Minhas Vendas (Afiliado)</a>
                </div>
            </div>

            <div class="nav-item">
                <a href="javascript:void(0);" class="nav-link has-submenu-link" onclick="toggleSubmenu(this)">
                    <i class="fas fa-chart-line"></i> <span>Vendas</span>
                    <i class="fas fa-chevron-down arrow-icon" style="margin-left: auto; font-size: 10px;"></i>
                </a>
                <div class="submenu">
                    <a href="?page=minhas_vendas_produtor">Como Produtor</a>
                    <a href="?page=minhas_vendas_afiliado">Como Afiliado</a>
                </div>
            </div>

            <div class="nav-item">
                <a href="javascript:void(0);" class="nav-link has-submenu-link" onclick="toggleSubmenu(this)">
                    <i class="fas fa-user-friends"></i> <span>Afiliados</span>
                    <i class="fas fa-chevron-down arrow-icon" style="margin-left: auto; font-size: 10px;"></i>
                </a>
                <div class="submenu">
                    <a href="?page=meus_afiliados">Meus Afiliados</a>
                </div>
            </div>

            <div class="nav-item">
                <a href="javascript:void(0);" class="nav-link has-submenu-link" onclick="toggleSubmenu(this)">
                    <i class="fas fa-wallet"></i> <span>Financeiro</span>
                    <i class="fas fa-chevron-down arrow-icon" style="margin-left: auto; font-size: 10px;"></i>
                </a>
                <div class="submenu">
                    <a href="?page=financeiro">Visão Geral</a>
                    <a href="?page=solicitar_saque">Solicitar Saque</a>
                    <a href="?page=meus_saques">Meus Saques</a>
                </div>
            </div>

            <div class="nav-item">
                <a href="?page=configuracoes" class="nav-link <?php echo $currentPage == 'configuracoes' ? 'active' : ''; ?>">
                    <i class="fas fa-cog"></i> <span>Configurações</span>
                </a>
            </div>

            <div class="nav-item">
                <a href="/views/marketplace.php" target="_blank" class="nav-link">
                    <i class="fas fa-store"></i> <span>Marketplace</span>
                    <i class="fas fa-external-link-alt" style="margin-left: auto; font-size: 10px;"></i>
                </a>
            </div>

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

    <div class="main-wrapper">
        
        <header id="topbar">
            <div class="header-left">
                <button class="toggle-btn" onclick="toggleSidebar()">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="page-title">
                    <h1><?php 
                        $titles = [
                            'home' => 'Início',
                            'meus_produtos' => 'Meus Produtos',
                            'minhas_compras' => 'Minhas Compras',
                            'afiliacao_marketplace' => 'Afiliação Marketplace',
                            'minhas_vendas_produtor' => 'Minhas Vendas (Produtor)',
                            'minhas_vendas_afiliado' => 'Minhas Vendas (Afiliado)',
                            'financeiro' => 'Financeiro',
                            'solicitar_saque' => 'Solicitar Saque',
                            'meus_saques' => 'Meus Saques',
                            'configuracoes' => 'Configurações'
                        ];
                        echo $titles[$currentPage] ?? 'Área do Usuário';
                    ?></h1>
                </div>
            </div>

            <div class="top-actions">
                <button class="theme-toggle" id="themeBtn" title="Alternar Tema">
                    <i class="fas fa-moon"></i>
                </button>

                <?php require_once __DIR__ . '/includes/header_perfil_saldo.php'; ?>
            </div>
        </header>

        <main id="content">
            <?php 
            // Incluir sistema de notificações de vendas (apenas para usuários comuns)
            require_once __DIR__ . '/includes/notificacoes_vendas.php';
            // Incluir notificações/broadcast
            require_once __DIR__ . '/includes/notificacoes_broadcast.php';
            // Incluir chat de suporte (apenas se habilitado)
            require_once __DIR__ . '/includes/chat_suporte.php';
            ?>
            <?php
            // Mapeamento de páginas
            $pagesMap = [
                'home' => 'home.php',
                'meus_produtos' => 'meus_produtos.php',
                'minhas_compras' => 'minhas_compras.php',
                'afiliacao_marketplace' => 'afiliacao_marketplace.php',
                'minhas_vendas_produtor' => 'minhas_vendas_produtor.php',
                'minhas_vendas_afiliado' => 'minhas_vendas_afiliado.php',
                'meus_afiliados' => 'meus_afiliados.php',
                'financeiro' => 'financeiro.php',
                'solicitar_saque' => 'solicitar_saque.php',
                'meus_saques' => 'meus_saques.php',
                'configuracoes' => 'configuracoes.php'
            ];

            $pagesDir = __DIR__ . '/pages_usuario/';
            $pageFile = isset($pagesMap[$currentPage]) ? $pagesDir . $pagesMap[$currentPage] : $pagesDir . 'home.php';
            
            if (file_exists($pageFile)) {
                include $pageFile;
            } else {
                echo '<div style="color: var(--text-muted); text-align: center; margin-top: 50px; font-size: 1.2rem;">';
                echo '<i class="fas fa-exclamation-triangle"></i> Página não encontrada.';
                echo '</div>';
            }
            ?>
        </main>
    </div>

    <script>
        // Controle de Tema
        (function() {
            const htmlElement = document.documentElement;
            const themeBtn = document.getElementById('themeBtn');
            
            function applyTheme(theme) {
                if (theme === 'dark') {
                    htmlElement.setAttribute('data-theme', 'dark');
                    localStorage.setItem('theme', 'dark');
                    if (themeBtn) {
                        const themeIcon = themeBtn.querySelector('i');
                        if (themeIcon) themeIcon.className = 'fas fa-sun';
                    }
                } else {
                    htmlElement.removeAttribute('data-theme');
                    localStorage.setItem('theme', 'light');
                    if (themeBtn) {
                        const themeIcon = themeBtn.querySelector('i');
                        if (themeIcon) themeIcon.className = 'fas fa-moon';
                    }
                }
            }

            const savedTheme = localStorage.getItem('theme');
            if (savedTheme) {
                applyTheme(savedTheme);
            }

            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', function() {
                    if (themeBtn) {
                        themeBtn.addEventListener('click', () => {
                            const currentTheme = htmlElement.getAttribute('data-theme') === 'dark' ? 'dark' : 'light';
                            const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
                            applyTheme(newTheme);
                        });
                    }
                });
            } else {
                if (themeBtn) {
                    themeBtn.addEventListener('click', () => {
                        const currentTheme = htmlElement.getAttribute('data-theme') === 'dark' ? 'dark' : 'light';
                        const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
                        applyTheme(newTheme);
                    });
                }
            }
        })();

        // Controle do Sidebar
        function toggleSidebar() {
            const body = document.body;
            const isMobile = window.innerWidth <= 768;

            if (isMobile) {
                body.classList.toggle('sidebar-mobile-open');
            } else {
                body.classList.toggle('sidebar-collapsed');
                const isCollapsed = body.classList.contains('sidebar-collapsed');
                localStorage.setItem('sidebarState', isCollapsed ? 'collapsed' : 'expanded');
            }
        }

        if (window.innerWidth > 768) {
            const savedSidebar = localStorage.getItem('sidebarState');
            if (savedSidebar === 'collapsed') {
                document.body.classList.add('sidebar-collapsed');
            }
        }

        // Controle de Submenus
        function toggleSubmenu(link) {
            if (document.body.classList.contains('sidebar-collapsed') && window.innerWidth > 768) {
                document.body.classList.remove('sidebar-collapsed');
                setTimeout(() => {
                    const submenu = link.nextElementSibling;
                    submenu.classList.toggle('open');
                }, 300);
            } else {
                const submenu = link.nextElementSibling;
                submenu.classList.toggle('open');
            }
            
            const icon = link.querySelector('.arrow-icon');
            if(icon) {
                icon.style.transform = icon.style.transform === 'rotate(180deg)' ? 'rotate(0deg)' : 'rotate(180deg)';
            }
        }

        // Garantir que o conteúdo seja exibido
        (function() {
            function ensureContentVisible() {
                const content = document.getElementById('content');
                if (content) {
                    content.style.display = 'block';
                    content.style.opacity = '1';
                    content.style.visibility = 'visible';
                    content.offsetHeight;
                }
            }

            ensureContentVisible();
            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', ensureContentVisible);
            }
            setTimeout(ensureContentVisible, 100);
        })();
    </script>
</body>
</html>
