<?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."); }

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

if (isset($_GET['sair'])) { 
    session_destroy(); 
    header("Location: ../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') {

    // --- CONFIGURAÇÕES (SMTP, LOJA, GATEWAY) ---
    
    // Salvar SMTP (E-mail)
    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 de E-mail (SMTP) salvas com sucesso!";
    }

    // Salvar Loja
    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 = "Configurações da loja salvas!";
    }

    // Salvar Gateway
    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 = "Chave API do Gateway salva!";
    }

    // --- 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 = "Erro: Este e-mail já está 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 cadastrado com sucesso!";
        }
    }

    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 = "Dados do aluno atualizados! ";

        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]);
            $msg .= "Senha alterada! ";
        }
        
        // Matrícula Manual
        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]);
                $msg .= " Acesso ao curso liberado!";
            }
        }
    }

    if (isset($_POST['acao']) && $_POST['acao'] == 'remover_matricula') {
        $stmt = $pdo->prepare("DELETE FROM matriculas WHERE id = ?");
        $stmt->execute([$_POST['id_matricula']]);
        $msg = "Acesso ao curso removido com sucesso.";
    }

    // --- 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 com sucesso!";
        } 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 com sucesso!";
        }
    }
    
    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!";
    }

    // --- AULAS (ATUALIZADO COM PERMISSÃO DE DOWNLOAD) ---
    if (isset($_POST['acao']) && $_POST['acao'] == 'salvar_aula') {
        $id = $_POST['aula_id'] ?? '';
        $link_material = $_POST['material_atual'] ?? '';
        // NOVO: Captura a permissão
        $permitir_dl = $_POST['permitir_download'] ?? 1;
        
        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) {
            // NOVO: Adicionei 'permitir_download' no UPDATE
            $stmt = $pdo->prepare("UPDATE aulas SET modulo_id=?, nome=?, video_url=?, descricao_texto=?, material_complementar=?, ordem=?, permitir_download=? WHERE id=?");
            $stmt->execute([$_POST['modulo_id'], $_POST['nome_aula'], $_POST['video_url'], $_POST['descricao_aula'], $link_material, $_POST['ordem_aula'], $permitir_dl, $id]);
            $msg = "Aula atualizada!";
        } else {
            // NOVO: Adicionei 'permitir_download' no INSERT
            $stmt = $pdo->prepare("INSERT INTO aulas (modulo_id, nome, video_url, descricao_texto, material_complementar, ordem, permitir_download) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$_POST['modulo_id'], $_POST['nome_aula'], $_POST['video_url'], $_POST['descricao_aula'], $link_material, $_POST['ordem_aula'], $permitir_dl]);
            $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 - Profissional</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; }</style>
</head>
<body class="bg-gray-100 flex h-screen overflow-hidden">

    <aside class="w-64 bg-[#1e1e1e] text-white flex flex-col shadow-2xl shrink-0">
        <div class="h-16 flex items-center justify-center border-b border-gray-700">
            <h2 class="text-xl font-bold tracking-wider">Jone<span class="text-[#ff0050]">Admin</span></h2>
        </div>
        <nav class="flex-1 px-2 py-4 space-y-2">
            <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>
            <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=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> Configurações
            </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 do Painel
            </a>
        </div>
    </aside>

    <main class="flex-1 overflow-y-auto p-8">
        
        <header class="flex justify-between items-center mb-8">
            <h1 class="text-3xl font-bold text-gray-800 capitalize"><?= ucfirst($page) ?></h1>
        </header>

        <?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">
                <i data-lucide="check-circle" class="mr-2"></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">
                <i data-lucide="alert-circle" class="mr-2"></i> <?= $erro ?>
            </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 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">
                        Total: <?php echo $pdo->query("SELECT COUNT(*) FROM usuarios WHERE tipo='cliente'")->fetchColumn(); ?>
                    </div>
                    <form method="GET" class="flex w-full">
                        <input type="hidden" name="page" value="alunos">
                        <input type="text" name="busca" value="<?= htmlspecialchars($busca) ?>" placeholder="Buscar por nome ou email..." 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-2 px-4 rounded flex items-center gap-2 shadow w-full md:w-auto justify-center">
                    <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">
                <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 placeholder="Ex: João Silva"></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 placeholder="joao@email.com"></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><p class="text-xs text-gray-500 mt-1">O aluno poderá mudar depois.</p></div>
                        <button class="w-full bg-green-600 hover:bg-green-700 text-white font-bold py-2 rounded">Cadastrar Aluno</button>
                    </form>
                </div>
            </div>

            <div class="bg-white rounded-lg shadow overflow-hidden">
                <table class="w-full text-sm text-left">
                    <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">
                                <button onclick="document.getElementById('modal-aluno-<?= $aluno['id'] ?>').classList.remove('hidden')" class="text-blue-600 hover:text-blue-900 font-bold text-xs border border-blue-200 px-3 py-1 rounded hover:bg-blue-50 transition">Gerenciar</button>
                            </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">
                            <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 do Aluno: <?= $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 Pessoais</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">WhatsApp:</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 (Opcional):</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">Liberar Acesso Manual</h4>
                                        <div class="flex gap-2">
                                            <select name="curso_matricula" class="w-full border p-2 rounded text-sm bg-white">
                                                <option value="">Selecione o Curso...</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 whitespace-nowrap">Adicionar +</button>
                                        </div>
                                        <button class="w-full bg-blue-600 text-white py-2 rounded font-bold text-sm mt-4">Salvar Alterações</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 Liberados</h4>
                                            <div class="bg-gray-50 rounded border max-h-40 overflow-y-auto p-2">
                                                <?php 
                                                $matriculas = $pdo->prepare("SELECT m.id, c.nome FROM matriculas m JOIN cursos c ON m.curso_id = c.id WHERE m.usuario_id = ?");
                                                $matriculas->execute([$aluno['id']]);
                                                $mats = $matriculas->fetchAll();
                                                if(empty($mats)) { echo '<p class="text-xs text-gray-400 p-2">Sem cursos liberados.</p>'; } else {
                                                    foreach($mats as $m) {
                                                        echo "<div class='flex justify-between items-center text-xs p-2 border-b last:border-0 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 acesso?\");'><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">Histórico de Pedidos</h4>
                                            <div class="bg-gray-50 rounded border max-h-48 overflow-y-auto p-2">
                                                <?php 
                                                $compras = $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");
                                                $compras->execute([$aluno['id']]);
                                                $historico = $compras->fetchAll();
                                                if(!$historico) echo "<p class='text-xs text-gray-400 p-2'>Nenhuma compra.</p>";
                                                foreach($historico as $h) {
                                                    $cor = in_array($h['status'], ['aprovado','pago']) ? 'text-green-600' : 'text-yellow-600';
                                                    $data = date('d/m/y', strtotime($h['data_pedido']));
                                                    echo "<div class='text-xs p-2 border-b last:border-0 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>$data</span></div></div>";
                                                }
                                                ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>

        <?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 Total</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 Ativos</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 à Venda</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: ' . $produto_edit['nome'] : '✨ Cadastrar 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 Edição</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="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 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 (Para sempre)</option>
                        </select>
                    </div>

                    <div class="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 col-span-2"><?= $produto_edit ? 'Salvar Alterações' : 'Cadastrar' ?></button>
                </form>
            </div>
            <div class="bg-white rounded shadow overflow-hidden">
                <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>
        <?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 da Loja</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 Principal</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 Loja</button></form></div>
                <div class="bg-white p-6 rounded shadow"><h3 class="font-bold mb-4">TheLikePay API</h3><form method="POST"><input type="hidden" name="acao" value="salvar_gateway"><div><label class="block text-sm font-bold text-gray-700">API Key (Access 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 col-span-1 md:col-span-2"><h3 class="font-bold mb-4 flex items-center gap-2"><i data-lucide="mail"></i> Configurar E-mail (SMTP)</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">Servidor SMTP</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 de Envio</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 do E-mail</label><input type="password" name="senha" value="<?= $smtp['senha'] ?? '' ?>" class="w-full border p-2 rounded"></div><button class="col-span-1 md:col-span-2 bg-blue-600 text-white py-2 rounded font-bold">Salvar Configurações de E-mail</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">Vincular ao 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><input type="text" name="video_url" value="<?= $edit_aula['video_url'] ?? '' ?>" placeholder="Vídeo URL" class="w-full border p-2 rounded text-sm"><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">Gerenciar Conteúdo</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>"; ?></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; ?>

    </main>
    <script>lucide.createIcons();</script>
</body>
</html>