<?php
session_start();

// ==============================================================================
// 1. CONEXÃO COM O BANCO DE DADOS
// ==============================================================================
$paths = ['../config.php', '../../config.php', 'config.php'];
$config_loaded = false;
foreach ($paths as $path) { 
    if (file_exists($path)) { 
        require_once $path; 
        $config_loaded = true; 
        break; 
    }
}
if (!$config_loaded) { die("Erro Crítico: O arquivo config.php não foi encontrado."); }

// Inclui o motor de envio de e-mail
if (file_exists('../enviar_email.php')) { require_once '../enviar_email.php'; }

// ==============================================================================
// 2. SEGURANÇA (LOGIN)
// ==============================================================================
if (!isset($_SESSION['admin_id'])) { 
    header("Location: ../admin/login.php"); 
    exit; 
}

if (isset($_GET['sair'])) { 
    session_destroy(); 
    header("Location: ../admin/login.php"); 
    exit; 
}

// ==============================================================================
// 3. DEFINIÇÃO DA PÁGINA ATUAL E VARIÁVEIS
// ==============================================================================
$page = $_GET['page'] ?? 'dashboard';
$busca = $_GET['busca'] ?? ''; 
$msg = '';
$erro = '';

// ==============================================================================
// 4. PROCESSAMENTO DE FORMULÁRIOS (POST)
// ==============================================================================

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // --- GESTÃO FINANCEIRA (SAQUES - NOVO!) ---
    if (isset($_POST['acao']) && $_POST['acao'] == 'aprovar_saque') {
        $id_saque = $_POST['id_saque'];
        // Marca como pago e registra data
        $stmt = $pdo->prepare("UPDATE saques SET status = 'pago', data_pagamento = NOW() WHERE id = ?");
        $stmt->execute([$id_saque]);
        
        // Opcional: Enviar e-mail avisando o afiliado que o pix foi feito
        $msg = "Saque #$id_saque aprovado e marcado como pago!";
    }

    if (isset($_POST['acao']) && $_POST['acao'] == 'rejeitar_saque') {
        $id_saque = $_POST['id_saque'];
        $motivo = $_POST['motivo'] ?? 'Dados incorretos';
        
        // 1. Busca dados do saque para devolver o dinheiro
        $stmt = $pdo->prepare("SELECT usuario_id, valor FROM saques WHERE id = ? AND status = 'pendente'");
        $stmt->execute([$id_saque]);
        $saque = $stmt->fetch();

        if ($saque) {
            $pdo->beginTransaction();
            // 2. Devolve o saldo para o usuário
            $pdo->prepare("UPDATE usuarios SET saldo_afiliado = saldo_afiliado + ? WHERE id = ?")->execute([$saque['valor'], $saque['usuario_id']]);
            // 3. Marca saque como rejeitado
            $pdo->prepare("UPDATE saques SET status = 'rejeitado', observacao = ? WHERE id = ?")->execute([$motivo, $id_saque]);
            $pdo->commit();
            $msg = "Saque rejeitado e valor estornado para a conta do afiliado.";
        }
    }

    // --- GESTÃO DE CUPONS E AFILIADOS ---
    if (isset($_POST['acao']) && $_POST['acao'] == 'criar_cupom') {
        $titulo = $_POST['titulo'];
        $codigo = strtoupper(preg_replace('/[^a-zA-Z0-9]/', '', $_POST['codigo']));
        $desc   = $_POST['descricao'];
        $cor    = $_POST['cor'];
        
        // Verifica se a tabela existe (Segurança para não quebrar se não rodou SQL)
        try {
            $stmt = $pdo->prepare("INSERT INTO cupoms (titulo, descricao, codigo, cor_fundo, ativo) VALUES (?, ?, ?, ?, 1)");
            $stmt->execute([$titulo, $desc, $codigo, $cor]);
            $msg = "Cupom criado com sucesso!";
        } catch (Exception $e) {
            $erro = "Erro ao criar cupom. Verifique se a tabela 'cupoms' existe no banco.";
        }
    }

    if (isset($_POST['acao']) && $_POST['acao'] == 'deletar_cupom') {
        $stmt = $pdo->prepare("DELETE FROM cupoms WHERE id = ?");
        $stmt->execute([$_POST['id_cupom']]);
        $msg = "Cupom removido!";
    }

    // --- REENVIAR ACESSO MANUALMENTE ---
    if (isset($_POST['acao']) && $_POST['acao'] == 'reenviar_acesso_manual') {
        $id_aluno = $_POST['id_aluno'];
        $stmt = $pdo->prepare("SELECT nome, email FROM usuarios WHERE id = ?");
        $stmt->execute([$id_aluno]);
        $aluno = $stmt->fetch();

        if ($aluno && function_exists('enviarEmailSMTP')) {
            $assunto = "🔐 Seus dados de acesso";
            $msg_email = "
            <h2>Olá, {$aluno['nome']}!</h2>
            <p>Recebemos sua Compra. Aqui estão seus dados de acesso:</p>
            <p><strong>E-mail:</strong> {$aluno['email']}<br>
            <strong>Senha:</strong> tiktok <small>(Se você já alterou, use a nova)</small></p>
            <br>
            <a href='https://{$_SERVER['HTTP_HOST']}/area_aluno.php'>CLIQUE AQUI PARA ACESSAR</a>
            ";
            
            if(enviarEmailSMTP($aluno['email'], $assunto, $msg_email)) {
                $msg = "Acesso enviado para {$aluno['nome']} com sucesso!";
            } else {
                $erro = "Falha ao enviar. Verifique o SMTP.";
            }
        }
    }

    // --- REENVIO DE E-MAIL (DO HISTÓRICO) ---
    if (isset($_POST['acao']) && $_POST['acao'] == 'reenviar_email_historico') {
        $id_log = $_POST['id_log'];
        $stmt = $pdo->prepare("SELECT * FROM email_logs WHERE id = ?");
        $stmt->execute([$id_log]);
        $log_original = $stmt->fetch();

        if ($log_original && function_exists('enviarEmailSMTP')) {
            if (enviarEmailSMTP($log_original['destinatario'], $log_original['assunto'], $log_original['corpo'])) {
                $msg = "E-mail reenviado com sucesso!";
            } else {
                $erro = "Falha ao reenviar.";
            }
        }
    }

    // --- SALVAR CONFIGURAÇÕES DE E-MAIL (SMTP) ---
    if (isset($_POST['acao']) && $_POST['acao'] == 'salvar_smtp') {
        $pdo->query("INSERT IGNORE INTO config_smtp (id) VALUES (1)");
        $stmt = $pdo->prepare("UPDATE config_smtp SET host=?, email=?, senha=?, porta=? WHERE id=1");
        $stmt->execute([$_POST['host'], $_POST['email'], $_POST['senha'], $_POST['porta']]);
        $msg = "Configurações SMTP salvas!";
    }

    // --- SALVAR MODELOS (TEMPLATES) ---
    if (isset($_POST['acao']) && $_POST['acao'] == 'salvar_template') {
        $gatilho = $_POST['gatilho'];
        $assunto = $_POST['assunto'];
        $corpo = $_POST['corpo'];
        
        $check = $pdo->prepare("SELECT id FROM email_templates WHERE gatilho = ?");
        $check->execute([$gatilho]);
        if($check->fetch()) {
            $stmt = $pdo->prepare("UPDATE email_templates SET assunto=?, corpo=? WHERE gatilho=?");
            $stmt->execute([$assunto, $corpo, $gatilho]);
        } else {
            $stmt = $pdo->prepare("INSERT INTO email_templates (gatilho, assunto, corpo) VALUES (?, ?, ?)");
            $stmt->execute([$gatilho, $assunto, $corpo]);
        }
        $msg = "Modelo atualizado!";
    }

    // --- ENVIO MANUAL (BROADCAST) ---
    if (isset($_POST['acao']) && $_POST['acao'] == 'enviar_email_manual') {
        $destinatario_tipo = $_POST['destinatario_id']; 
        $assunto = $_POST['assunto_manual'];
        $mensagem = $_POST['corpo_manual'];

        if (function_exists('enviarEmailSMTP')) {
            if ($destinatario_tipo == 'todos') {
                $alunos = $pdo->query("SELECT email, nome FROM usuarios WHERE tipo='cliente'")->fetchAll();
                $count = 0;
                foreach($alunos as $aluno) {
                    $msg_final = str_replace('{nome}', $aluno['nome'], $mensagem);
                    enviarEmailSMTP($aluno['email'], $assunto, $msg_final);
                    $count++;
                }
                $msg = "Envio em massa iniciado para $count alunos!";
            } else {
                $stmt = $pdo->prepare("SELECT email, nome FROM usuarios WHERE id = ?");
                $stmt->execute([$destinatario_tipo]);
                $aluno = $stmt->fetch();
                if ($aluno) {
                    $msg_final = str_replace('{nome}', $aluno['nome'], $mensagem);
                    if(enviarEmailSMTP($aluno['email'], $assunto, $msg_final)) {
                        $msg = "E-mail enviado para {$aluno['nome']}!";
                    }
                }
            }
        }
    }

    // --- CONFIGURAÇÕES GERAIS ---
    if (isset($_POST['acao']) && $_POST['acao'] == 'salvar_loja') {
        $logo_url = $_POST['logo_atual'];
        if (!empty($_FILES['logo']['name'])) {
            $ext = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
            $novo_nome = 'logo_' . uniqid() . "." . $ext;
            if(!is_dir('../uploads')) mkdir('../uploads');
            move_uploaded_file($_FILES['logo']['tmp_name'], '../uploads/' . $novo_nome);
            $logo_url = 'uploads/' . $novo_nome;
        }
        $pdo->query("INSERT IGNORE INTO config_loja (id) VALUES (1)");
        $stmt = $pdo->prepare("UPDATE config_loja SET nome_loja=?, cor_primaria=?, logo_url=? WHERE id=1");
        $stmt->execute([$_POST['nome_loja'], $_POST['cor_primaria'], $logo_url]);
        $msg = "Loja atualizada!";
    }

    if (isset($_POST['acao']) && $_POST['acao'] == 'salvar_gateway') {
        $pdo->query("INSERT IGNORE INTO config_gateway (id) VALUES (1)");
        $stmt = $pdo->prepare("UPDATE config_gateway SET access_token=? WHERE id=1");
        $stmt->execute([$_POST['access_token']]);
        $msg = "Token salvo!";
    }

    // --- ALUNOS ---
    if (isset($_POST['acao']) && $_POST['acao'] == 'criar_aluno') {
        $nome = $_POST['nome'];
        $email = $_POST['email'];
        $senha = $_POST['senha']; 
        
        $check = $pdo->prepare("SELECT id FROM usuarios WHERE email = ?");
        $check->execute([$email]);
        
        if ($check->rowCount() > 0) {
            $erro = "E-mail já cadastrado!";
        } else {
            $hash = password_hash($senha, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("INSERT INTO usuarios (nome, email, senha, tipo) VALUES (?, ?, ?, 'cliente')");
            $stmt->execute([$nome, $email, $hash]);
            $msg = "Aluno criado!";
        }
    }

    if (isset($_POST['acao']) && $_POST['acao'] == 'editar_aluno') {
        $id_aluno = $_POST['id_aluno'];
        $stmt = $pdo->prepare("UPDATE usuarios SET nome=?, email=?, cpf=?, whatsapp=? WHERE id=?");
        $stmt->execute([$_POST['nome'], $_POST['email'], $_POST['cpf'], $_POST['whatsapp'], $id_aluno]);
        $msg = "Aluno atualizado!";

        if (!empty($_POST['nova_senha'])) {
            $hash = password_hash($_POST['nova_senha'], PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("UPDATE usuarios SET senha = ? WHERE id = ?");
            $stmt->execute([$hash, $id_aluno]);
        }
        
        if (!empty($_POST['curso_matricula'])) {
            $curso_id = $_POST['curso_matricula'];
            $check = $pdo->prepare("SELECT id FROM matriculas WHERE usuario_id=? AND curso_id=?");
            $check->execute([$id_aluno, $curso_id]);
            if(!$check->fetch()) {
                $stmt = $pdo->prepare("INSERT INTO matriculas (usuario_id, curso_id, ativo) VALUES (?, ?, 1)");
                $stmt->execute([$id_aluno, $curso_id]);
            }
        }
    }

    if (isset($_POST['acao']) && $_POST['acao'] == 'remover_matricula') {
        $stmt = $pdo->prepare("DELETE FROM matriculas WHERE id = ?");
        $stmt->execute([$_POST['id_matricula']]);
        $msg = "Matrícula removida.";
    }

    // --- PRODUTOS ---
    if (isset($_POST['acao']) && $_POST['acao'] == 'salvar_produto') {
        $id = $_POST['id_produto'] ?? '';
        $nome = $_POST['nome'];
        $descricao = $_POST['descricao'];
        $preco_de = str_replace(',', '.', str_replace('R$', '', $_POST['preco_de']));
        $preco_por = str_replace(',', '.', str_replace('R$', '', $_POST['preco_por']));
        $tipo = $_POST['tipo'];
        $vendas = $_POST['vendas_qtd'];
        $validade = $_POST['validade_dias'] ?? 36500;
        
        $caminho_img = $_POST['imagem_atual'] ?? '';
        if (!empty($_FILES['imagem']['name'])) {
            $ext = pathinfo($_FILES['imagem']['name'], PATHINFO_EXTENSION);
            $novo_nome = uniqid() . "." . $ext;
            if(!is_dir('../uploads')) mkdir('../uploads');
            move_uploaded_file($_FILES['imagem']['tmp_name'], '../uploads/' . $novo_nome);
            $caminho_img = 'uploads/' . $novo_nome;
        }

        if ($id) {
            $stmt = $pdo->prepare("UPDATE produtos SET nome=?, descricao=?, preco_original=?, preco_atual=?, tipo=?, vendas_qtd=?, imagem_principal=?, validade_dias=? WHERE id=?");
            $stmt->execute([$nome, $descricao, $preco_de, $preco_por, $tipo, $vendas, $caminho_img, $validade, $id]);
            $msg = "Produto atualizado!";
        } else {
            $stmt = $pdo->prepare("INSERT INTO produtos (nome, descricao, preco_original, preco_atual, tipo, vendas_qtd, imagem_principal, validade_dias) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$nome, $descricao, $preco_de, $preco_por, $tipo, $vendas, $caminho_img, $validade]);
            $msg = "Produto criado!";
        }
    }
    
    if (isset($_POST['acao']) && $_POST['acao'] == 'excluir_produto') {
        $stmt = $pdo->prepare("DELETE FROM produtos WHERE id = ?");
        $stmt->execute([$_POST['id_excluir']]);
        $msg = "Produto removido!";
    }

    // --- CURSOS / MÓDULOS / AULAS ---
    if (isset($_POST['acao']) && $_POST['acao'] == 'salvar_curso') {
        $id = $_POST['curso_id'] ?? '';
        $produto_id = $_POST['produto_vinculo'] ?: NULL;
        
        $banner_url = $_POST['banner_atual'] ?? '';
        if (!empty($_FILES['banner']['name'])) {
            $ext = pathinfo($_FILES['banner']['name'], PATHINFO_EXTENSION);
            $novo_nome = 'banner_' . uniqid() . "." . $ext;
            if(!is_dir('../uploads')) mkdir('../uploads');
            move_uploaded_file($_FILES['banner']['tmp_name'], '../uploads/' . $novo_nome);
            $banner_url = 'uploads/' . $novo_nome;
        }

        $capa_url = $_POST['capa_atual'] ?? '';
        if (!empty($_FILES['capa']['name'])) {
            $ext = pathinfo($_FILES['capa']['name'], PATHINFO_EXTENSION);
            $novo_nome = 'capa_' . uniqid() . "." . $ext;
            if(!is_dir('../uploads')) mkdir('../uploads');
            move_uploaded_file($_FILES['capa']['tmp_name'], '../uploads/' . $novo_nome);
            $capa_url = 'uploads/' . $novo_nome;
        }

        if ($id) {
            $stmt = $pdo->prepare("UPDATE cursos SET nome=?, descricao=?, produto_id=?, imagem_banner=?, imagem_capa=? WHERE id=?");
            $stmt->execute([$_POST['nome_curso'], $_POST['desc_curso'], $produto_id, $banner_url, $capa_url, $id]);
            $msg = "Curso atualizado!";
        } else {
            $stmt = $pdo->prepare("INSERT INTO cursos (nome, descricao, produto_id, imagem_banner, imagem_capa) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([$_POST['nome_curso'], $_POST['desc_curso'], $produto_id, $banner_url, $capa_url]);
            $msg = "Curso criado!";
        }
    }
    if (isset($_POST['acao']) && $_POST['acao'] == 'excluir_curso') {
        $stmt = $pdo->prepare("DELETE FROM cursos WHERE id = ?");
        $stmt->execute([$_POST['id']]);
        $msg = "Curso excluído!";
    }

    if (isset($_POST['acao']) && $_POST['acao'] == 'salvar_modulo') {
        $id = $_POST['modulo_id'] ?? '';
        if ($id) {
            $stmt = $pdo->prepare("UPDATE modulos SET curso_id=?, nome=?, ordem=? WHERE id=?");
            $stmt->execute([$_POST['curso_id'], $_POST['nome_modulo'], $_POST['ordem_modulo'], $id]);
            $msg = "Módulo atualizado!";
        } else {
            $stmt = $pdo->prepare("INSERT INTO modulos (curso_id, nome, ordem) VALUES (?, ?, ?)");
            $stmt->execute([$_POST['curso_id'], $_POST['nome_modulo'], $_POST['ordem_modulo']]);
            $msg = "Módulo criado!";
        }
    }
    if (isset($_POST['acao']) && $_POST['acao'] == 'excluir_modulo') {
        $stmt = $pdo->prepare("DELETE FROM modulos WHERE id = ?");
        $stmt->execute([$_POST['id']]);
        $msg = "Módulo excluído!";
    }

    if (isset($_POST['acao']) && $_POST['acao'] == 'salvar_aula') {
        $id = $_POST['aula_id'] ?? '';
        $link_material = $_POST['material_atual'] ?? '';
        $permitir_dl = $_POST['permitir_download'] ?? 1;
        $formato = $_POST['formato_video'] ?? 'paisagem'; 
        
        if (!empty($_FILES['material']['name'])) {
            $ext = strtolower(pathinfo($_FILES['material']['name'], PATHINFO_EXTENSION));
            if(in_array($ext, ['pdf', 'zip', 'png', 'jpg', 'jpeg', 'doc', 'docx'])) {
                $novo_nome = 'material_' . uniqid() . "." . $ext;
                if(!is_dir('../uploads')) mkdir('../uploads');
                move_uploaded_file($_FILES['material']['tmp_name'], '../uploads/' . $novo_nome);
                $link_material = 'uploads/' . $novo_nome;
            }
        }

        if ($id) {
            $stmt = $pdo->prepare("UPDATE aulas SET modulo_id=?, nome=?, video_url=?, descricao_texto=?, material_complementar=?, ordem=?, permitir_download=?, formato_video=? WHERE id=?");
            $stmt->execute([$_POST['modulo_id'], $_POST['nome_aula'], $_POST['video_url'], $_POST['descricao_aula'], $link_material, $_POST['ordem_aula'], $permitir_dl, $formato, $id]);
            $msg = "Aula atualizado!";
        } else {
            $stmt = $pdo->prepare("INSERT INTO aulas (modulo_id, nome, video_url, descricao_texto, material_complementar, ordem, permitir_download, formato_video) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$_POST['modulo_id'], $_POST['nome_aula'], $_POST['video_url'], $_POST['descricao_aula'], $link_material, $_POST['ordem_aula'], $permitir_dl, $formato]);
            $msg = "Aula criada!";
        }
    }
    if (isset($_POST['acao']) && $_POST['acao'] == 'excluir_aula') {
        $stmt = $pdo->prepare("DELETE FROM aulas WHERE id = ?");
        $stmt->execute([$_POST['id']]);
        $msg = "Aula excluída!";
    }
}

// ==============================================================================
// 5. CARREGAR DADOS PARA EDIÇÃO
// ==============================================================================
$produto_edit = null; $edit_curso = null; $edit_modulo = null; $edit_aula = null;

if ($page == 'produtos' && isset($_GET['editar'])) {
    $stmt = $pdo->prepare("SELECT * FROM produtos WHERE id=?");
    $stmt->execute([$_GET['editar']]); 
    $produto_edit = $stmt->fetch();
}

if ($page == 'cursos') {
    if (isset($_GET['editar_curso'])) { 
        $stmt = $pdo->prepare("SELECT * FROM cursos WHERE id=?"); 
        $stmt->execute([$_GET['editar_curso']]); 
        $edit_curso = $stmt->fetch(); 
    }
    if (isset($_GET['editar_modulo'])) { 
        $stmt = $pdo->prepare("SELECT * FROM modulos WHERE id=?"); 
        $stmt->execute([$_GET['editar_modulo']]); 
        $edit_modulo = $stmt->fetch(); 
    }
    if (isset($_GET['editar_aula'])) { 
        $stmt = $pdo->prepare("SELECT * FROM aulas WHERE id=?"); 
        $stmt->execute([$_GET['editar_aula']]); 
        $edit_aula = $stmt->fetch(); 
    }
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Painel Admin - TheLike</title>
    <link rel="icon" href="https://www.tiktok.com/favicon.ico" type="image/x-icon" />
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/lucide@latest"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Inter', sans-serif; }
        .scroller { scrollbar-width: thin; }
    </style>
</head>
<body class="bg-gray-100 flex h-screen overflow-hidden">

    <div id="sidebar-overlay" onclick="toggleSidebar()" class="fixed inset-0 bg-black bg-opacity-50 z-20 hidden md:hidden glass transition-opacity"></div>

    <aside id="sidebar" class="bg-[#1e1e1e] text-white flex flex-col shadow-2xl shrink-0 fixed inset-y-0 left-0 w-64 z-30 transform -translate-x-full md:translate-x-0 md:relative transition duration-200 ease-in-out">
        <div class="h-16 flex items-center justify-between px-6 border-b border-gray-700">
            <h2 class="text-xl font-bold tracking-wider">Jone<span class="text-[#ff0050]">Admin</span></h2>
            <button onclick="toggleSidebar()" class="md:hidden text-gray-400 hover:text-white"><i data-lucide="x"></i></button>
        </div>
        <nav class="flex-1 px-2 py-4 space-y-2 overflow-y-auto">
            <a href="?page=dashboard" class="flex items-center px-4 py-3 text-gray-300 hover:bg-[#ff0050] hover:text-white rounded <?= $page=='dashboard'?'bg-[#ff0050] text-white':'' ?>">
                <i data-lucide="layout-dashboard" class="w-5 h-5 mr-3"></i> Dashboard
            </a>
            <!-- NOVAS ABAS DE GESTÃO -->
            <a href="?page=financeiro" class="flex items-center px-4 py-3 text-gray-300 hover:bg-[#ff0050] hover:text-white rounded <?= $page=='financeiro'?'bg-[#ff0050] text-white':'' ?>">
                <i data-lucide="dollar-sign" class="w-5 h-5 mr-3"></i> Financeiro (Saques)
            </a>
            <a href="?page=afiliados" class="flex items-center px-4 py-3 text-gray-300 hover:bg-[#ff0050] hover:text-white rounded <?= $page=='afiliados'?'bg-[#ff0050] text-white':'' ?>">
                <i data-lucide="award" class="w-5 h-5 mr-3"></i> Afiliados & Mkt
            </a>
            
            <a href="?page=produtos" class="flex items-center px-4 py-3 text-gray-300 hover:bg-[#ff0050] hover:text-white rounded <?= $page=='produtos'?'bg-[#ff0050] text-white':'' ?>">
                <i data-lucide="shopping-bag" class="w-5 h-5 mr-3"></i> Produtos
            </a>
            <a href="?page=cursos" class="flex items-center px-4 py-3 text-gray-300 hover:bg-[#ff0050] hover:text-white rounded <?= $page=='cursos'?'bg-[#ff0050] text-white':'' ?>">
                <i data-lucide="graduation-cap" class="w-5 h-5 mr-3"></i> Aulas / Cursos
            </a>
            <a href="?page=alunos" class="flex items-center px-4 py-3 text-gray-300 hover:bg-[#ff0050] hover:text-white rounded <?= $page=='alunos'?'bg-[#ff0050] text-white':'' ?>">
                <i data-lucide="users" class="w-5 h-5 mr-3"></i> Alunos
            </a>
            <a href="?page=emails" class="flex items-center px-4 py-3 text-gray-300 hover:bg-[#ff0050] hover:text-white rounded <?= $page=='emails'?'bg-[#ff0050] text-white':'' ?>">
                <i data-lucide="mail" class="w-5 h-5 mr-3"></i> E-mails & Mkt
            </a>
            <a href="?page=personalizar" class="flex items-center px-4 py-3 text-gray-300 hover:bg-[#ff0050] hover:text-white rounded <?= $page=='personalizar'?'bg-[#ff0050] text-white':'' ?>">
                <i data-lucide="settings" class="w-5 h-5 mr-3"></i> Config
            </a>
        </nav>
        <div class="p-4 border-t border-gray-700">
            <a href="?sair=true" class="flex items-center text-red-400 hover:text-white transition">
                <i data-lucide="log-out" class="w-5 h-5 mr-3"></i> Sair
            </a>
        </div>
    </aside>

    <main class="flex-1 overflow-y-auto w-full relative">
        <header class="bg-white shadow-sm p-4 flex items-center justify-between md:hidden sticky top-0 z-10">
            <button onclick="toggleSidebar()" class="text-gray-600"><i data-lucide="menu" class="w-6 h-6"></i></button>
            <h1 class="text-lg font-bold text-gray-800 capitalize"><?= ucfirst($page) ?></h1>
            <div class="w-6"></div> 
        </header>

        <div class="p-4 md:p-8">
            <?php if($msg): ?><div class="bg-green-100 border-l-4 border-green-500 text-green-700 p-4 mb-6 rounded shadow flex items-center text-sm md:text-base"><i data-lucide="check-circle" class="mr-2 shrink-0"></i> <?= $msg ?></div><?php endif; ?>
            <?php if($erro): ?><div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 mb-6 rounded shadow flex items-center text-sm md:text-base"><i data-lucide="alert-circle" class="mr-2 shrink-0"></i> <?= $erro ?></div><?php endif; ?>

            <!-- PÁGINA FINANCEIRO (SAQUES) -->
            <?php if($page == 'financeiro'): ?>
                <h1 class="text-2xl font-bold text-gray-800 mb-6 flex items-center gap-2"><i data-lucide="dollar-sign"></i> Gestão de Saques</h1>
                
                <?php 
                    try {
                        $saques = $pdo->query("SELECT s.*, u.nome, u.email FROM saques s JOIN usuarios u ON s.usuario_id = u.id ORDER BY s.status = 'pendente' DESC, s.id DESC")->fetchAll(PDO::FETCH_ASSOC);
                    } catch (Exception $e) { $saques = []; echo "<p class='text-red-500'>Tabela de saques não encontrada. Rode o SQL.</p>"; }
                ?>

                <div class="bg-white rounded-lg shadow overflow-hidden">
                    <div class="overflow-x-auto">
                        <table class="w-full text-sm text-left">
                            <thead class="bg-gray-100 text-gray-600 uppercase text-xs">
                                <tr>
                                    <th class="p-4">Data</th>
                                    <th class="p-4">Afiliado</th>
                                    <th class="p-4">Valor</th>
                                    <th class="p-4">Chave PIX</th>
                                    <th class="p-4">Status</th>
                                    <th class="p-4 text-right">Ação</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-100">
                                <?php if(empty($saques)): ?>
                                    <tr><td colspan="6" class="p-8 text-center text-gray-400">Nenhum pedido de saque encontrado.</td></tr>
                                <?php else: foreach($saques as $s): 
                                    $statusColor = $s['status'] == 'pendente' ? 'bg-yellow-100 text-yellow-800' : ($s['status'] == 'pago' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800');
                                ?>
                                <tr class="hover:bg-gray-50">
                                    <td class="p-4 text-gray-500"><?= date('d/m/y H:i', strtotime($s['data_solicitacao'])) ?></td>
                                    <td class="p-4">
                                        <div class="font-bold"><?= $s['nome'] ?></div>
                                        <div class="text-xs text-gray-400"><?= $s['email'] ?></div>
                                    </td>
                                    <td class="p-4 font-bold text-gray-800">R$ <?= number_format($s['valor'], 2, ',', '.') ?></td>
                                    <td class="p-4">
                                        <div class="flex items-center gap-2">
                                            <span class="bg-gray-200 px-2 py-1 rounded text-xs font-mono select-all"><?= $s['chave_pix'] ?></span>
                                            <span class="text-[10px] text-gray-400 uppercase">(<?= $s['tipo_chave'] ?>)</span>
                                        </div>
                                    </td>
                                    <td class="p-4">
                                        <span class="px-2 py-1 rounded-full text-xs font-bold <?= $statusColor ?>"><?= strtoupper($s['status']) ?></span>
                                    </td>
                                    <td class="p-4 text-right">
                                        <?php if($s['status'] == 'pendente'): ?>
                                            <div class="flex justify-end gap-2">
                                                <form method="POST" onsubmit="return confirm('Confirmar pagamento de R$ <?= $s['valor'] ?>?');">
                                                    <input type="hidden" name="acao" value="aprovar_saque">
                                                    <input type="hidden" name="id_saque" value="<?= $s['id'] ?>">
                                                    <button class="bg-green-600 hover:bg-green-700 text-white px-3 py-1 rounded text-xs font-bold flex items-center gap-1">
                                                        <i data-lucide="check"></i> Pagar
                                                    </button>
                                                </form>
                                                <form method="POST" onsubmit="return confirm('Rejeitar e devolver o saldo?');">
                                                    <input type="hidden" name="acao" value="rejeitar_saque">
                                                    <input type="hidden" name="id_saque" value="<?= $s['id'] ?>">
                                                    <button class="bg-red-500 hover:bg-red-600 text-white px-3 py-1 rounded text-xs font-bold flex items-center gap-1">
                                                        <i data-lucide="x"></i> Negar
                                                    </button>
                                                </form>
                                            </div>
                                        <?php else: ?>
                                            <span class="text-xs text-gray-400">Finalizado</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            <?php endif; ?>

            <!-- PÁGINA AFILIADOS (Dashboard e Cupons) -->
            <?php if($page == 'afiliados'): ?>
                <?php 
                    try {
                        $totalComissoes = $pdo->query("SELECT SUM(saldo_afiliado) FROM usuarios")->fetchColumn();
                        $totalVendasAfiliados = $pdo->query("SELECT SUM(total_vendas_afiliado) FROM usuarios")->fetchColumn();
                        $listaCupons = $pdo->query("SELECT * FROM cupoms ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);
                        $topAfiliados = $pdo->query("SELECT u.nome, u.email, u.saldo_afiliado, u.total_vendas_afiliado, u.codigo_afiliado FROM usuarios u WHERE u.codigo_afiliado IS NOT NULL ORDER BY u.saldo_afiliado DESC LIMIT 10")->fetchAll(PDO::FETCH_ASSOC);
                    } catch (Exception $e) { echo "<div class='bg-yellow-100 p-4 mb-4 text-yellow-800'>Aviso: Tabelas não encontradas.</div>"; }
                ?>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
                    <div class="bg-white p-6 rounded-lg shadow border-l-4 border-pink-500">
                        <p class="text-gray-500 text-sm font-bold uppercase">Comissões Pendentes (Saldo)</p>
                        <h3 class="text-3xl font-bold text-gray-800">R$ <?= number_format($totalComissoes ?? 0, 2, ',', '.') ?></h3>
                    </div>
                    <div class="bg-white p-6 rounded-lg shadow border-l-4 border-blue-500">
                        <p class="text-gray-500 text-sm font-bold uppercase">Total de Vendas</p>
                        <h3 class="text-3xl font-bold text-gray-800"><?= $totalVendasAfiliados ?? 0 ?></h3>
                    </div>
                </div>

                <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
                    <div class="bg-white rounded-lg shadow overflow-hidden">
                        <div class="p-6 bg-gray-50 border-b flex justify-between items-center">
                            <h3 class="font-bold text-gray-800 flex items-center gap-2"><i data-lucide="ticket"></i> Cupons</h3>
                            <button onclick="document.getElementById('formCupom').classList.toggle('hidden')" class="bg-gray-800 text-white text-xs px-3 py-1 rounded">+ Novo</button>
                        </div>
                        <div id="formCupom" class="hidden bg-gray-50 p-6 border-b">
                            <form method="POST" class="grid gap-3">
                                <input type="hidden" name="acao" value="criar_cupom">
                                <div class="grid grid-cols-2 gap-3"><input type="text" name="codigo" placeholder="CÓDIGO" class="border p-2 rounded text-sm uppercase font-bold" required><input type="text" name="titulo" placeholder="Título" class="border p-2 rounded text-sm" required></div>
                                <input type="text" name="descricao" placeholder="Regra" class="border p-2 rounded text-sm" required>
                                <select name="cor" class="border p-2 rounded text-sm"><option value="white">Branco</option><option value="pink">Rosa</option></select>
                                <button class="bg-pink-600 text-white py-2 rounded text-sm font-bold hover:bg-pink-700">Salvar Cupom</button>
                            </form>
                        </div>
                        <div class="overflow-x-auto">
                            <table class="w-full text-sm"><thead class="bg-gray-100"><tr><th class="p-3 text-left">Código</th><th class="p-3 text-left">Detalhes</th><th class="p-3 text-right">Ação</th></tr></thead><tbody class="divide-y"><?php if(!empty($listaCupons)): foreach($listaCupons as $c): ?><tr><td class="p-3 font-bold text-pink-600"><?= $c['codigo'] ?></td><td class="p-3"><div class="font-bold"><?= $c['titulo'] ?></div><div class="text-xs text-gray-500"><?= $c['descricao'] ?></div></td><td class="p-3 text-right"><form method="POST" onsubmit="return confirm('Excluir?');"><input type="hidden" name="acao" value="deletar_cupom"><input type="hidden" name="id_cupom" value="<?= $c['id'] ?>"><button class="text-red-500 hover:text-red-700"><i data-lucide="trash-2" class="w-4 h-4"></i></button></form></td></tr><?php endforeach; else: ?><tr><td colspan="3" class="p-4 text-center text-gray-400">Nenhum cupom ativo.</td></tr><?php endif; ?></tbody></table>
                        </div>
                    </div>
                    <div class="bg-white rounded-lg shadow overflow-hidden">
                        <div class="p-6 bg-gray-50 border-b"><h3 class="font-bold text-gray-800 flex items-center gap-2"><i data-lucide="trophy"></i> Top Afiliados</h3></div>
                        <div class="overflow-x-auto"><table class="w-full text-sm"><thead class="bg-gray-100"><tr><th class="p-3 text-left">Parceiro</th><th class="p-3 text-right">Vendas</th><th class="p-3 text-right">Saldo</th></tr></thead><tbody class="divide-y"><?php if(!empty($topAfiliados)): foreach($topAfiliados as $a): ?><tr><td class="p-3"><div class="font-bold"><?= $a['nome'] ?></div><div class="text-xs text-gray-500"><?= $a['email'] ?></div></td><td class="p-3 text-right font-medium"><?= $a['total_vendas_afiliado'] ?></td><td class="p-3 text-right font-bold text-green-600">R$ <?= number_format($a['saldo_afiliado'], 2, ',', '.') ?></td></tr><?php endforeach; else: ?><tr><td colspan="3" class="p-4 text-center text-gray-400">Nenhuma venda.</td></tr><?php endif; ?></tbody></table></div>
                    </div>
                </div>
            <?php endif; ?>

            <!-- DEMAIS PÁGINAS (Dashboard, Alunos, etc...) -->
            <?php if($page == 'dashboard'): 
                $total_vendas = $pdo->query("SELECT SUM(valor_total) FROM pedidos WHERE status IN ('aprovado', 'pago')")->fetchColumn() ?: '0.00';
                $alunos = $pdo->query("SELECT COUNT(*) FROM usuarios WHERE tipo='cliente'")->fetchColumn();
                $prods_ativos = $pdo->query("SELECT COUNT(*) FROM produtos WHERE ativo=1")->fetchColumn();
            ?>
                <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                    <div class="bg-white p-6 rounded-lg shadow border-l-4 border-[#ff0050]"><p class="text-gray-500 text-sm font-bold uppercase">Faturamento</p><h3 class="text-3xl font-bold text-gray-800">R$ <?= number_format($total_vendas, 2, ',', '.') ?></h3></div>
                    <div class="bg-white p-6 rounded-lg shadow border-l-4 border-blue-500"><p class="text-gray-500 text-sm font-bold uppercase">Alunos</p><h3 class="text-3xl font-bold text-gray-800"><?= $alunos ?></h3></div>
                    <div class="bg-white p-6 rounded-lg shadow border-l-4 border-green-500"><p class="text-gray-500 text-sm font-bold uppercase">Produtos</p><h3 class="text-3xl font-bold text-gray-800"><?= $prods_ativos ?></h3></div>
                </div>
            <?php endif; ?>

            <?php if($page == 'produtos'): ?>
                <div class="bg-white p-6 rounded-lg shadow mb-8 <?= $produto_edit ? 'border-l-4 border-yellow-400 bg-yellow-50' : '' ?>">
                    <h3 class="text-lg font-bold mb-4 text-gray-800 border-b pb-2 flex justify-between items-center">
                        <span><?= $produto_edit ? '✏️ Editando' : '✨ Novo Produto' ?></span>
                        <?php if($produto_edit): ?><a href="?page=produtos" class="text-xs bg-gray-200 px-2 py-1 rounded text-gray-600">Cancelar</a><?php endif; ?>
                    </h3>
                    <form method="POST" enctype="multipart/form-data" class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <input type="hidden" name="acao" value="salvar_produto">
                        <input type="hidden" name="id_produto" value="<?= $produto_edit['id'] ?? '' ?>">
                        <input type="hidden" name="imagem_atual" value="<?= $produto_edit['imagem_principal'] ?? '' ?>">
                        <div><label class="block text-sm font-bold text-gray-700 mb-1">Nome</label><input type="text" name="nome" value="<?= $produto_edit['nome'] ?? '' ?>" class="w-full border p-2 rounded" required></div>
                        <div><label class="block text-sm font-bold text-gray-700 mb-1">Tipo</label><select name="tipo" class="w-full border p-2 rounded"><option value="digital">Digital</option><option value="fisico">Físico</option></select></div>
                        <div class="md:col-span-2"><label class="block text-sm font-bold text-gray-700 mb-1">Descrição</label><textarea name="descricao" rows="2" class="w-full border p-2 rounded"><?= $produto_edit['descricao'] ?? '' ?></textarea></div>
                        <div><label class="block text-sm font-bold text-gray-700 mb-1">Preço "De"</label><input type="text" name="preco_de" value="<?= $produto_edit['preco_original'] ?? '' ?>" class="w-full border p-2 rounded"></div>
                        <div><label class="block text-sm font-bold text-gray-700 mb-1">Preço "Por"</label><input type="text" name="preco_por" value="<?= $produto_edit['preco_atual'] ?? '' ?>" class="w-full border p-2 rounded font-bold text-green-600" required></div>
                        
                        <div class="bg-blue-50 p-3 rounded border border-blue-200 md:col-span-2">
                            <label class="block text-sm font-bold text-blue-800 mb-1">Validade do Acesso</label>
                            <select name="validade_dias" class="w-full border p-2 rounded bg-white">
                                <?php $val = $produto_edit['validade_dias'] ?? 36500; ?>
                                <option value="7" <?= $val==7?'selected':'' ?>>Semanal (7 dias)</option>
                                <option value="30" <?= $val==30?'selected':'' ?>>Mensal (30 dias)</option>
                                <option value="90" <?= $val==90?'selected':'' ?>>Trimestral (90 dias)</option>
                                <option value="180" <?= $val==180?'selected':'' ?>>Semestral (180 dias)</option>
                                <option value="365" <?= $val==365?'selected':'' ?>>Anual (365 dias)</option>
                                <option value="36500" <?= $val>365?'selected':'' ?>>Vitalício</option>
                            </select>
                        </div>

                        <div class="md:col-span-2"><label class="block text-sm font-bold text-gray-700 mb-1">Imagem</label><input type="file" name="imagem" class="w-full text-sm"></div>
                        <button class="bg-[#ff0050] text-white py-2 px-6 rounded font-bold md:col-span-2"><?= $produto_edit ? 'Salvar' : 'Cadastrar' ?></button>
                    </form>
                </div>
                <div class="bg-white rounded shadow overflow-hidden">
                    <div class="overflow-x-auto">
                        <table class="w-full text-sm"><thead class="bg-gray-50"><tr><th class="p-3 text-left">Produto</th><th class="p-3">Preço</th><th class="p-3 text-right">Ações</th></tr></thead><tbody><?php $prods = $pdo->query("SELECT * FROM produtos ORDER BY id DESC")->fetchAll(); foreach($prods as $p): ?><tr class="border-t"><td class="p-3 flex items-center gap-2"><img src="../<?= $p['imagem_principal'] ?: 'https://placehold.co/40' ?>" class="w-8 h-8 rounded object-cover border"><?= $p['nome'] ?></td><td class="p-3 text-center">R$ <?= $p['preco_atual'] ?></td><td class="p-3 text-right flex justify-end gap-2"><a href="?page=produtos&editar=<?= $p['id'] ?>" class="text-blue-600 hover:bg-blue-100 p-1 rounded"><i data-lucide="edit"></i></a><form method="POST" onsubmit="return confirm('Excluir?');"><input type="hidden" name="acao" value="excluir_produto"><input type="hidden" name="id_excluir" value="<?= $p['id'] ?>"><button class="text-red-600 hover:bg-red-100 p-1 rounded"><i data-lucide="trash"></i></button></form></td></tr><?php endforeach; ?></tbody></table>
                    </div>
                </div>
            <?php endif; ?>

            <?php if($page == 'personalizar'): 
                $conf = $pdo->query("SELECT * FROM config_loja WHERE id=1")->fetch(); 
                $gateway = $pdo->query("SELECT * FROM config_gateway WHERE id=1")->fetch(); 
                $smtp = $pdo->query("SELECT * FROM config_smtp WHERE id=1")->fetch();
            ?>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div class="bg-white p-6 rounded shadow"><h3 class="font-bold mb-4">Loja</h3><form method="POST" enctype="multipart/form-data"><input type="hidden" name="acao" value="salvar_loja"><input type="hidden" name="logo_atual" value="<?= $conf['logo_url'] ?? '' ?>"><div><label class="block text-sm font-bold text-gray-700">Nome</label><input type="text" name="nome_loja" value="<?= $conf['nome_loja'] ?? '' ?>" class="w-full border p-2 rounded"></div><div class="mt-2"><label class="block text-sm font-bold text-gray-700">Cor</label><input type="color" name="cor_primaria" value="<?= $conf['cor_primaria'] ?? '#ff0050' ?>" class="w-full h-10 rounded cursor-pointer"></div><div class="mt-2"><label class="block text-sm font-bold text-gray-700">Logo</label><?php if(!empty($conf['logo_url'])): ?><img src="../<?= $conf['logo_url'] ?>" class="h-10 mb-2 border p-1"><?php endif; ?><input type="file" name="logo" class="w-full text-sm"></div><button class="bg-gray-800 text-white px-4 py-2 rounded w-full mt-4">Salvar</button></form></div>
                    <div class="bg-white p-6 rounded shadow"><h3 class="font-bold mb-4">API Pagamento</h3><form method="POST"><input type="hidden" name="acao" value="salvar_gateway"><div><label class="block text-sm font-bold text-gray-700">Token</label><input type="text" name="access_token" value="<?= $gateway['access_token'] ?? '' ?>" class="w-full border p-2 rounded" placeholder="sk_..."></div><button class="bg-green-600 text-white px-4 py-2 rounded w-full mt-4">Salvar Token</button></form></div>
                    <div class="bg-white p-6 rounded shadow md:col-span-2"><h3 class="font-bold mb-4 flex items-center gap-2"><i data-lucide="mail"></i> SMTP (E-mail)</h3><form method="POST" class="grid grid-cols-1 md:grid-cols-2 gap-4"><input type="hidden" name="acao" value="salvar_smtp"><div><label class="block text-sm font-bold text-gray-700">Host</label><input type="text" name="host" value="<?= $smtp['host'] ?? 'mail.seusite.com' ?>" class="w-full border p-2 rounded"></div><div><label class="block text-sm font-bold text-gray-700">Porta</label><input type="number" name="porta" value="<?= $smtp['porta'] ?? 465 ?>" class="w-full border p-2 rounded"></div><div><label class="block text-sm font-bold text-gray-700">E-mail</label><input type="email" name="email" value="<?= $smtp['email'] ?? '' ?>" class="w-full border p-2 rounded"></div><div><label class="block text-sm font-bold text-gray-700">Senha</label><input type="password" name="senha" value="<?= $smtp['senha'] ?? '' ?>" class="w-full border p-2 rounded"></div><button class="md:col-span-2 bg-blue-600 text-white py-2 rounded font-bold">Salvar SMTP</button></form></div>
                </div>
            <?php endif; ?>

            <?php if($page == 'cursos'): ?>
                <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                    <div class="bg-white p-5 rounded-lg shadow <?= $edit_curso ? 'border-2 border-yellow-400' : '' ?>">
                        <h3 class="font-bold text-gray-800 mb-3 border-b pb-2 flex justify-between"><?= $edit_curso ? '✏️ Editar Curso' : '1. Criar Curso' ?><?php if($edit_curso): ?><a href="?page=cursos" class="text-xs text-red-500">Cancelar</a><?php endif; ?></h3>
                        <form method="POST" enctype="multipart/form-data" class="space-y-3">
                            <input type="hidden" name="acao" value="salvar_curso">
                            <input type="hidden" name="curso_id" value="<?= $edit_curso['id'] ?? '' ?>">
                            <input type="hidden" name="banner_atual" value="<?= $edit_curso['imagem_banner'] ?? '' ?>">
                            <input type="hidden" name="capa_atual" value="<?= $edit_curso['imagem_capa'] ?? '' ?>">
                            <input type="text" name="nome_curso" value="<?= $edit_curso['nome'] ?? '' ?>" placeholder="Nome (ex: Método TikTok)" class="w-full border p-2 rounded text-sm" required>
                            <textarea name="desc_curso" placeholder="Descrição" class="w-full border p-2 rounded text-sm"><?= $edit_curso['descricao'] ?? '' ?></textarea>
                            <div class="bg-blue-50 p-2 rounded border border-blue-200"><label class="block text-xs font-bold text-blue-800 mb-1">Produto (Venda):</label><select name="produto_vinculo" class="w-full text-sm border p-1 rounded bg-white"><option value="">Sem vínculo (Gratuito)</option><?php $prods = $pdo->query("SELECT * FROM produtos")->fetchAll(); foreach($prods as $p) { $sel = ($edit_curso['produto_id'] ?? '') == $p['id'] ? 'selected' : ''; echo "<option value='{$p['id']}' $sel>{$p['nome']}</option>"; } ?></select></div>
                            <div class="grid grid-cols-2 gap-2"><div><label class="text-[10px] font-bold text-gray-600">Capa (Vertical)</label><input type="file" name="capa" class="text-[10px]"></div><div><label class="text-[10px] font-bold text-gray-600">Banner (Netflix)</label><input type="file" name="banner" class="text-[10px]"></div></div>
                            <button class="w-full <?= $edit_curso ? 'bg-yellow-500' : 'bg-[#ff0050]' ?> text-white py-2 rounded font-bold text-sm"><?= $edit_curso ? 'Salvar' : 'Criar' ?></button>
                        </form>
                    </div>
                    
                    <div class="bg-white p-5 rounded-lg shadow <?= $edit_modulo ? 'border-2 border-yellow-400' : '' ?>"><h3 class="font-bold text-blue-600 mb-3 border-b pb-2 flex justify-between"><?= $edit_modulo ? '✏️ Editar Módulo' : '2. Criar Módulo' ?><?php if($edit_modulo): ?><a href="?page=cursos" class="text-xs text-red-500">Cancelar</a><?php endif; ?></h3><form method="POST" class="space-y-3"><input type="hidden" name="acao" value="salvar_modulo"><input type="hidden" name="modulo_id" value="<?= $edit_modulo['id'] ?? '' ?>"><select name="curso_id" class="w-full border p-2 rounded text-sm bg-white" required><option value="">Selecione o Curso...</option><?php $cursos_list = $pdo->query("SELECT * FROM cursos ORDER BY id DESC")->fetchAll(); foreach($cursos_list as $c) { $sel = ($edit_modulo['curso_id'] ?? '') == $c['id'] ? 'selected' : ''; echo "<option value='{$c['id']}' $sel>{$c['nome']}</option>"; } ?></select><input type="text" name="nome_modulo" value="<?= $edit_modulo['nome'] ?? '' ?>" placeholder="Nome Módulo" class="w-full border p-2 rounded text-sm" required><input type="number" name="ordem_modulo" value="<?= $edit_modulo['ordem'] ?? '1' ?>" placeholder="Ordem" class="w-full border p-2 rounded text-sm"><button class="w-full <?= $edit_modulo ? 'bg-yellow-500' : 'bg-blue-600' ?> text-white py-2 rounded font-bold text-sm"><?= $edit_modulo ? 'Salvar' : 'Criar' ?></button></form></div>
                    
                    <div class="bg-white p-5 rounded-lg shadow <?= $edit_aula ? 'border-2 border-yellow-400' : '' ?>">
                        <h3 class="font-bold text-green-600 mb-3 border-b pb-2 flex justify-between"><?= $edit_aula ? '✏️ Editar Aula' : '3. Adicionar Aula' ?><?php if($edit_aula): ?><a href="?page=cursos" class="text-xs text-red-500">Cancelar</a><?php endif; ?></h3>
                        <form method="POST" enctype="multipart/form-data" class="space-y-3">
                            <input type="hidden" name="acao" value="salvar_aula">
                            <input type="hidden" name="aula_id" value="<?= $edit_aula['id'] ?? '' ?>">
                            <input type="hidden" name="material_atual" value="<?= $edit_aula['material_complementar'] ?? '' ?>">
                            
                            <select name="modulo_id" class="w-full border p-2 rounded text-sm bg-white" required>
                                <option value="">Local da Aula...</option>
                                <?php $mods_list = $pdo->query("SELECT m.id as mod_id, m.nome as mod_nome, c.nome as cur_nome FROM modulos m JOIN cursos c ON m.curso_id = c.id ORDER BY c.id DESC, m.ordem ASC")->fetchAll(); foreach($mods_list as $m) { $sel = ($edit_aula['modulo_id'] ?? '') == $m['mod_id'] ? 'selected' : ''; echo "<option value='{$m['mod_id']}' $sel>{$m['cur_nome']} > {$m['mod_nome']}</option>"; } ?>
                            </select>
                            <input type="text" name="nome_aula" value="<?= $edit_aula['nome'] ?? '' ?>" placeholder="Título" class="w-full border p-2 rounded text-sm" required>
                            
                            <div class="flex gap-2">
                                <input type="text" name="video_url" value="<?= $edit_aula['video_url'] ?? '' ?>" placeholder="Vídeo URL (YouTube/Vimeo)" class="w-2/3 border p-2 rounded text-sm">
                                <select name="formato_video" class="w-1/3 border p-2 rounded text-xs bg-white font-bold text-gray-700">
                                    <option value="paisagem" <?= ($edit_aula['formato_video'] ?? '') == 'paisagem' ? 'selected' : '' ?>>🖥️ Paisagem (16:9)</option>
                                    <option value="retrato" <?= ($edit_aula['formato_video'] ?? '') == 'retrato' ? 'selected' : '' ?>>📱 Retrato (Shorts)</option>
                                </select>
                            </div>

                            <textarea name="descricao_aula" placeholder="Descrição..." class="w-full border p-2 rounded text-sm"><?= $edit_aula['descricao_texto'] ?? '' ?></textarea>
                            
                            <div class="bg-gray-50 p-2 rounded border border-dashed border-gray-300">
                                <label class="block text-xs font-bold mb-1 text-gray-500">Arquivo/PDF:</label>
                                <?php if(!empty($edit_aula['material_complementar'])): ?><p class="text-xs text-green-600 mb-1">📎 Arquivo existe</p><?php endif; ?>
                                <input type="file" name="material" class="w-full text-xs mb-2">
                                
                                <label class="block text-xs font-bold text-blue-800 mb-1">Permissão:</label>
                                <select name="permitir_download" class="w-full border p-1 rounded text-sm bg-white">
                                    <option value="1" <?= ($edit_aula['permitir_download'] ?? 1) == 1 ? 'selected' : '' ?>>⬇️ Permitir Download</option>
                                    <option value="0" <?= ($edit_aula['permitir_download'] ?? 1) == 0 ? 'selected' : '' ?>>👀 Apenas Visualizar</option>
                                </select>
                            </div>

                            <input type="number" name="ordem_aula" value="<?= $edit_aula['ordem'] ?? '1' ?>" placeholder="Ordem" class="w-full border p-2 rounded text-sm">
                            <button class="w-full <?= $edit_aula ? 'bg-yellow-500' : 'bg-green-600' ?> text-white py-2 rounded font-bold text-sm"><?= $edit_aula ? 'Salvar' : 'Criar' ?></button>
                        </form>
                    </div>
                </div>
                <div class="mt-8 bg-white p-6 rounded shadow"><h3 class="font-bold text-gray-700 mb-4">Conteúdo Cadastrado</h3><?php foreach($cursos_list as $c): ?><details class="mb-2 border rounded group open"><summary class="bg-gray-100 p-3 font-bold cursor-pointer hover:bg-gray-200 flex justify-between items-center"><span>📚 <?= $c['nome'] ?></span><div class="flex gap-2"><a href="?page=cursos&editar_curso=<?= $c['id'] ?>" class="text-xs text-blue-600 hover:underline">Editar</a><form method="POST" onsubmit="return confirm('Excluir curso?');" style="display:inline;"><input type="hidden" name="acao" value="excluir_curso"><input type="hidden" name="id" value="<?= $c['id'] ?>"><button class="text-xs text-red-500 hover:underline">Excluir</button></form></div></summary><div class="p-4 bg-white"><?php $modulos_c = $pdo->prepare("SELECT * FROM modulos WHERE curso_id = ? ORDER BY ordem"); $modulos_c->execute([$c['id']]); foreach($modulos_c->fetchAll() as $mc): ?><div class="ml-4 mb-3 border-l-2 border-blue-200 pl-3"><div class="flex justify-between items-center mb-1"><h4 class="font-bold text-sm text-gray-600">📁 <?= $mc['nome'] ?></h4><div class="flex gap-2"><a href="?page=cursos&editar_modulo=<?= $mc['id'] ?>" class="text-[10px] text-blue-500 uppercase font-bold">Editar</a><form method="POST" onsubmit="return confirm('Excluir módulo?');" style="display:inline;"><input type="hidden" name="acao" value="excluir_modulo"><input type="hidden" name="id" value="<?= $mc['id'] ?>"><button class="text-[10px] text-red-400 uppercase font-bold">Excluir</button></form></div></div><ul class="mt-1 space-y-1"><?php $aulas_c = $pdo->prepare("SELECT * FROM aulas WHERE modulo_id = ? ORDER BY ordem"); $aulas_c->execute([$mc['id']]); foreach($aulas_c->fetchAll() as $ac): ?><li class="text-sm text-gray-500 flex items-center justify-between gap-2 p-1 hover:bg-gray-50 rounded"><div class="flex items-center gap-2"><i data-lucide="play-circle" class="w-3 h-3"></i> <?= $ac['nome'] ?><?php if($ac['material_complementar']) echo "<span class='text-[10px] bg-green-100 text-green-800 px-1 rounded'>PDF</span>"; ?><?php if(($ac['formato_video']??'') == 'retrato') echo "<span class='text-[10px] bg-purple-100 text-purple-800 px-1 rounded'>📱</span>"; ?></div><div class="flex gap-2"><a href="?page=cursos&editar_aula=<?= $ac['id'] ?>" class="text-blue-500 hover:text-blue-700"><i data-lucide="edit-2" class="w-3 h-3"></i></a><form method="POST" onsubmit="return confirm('Excluir aula?');" style="display:inline;"><input type="hidden" name="acao" value="excluir_aula"><input type="hidden" name="id" value="<?= $ac['id'] ?>"><button class="text-red-500 hover:text-red-700"><i data-lucide="trash-2" class="w-3 h-3"></i></button></form></div></li><?php endforeach; ?></ul></div><?php endforeach; ?></div></details><?php endforeach; ?></div>
            <?php endif; ?>

            <?php if($page == 'alunos'): ?>
                <div class="flex flex-col md:flex-row justify-between items-center mb-6 gap-4">
                    <div class="flex flex-col md:flex-row items-center gap-4 w-full md:w-auto">
                        <div class="bg-blue-100 text-blue-800 text-xs font-bold px-3 py-1 rounded-full whitespace-nowrap self-start md:self-auto">
                            Total: <?php echo $pdo->query("SELECT COUNT(*) FROM usuarios WHERE tipo='cliente'")->fetchColumn(); ?>
                        </div>
                        <form method="GET" class="flex w-full md:w-auto">
                            <input type="hidden" name="page" value="alunos">
                            <input type="text" name="busca" value="<?= htmlspecialchars($busca) ?>" placeholder="Buscar..." class="border p-2 rounded-l w-full md:w-64 text-sm focus:outline-none focus:border-blue-500">
                            <button class="bg-gray-200 px-4 rounded-r hover:bg-gray-300"><i data-lucide="search" class="w-4 h-4"></i></button>
                        </form>
                    </div>
                    
                    <button onclick="document.getElementById('modal-novo-aluno').classList.remove('hidden')" class="bg-[#ff0050] hover:bg-pink-700 text-white font-bold py-3 md:py-2 px-4 rounded flex items-center gap-2 shadow w-full md:w-auto justify-center text-sm">
                        <i data-lucide="plus" class="w-4 h-4"></i> Novo Aluno
                    </button>
                </div>

                <div id="modal-novo-aluno" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 px-4">
                    <div class="bg-white rounded-lg shadow-xl w-full max-w-md p-6 relative">
                        <button onclick="document.getElementById('modal-novo-aluno').classList.add('hidden')" class="absolute top-4 right-4 text-gray-400 hover:text-gray-600">✕</button>
                        <h3 class="text-xl font-bold text-gray-800 mb-4">Novo Aluno</h3>
                        <form method="POST">
                            <input type="hidden" name="acao" value="criar_aluno">
                            <div class="mb-3"><label class="block text-sm font-bold text-gray-700 mb-1">Nome Completo</label><input type="text" name="nome" class="w-full border p-2 rounded" required></div>
                            <div class="mb-3"><label class="block text-sm font-bold text-gray-700 mb-1">E-mail</label><input type="email" name="email" class="w-full border p-2 rounded" required></div>
                            <div class="mb-4"><label class="block text-sm font-bold text-gray-700 mb-1">Senha Inicial</label><input type="text" name="senha" class="w-full border p-2 rounded bg-gray-50" value="tiktok" required></div>
                            <button class="w-full bg-green-600 hover:bg-green-700 text-white font-bold py-2 rounded">Cadastrar</button>
                        </form>
                    </div>
                </div>

                <div class="bg-white rounded-lg shadow overflow-hidden">
                    <div class="overflow-x-auto">
                        <table class="w-full text-sm text-left whitespace-nowrap">
                            <thead class="bg-gray-100 text-gray-600 uppercase text-xs">
                                <tr><th class="px-6 py-3">Aluno</th><th class="px-6 py-3">Status</th><th class="px-6 py-3">Financeiro</th><th class="px-6 py-3">Cursos</th><th class="px-6 py-3 text-right">Ações</th></tr>
                            </thead>
                            <tbody class="divide-y divide-gray-200">
                                <?php 
                                $sql = "SELECT u.*, (SELECT SUM(valor_total) FROM pedidos WHERE usuario_id = u.id AND status IN ('aprovado', 'pago')) as total_gasto, (SELECT COUNT(*) FROM matriculas WHERE usuario_id = u.id) as qtd_cursos FROM usuarios u WHERE u.tipo = 'cliente'";
                                if($busca) $sql .= " AND (u.nome LIKE '%$busca%' OR u.email LIKE '%$busca%')";
                                $sql .= " ORDER BY u.id DESC";
                                $alunos = $pdo->query($sql)->fetchAll();
                                foreach($alunos as $aluno): 
                                    $ativo = ($aluno['total_gasto'] > 0);
                                ?>
                                <tr class="hover:bg-gray-50 transition">
                                    <td class="px-6 py-4">
                                        <div class="flex items-center">
                                            <div class="h-10 w-10 rounded-full bg-gray-200 flex items-center justify-center text-gray-500 font-bold mr-3"><?= strtoupper(substr($aluno['nome'], 0, 1)) ?></div>
                                            <div><div class="font-medium text-gray-900"><?= $aluno['nome'] ?></div><div class="text-xs text-gray-500"><?= $aluno['email'] ?></div></div>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4"><?= $ativo ? '<span class="px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800">Ativo</span>' : '<span class="px-2 py-1 text-xs font-semibold rounded-full bg-gray-100 text-gray-800">Lead</span>' ?></td>
                                    <td class="px-6 py-4 font-bold text-gray-700">R$ <?= number_format($aluno['total_gasto'] ?: 0, 2, ',', '.') ?></td>
                                    <td class="px-6 py-4 text-xs text-gray-500"><?= $aluno['qtd_cursos'] ?> matriculado(s)</td>
                                    <td class="px-6 py-4 text-right">
                                        <div class="flex justify-end gap-2">
                                <form method="POST" onsubmit="return confirm('Enviar dados de acesso para <?= $aluno['email'] ?>?');">
                                    <input type="hidden" name="acao" value="reenviar_acesso_manual">
                                    <input type="hidden" name="id_aluno" value="<?= $aluno['id'] ?>">
                                    <button class="text-green-600 border border-green-200 px-2 py-1 rounded hover:bg-green-50 text-xs font-bold flex items-center gap-1" title="Reenviar Acesso por E-mail">
                                        <i data-lucide="mail"></i> Reenviar
                                    </button>
                                </form>
                                
                                <button onclick="document.getElementById('modal-aluno-<?= $aluno['id'] ?>').classList.remove('hidden')" class="text-blue-600 border border-blue-200 px-2 py-1 rounded hover:bg-blue-50 text-xs font-bold">
                                    Gerenciar
                                </button>
                            </div>
                                    </td>
                                </tr>
                                <div id="modal-aluno-<?= $aluno['id'] ?>" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 px-4">
                                    <div class="bg-white rounded-lg shadow-xl w-full max-w-3xl p-6 relative max-h-[90vh] overflow-y-auto">
                                        <button onclick="document.getElementById('modal-aluno-<?= $aluno['id'] ?>').classList.add('hidden')" class="absolute top-4 right-4 text-gray-400 hover:text-gray-600">✕</button>
                                        <h3 class="text-xl font-bold text-gray-800 mb-6 flex items-center gap-2"><i data-lucide="user"></i> Gestão: <?= $aluno['nome'] ?></h3>
                                        <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
                                            <form method="POST" class="space-y-4">
                                                <input type="hidden" name="acao" value="editar_aluno"><input type="hidden" name="id_aluno" value="<?= $aluno['id'] ?>">
                                                <h4 class="text-xs font-bold text-gray-500 uppercase border-b pb-1">Dados</h4>
                                                <div><label class="block text-xs font-bold mb-1">Nome:</label><input type="text" name="nome" value="<?= $aluno['nome'] ?>" class="w-full border p-2 rounded text-sm"></div>
                                                <div><label class="block text-xs font-bold mb-1">E-mail:</label><input type="email" name="email" value="<?= $aluno['email'] ?>" class="w-full border p-2 rounded text-sm"></div>
                                                <div class="grid grid-cols-2 gap-2">
                                                    <div><label class="block text-xs font-bold mb-1">CPF:</label><input type="text" name="cpf" value="<?= $aluno['cpf'] ?>" class="w-full border p-2 rounded text-sm"></div>
                                                    <div><label class="block text-xs font-bold mb-1">Whats:</label><input type="text" name="whatsapp" value="<?= $aluno['whatsapp'] ?>" class="w-full border p-2 rounded text-sm"></div>
                                                </div>
                                                <div><label class="block text-xs font-bold mb-1 text-red-500">Alterar Senha:</label><input type="text" name="nova_senha" placeholder="Nova senha..." class="w-full border p-2 rounded text-sm bg-red-50"></div>
                                                <h4 class="text-xs font-bold text-gray-500 uppercase border-b pb-1 mt-4">Matricular</h4>
                                                <div class="flex gap-2">
                                                    <select name="curso_matricula" class="w-full border p-2 rounded text-sm bg-white">
                                                        <option value="">Selecione...</option>
                                                        <?php $cursos_all = $pdo->query("SELECT * FROM cursos")->fetchAll(); foreach($cursos_all as $ca) echo "<option value='{$ca['id']}'>{$ca['nome']}</option>"; ?>
                                                    </select>
                                                    <button class="bg-green-600 text-white px-3 py-2 rounded text-xs font-bold">Add</button>
                                                </div>
                                                <button class="w-full bg-blue-600 text-white py-2 rounded font-bold text-sm mt-4">Salvar</button>
                                            </form>
                                            <div class="space-y-6">
                                                <div>
                                                    <h4 class="text-xs font-bold text-gray-500 uppercase border-b pb-1 mb-2">Cursos</h4>
                                                    <div class="bg-gray-50 rounded border max-h-40 overflow-y-auto p-2">
                                                        <?php 
                                                        $mats = $pdo->prepare("SELECT m.id, c.nome FROM matriculas m JOIN cursos c ON m.curso_id = c.id WHERE m.usuario_id = ?");
                                                        $mats->execute([$aluno['id']]);
                                                        $mats_res = $mats->fetchAll();
                                                        if(empty($mats_res)) { echo '<p class="text-xs text-gray-400 p-2">Sem cursos.</p>'; } else {
                                                            foreach($mats_res as $m) echo "<div class='flex justify-between items-center text-xs p-2 border-b bg-white mb-1 rounded'><span class='font-bold flex items-center gap-2'><i data-lucide='check-circle' class='w-3 h-3 text-green-500'></i> {$m['nome']}</span><form method='POST' onsubmit='return confirm(\"Remover?\");'><input type='hidden' name='acao' value='remover_matricula'><input type='hidden' name='id_matricula' value='{$m['id']}'><button class='text-red-500 hover:text-red-700 font-bold px-2'>✕</button></form></div>";
                                                        }
                                                        ?>
                                                    </div>
                                                </div>
                                                <div>
                                                    <h4 class="text-xs font-bold text-gray-500 uppercase border-b pb-1 mb-2">Pedidos</h4>
                                                    <div class="bg-gray-50 rounded border max-h-48 overflow-y-auto p-2">
                                                        <?php 
                                                        $pedidos = $pdo->prepare("SELECT p.nome, ped.valor_total, ped.status, ped.data_pedido FROM pedidos ped JOIN produtos p ON ped.produto_id = p.id WHERE ped.usuario_id = ? ORDER BY ped.id DESC");
                                                        $pedidos->execute([$aluno['id']]);
                                                        $hist = $pedidos->fetchAll();
                                                        if(!$hist) echo "<p class='text-xs text-gray-400 p-2'>Vazio.</p>";
                                                        foreach($hist as $h) {
                                                            $cor = in_array($h['status'], ['aprovado','pago']) ? 'text-green-600' : 'text-yellow-600';
                                                            echo "<div class='text-xs p-2 border-b bg-white mb-1 rounded'><div class='flex justify-between font-bold'><span>{$h['nome']}</span><span class='$cor'>" . ucfirst($h['status']) . "</span></div><div class='flex justify-between text-gray-500 mt-1'><span>R$ " . number_format($h['valor_total'], 2, ',', '.') . "</span><span>".date('d/m/y', strtotime($h['data_pedido']))."</span></div></div>";
                                                        }
                                                        ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            <?php endif; ?>

            <?php if($page == 'emails'): ?>
                <?php 
                    $smtp = $pdo->query("SELECT * FROM config_smtp WHERE id=1")->fetch(); 
                    $templates = $pdo->query("SELECT * FROM email_templates")->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_UNIQUE);
                    // Busca os últimos 50 logs para o histórico
                    $logs = $pdo->query("SELECT * FROM email_logs ORDER BY id DESC LIMIT 50")->fetchAll();
                ?>
                <div class="space-y-8">
                    <div class="flex flex-wrap gap-2 border-b border-gray-200 pb-2">
                        <button onclick="openTab('history')" class="tab-btn px-4 py-2 bg-gray-200 rounded text-sm font-bold active" data-target="history">📜 Histórico de Envios</button>
                        <button onclick="openTab('manual')" class="tab-btn px-4 py-2 bg-white border rounded text-sm font-bold" data-target="manual">📨 Enviar Manual</button>
                        <button onclick="openTab('templates')" class="tab-btn px-4 py-2 bg-white border rounded text-sm font-bold" data-target="templates">🤖 Modelos Automáticos</button>
                        <button onclick="openTab('smtp')" class="tab-btn px-4 py-2 bg-white border rounded text-sm font-bold" data-target="smtp">🔌 Configuração SMTP</button>
                    </div>

                    <div id="tab-history" class="tab-content bg-white p-6 rounded-lg shadow">
                        <h3 class="font-bold mb-4 flex items-center gap-2"><i data-lucide="history"></i> Últimos E-mails Enviados</h3>
                        <div class="overflow-x-auto">
                            <table class="w-full text-sm text-left whitespace-nowrap">
                                <thead class="bg-gray-100 text-gray-600 uppercase text-xs">
                                    <tr>
                                        <th class="p-3">Data</th>
                                        <th class="p-3">Para</th>
                                        <th class="p-3">Assunto</th>
                                        <th class="p-3">Status</th>
                                        <th class="p-3 text-right">Ações</th>
                                    </tr>
                                </thead>
                                <tbody class="divide-y divide-gray-200">
                                    <?php if(empty($logs)): ?>
                                        <tr><td colspan="5" class="p-4 text-center text-gray-500">Nenhum registro encontrado.</td></tr>
                                    <?php else: foreach($logs as $log): 
                                        $statusClass = $log['status'] == 'sucesso' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800';
                                        $icon = $log['status'] == 'sucesso' ? 'check' : 'alert-triangle';
                                    ?>
                                    <tr class="hover:bg-gray-50">
                                        <td class="p-3 text-gray-500"><?= date('d/m H:i', strtotime($log['data_envio'])) ?></td>
                                        <td class="p-3 font-bold"><?= $log['destinatario'] ?></td>
                                        <td class="p-3 text-gray-600" title="<?= htmlspecialchars($log['assunto']) ?>"><?= substr($log['assunto'], 0, 30) ?>...</td>
                                        <td class="p-3">
                                            <span class="px-2 py-1 rounded-full text-xs font-bold flex items-center gap-1 w-fit <?= $statusClass ?>">
                                                <i data-lucide="<?= $icon ?>" class="w-3 h-3"></i> <?= ucfirst($log['status']) ?>
                                            </span>
                                            <?php if($log['status'] == 'erro'): ?>
                                                <p class="text-[10px] text-red-500 mt-1 max-w-xs truncate" title="<?= $log['erro_msg'] ?>"><?= $log['erro_msg'] ?></p>
                                            <?php endif; ?>
                                        </td>
                                        <td class="p-3 text-right">
                                            <form method="POST" onsubmit="return confirm('Tem certeza que deseja reenviar este e-mail para <?= $log['destinatario'] ?>?');">
                                                <input type="hidden" name="acao" value="reenviar_email_historico">
                                                <input type="hidden" name="id_log" value="<?= $log['id'] ?>">
                                                <button class="text-blue-600 hover:text-blue-800 border border-blue-200 hover:bg-blue-50 px-3 py-1 rounded text-xs font-bold transition flex items-center gap-1 ml-auto">
                                                    <i data-lucide="refresh-cw" class="w-3 h-3"></i> Reenviar
                                                </button>
                                            </form>
                                        </td>
                                    </tr>
                                    <?php endforeach; endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <div id="tab-manual" class="tab-content hidden bg-white p-6 rounded-lg shadow border-l-4 border-[#ff0050]">
                        <h3 class="font-bold mb-4 flex items-center gap-2 text-gray-700"><i data-lucide="send"></i> Disparo Manual (Broadcast)</h3>
                        <form method="POST">
                            <input type="hidden" name="acao" value="enviar_email_manual">
                            <div class="mb-4">
                                <label class="block text-sm font-bold text-gray-700 mb-1">Enviar para:</label>
                                <select name="destinatario_id" class="w-full border p-2 rounded bg-gray-50">
                                    <option value="todos">📢 TODOS OS ALUNOS (Em Massa)</option>
                                    <optgroup label="Aluno Específico">
                                        <?php $users = $pdo->query("SELECT id, nome, email FROM usuarios WHERE tipo='cliente'")->fetchAll(); 
                                        foreach($users as $u) echo "<option value='{$u['id']}'>{$u['nome']} ({$u['email']})</option>"; ?>
                                    </optgroup>
                                </select>
                            </div>
                            <div class="mb-4">
                                <label class="block text-sm font-bold text-gray-700 mb-1">Assunto:</label>
                                <input type="text" name="assunto_manual" class="w-full border p-2 rounded" placeholder="Ex: Novidade Incrível para você..." required>
                            </div>
                            <div class="mb-4">
                                <label class="block text-sm font-bold text-gray-700 mb-1">Mensagem:</label>
                                <textarea name="corpo_manual" rows="6" class="w-full border p-2 rounded" placeholder="Escreva sua mensagem aqui... Use {nome} para personalizar com o nome do aluno." required></textarea>
                            </div>
                            <button class="bg-[#ff0050] hover:bg-pink-700 text-white font-bold py-3 px-6 rounded flex items-center gap-2">
                                <i data-lucide="send" class="w-4 h-4"></i> ENVIAR AGORA
                            </button>
                        </form>
                    </div>

                    <div id="tab-templates" class="tab-content hidden bg-white p-6 rounded-lg shadow">
                        <h3 class="font-bold mb-4 flex items-center gap-2 text-gray-700"><i data-lucide="bot"></i> Modelos de E-mail Automáticos</h3>
                        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                            <form method="POST" class="bg-gray-50 p-4 rounded border">
                                <input type="hidden" name="acao" value="salvar_template">
                                <input type="hidden" name="gatilho" value="boas_vindas">
                                <h4 class="font-bold text-green-600 mb-2 text-sm">✅ Pagamento Aprovado</h4>
                                <label class="block text-xs mb-1 font-bold">Assunto:</label>
                                <input type="text" name="assunto" value="<?= $templates['boas_vindas']['assunto'] ?? 'Parabéns! Acesso Liberado 🚀' ?>" class="w-full border p-2 rounded mb-2 text-sm">
                                <label class="block text-xs mb-1 font-bold">Mensagem:</label>
                                <textarea name="corpo" rows="4" class="w-full border p-2 rounded text-sm"><?= $templates['boas_vindas']['corpo'] ?? 'Olá {nome}, seu acesso ao curso foi liberado! Link: {link}' ?></textarea>
                                <button class="w-full bg-gray-800 text-white py-1 rounded text-xs font-bold mt-2">Salvar Modelo</button>
                            </form>

                            <form method="POST" class="bg-gray-50 p-4 rounded border">
                                <input type="hidden" name="acao" value="salvar_template">
                                <input type="hidden" name="gatilho" value="recuperacao">
                                <h4 class="font-bold text-yellow-600 mb-2 text-sm">⏰ Recuperação (Carrinho)</h4>
                                <label class="block text-xs mb-1 font-bold">Assunto:</label>
                                <input type="text" name="assunto" value="<?= $templates['recuperacao']['assunto'] ?? 'Não perca sua vaga! 👀' ?>" class="w-full border p-2 rounded mb-2 text-sm">
                                <label class="block text-xs mb-1 font-bold">Mensagem:</label>
                                <textarea name="corpo" rows="4" class="w-full border p-2 rounded text-sm"><?= $templates['recuperacao']['corpo'] ?? 'Oi {nome}, finalise sua inscrição agora: {link}' ?></textarea>
                                <button class="w-full bg-gray-800 text-white py-1 rounded text-xs font-bold mt-2">Salvar Modelo</button>
                            </form>

                            <form method="POST" class="bg-gray-50 p-4 rounded border">
                                <input type="hidden" name="acao" value="salvar_template">
                                <input type="hidden" name="gatilho" value="conclusao">
                                <h4 class="font-bold text-blue-600 mb-2 text-sm">🎓 Conclusão de Curso</h4>
                                <label class="block text-xs mb-1 font-bold">Assunto:</label>
                                <input type="text" name="assunto" value="<?= $templates['conclusao']['assunto'] ?? 'Parabéns pela Conclusão!' ?>" class="w-full border p-2 rounded mb-2 text-sm">
                                <label class="block text-xs mb-1 font-bold">Mensagem:</label>
                                <textarea name="corpo" rows="4" class="w-full border p-2 rounded text-sm"><?= $templates['conclusao']['corpo'] ?? 'Parabéns {nome}, você concluiu o curso!' ?></textarea>
                                <button class="w-full bg-gray-800 text-white py-1 rounded text-xs font-bold mt-2">Salvar Modelo</button>
                            </form>
                        </div>
                        <p class="text-xs text-gray-500 mt-4">💡 <b>Variáveis disponíveis:</b> <code>{nome}</code> = Nome do Aluno, <code>{link}</code> = Link do Checkout/Curso.</p>
                    </div>

                    <div id="tab-smtp" class="tab-content hidden bg-white p-6 rounded-lg shadow">
                        <h3 class="font-bold mb-4 flex items-center gap-2 text-gray-700"><i data-lucide="server"></i> Servidor de E-mail</h3>
                        <form method="POST" class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <input type="hidden" name="acao" value="salvar_smtp">
                            <div><label class="block text-xs font-bold mb-1">Host (Servidor)</label><input type="text" name="host" value="<?= $smtp['host'] ?? 'smtp.hostinger.com' ?>" class="w-full border p-2 rounded"></div>
                            <div><label class="block text-xs font-bold mb-1">Porta</label><input type="number" name="porta" value="<?= $smtp['porta'] ?? 465 ?>" class="w-full border p-2 rounded"></div>
                            <div><label class="block text-xs font-bold mb-1">E-mail (Login)</label><input type="email" name="email" value="<?= $smtp['email'] ?? '' ?>" class="w-full border p-2 rounded"></div>
                            <div><label class="block text-xs font-bold mb-1">Senha</label><input type="password" name="senha" value="<?= $smtp['senha'] ?? '' ?>" class="w-full border p-2 rounded"></div>
                            <button class="md:col-span-2 bg-blue-600 text-white py-2 rounded font-bold hover:bg-blue-700">Salvar Conexão</button>
                        </form>
                    </div>
                </div>

                <script>
                    function openTab(tabName) {
                        document.querySelectorAll('.tab-content').forEach(el => el.classList.add('hidden'));
                        document.getElementById('tab-' + tabName).classList.remove('hidden');
                        document.querySelectorAll('.tab-btn').forEach(el => {
                            el.classList.remove('bg-gray-200', 'active');
                            el.classList.add('bg-white');
                        });
                        event.target.classList.remove('bg-white');
                        event.target.classList.add('bg-gray-200', 'active');
                    }
                </script>
            <?php endif; ?>

        </div>
    </main>

    <script>
        lucide.createIcons();
        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            const overlay = document.getElementById('sidebar-overlay');
            if (sidebar.classList.contains('-translate-x-full')) {
                sidebar.classList.remove('-translate-x-full');
                overlay.classList.remove('hidden');
            } else {
                sidebar.classList.add('-translate-x-full');
                overlay.classList.add('hidden');
            }
        }
    </script>
</body>
</html>