<?php
session_start();

// ==============================================================================
// 1. CONEXÃO E CONFIGURAÇÕES
// ==============================================================================
$paths = ['config.php', 'tiktok/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: config.php não encontrado."); }

// ==============================================================================
// 2. LÓGICA DE LOGIN / LOGOUT
// ==============================================================================
$erro_login = '';

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['acao']) && $_POST['acao'] === 'entrar') {
    $email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
    $senha = $_POST['senha'];

    $stmt = $pdo->prepare("SELECT * FROM usuarios WHERE email = ? AND tipo = 'cliente'");
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    if ($user && password_verify($senha, $user['senha'])) {
        $_SESSION['aluno_id'] = $user['id'];
        $_SESSION['aluno_nome'] = $user['nome'];

        // --- GRAVAR LOG DE ACESSO ---
        $ip = $_SERVER['REMOTE_ADDR'];
        $device = $_SERVER['HTTP_USER_AGENT'];
        try {
            $pdo->prepare("INSERT INTO logs_acesso (usuario_id, ip, dispositivo) VALUES (?, ?, ?)")->execute([$user['id'], $ip, $device]);
        } catch (Exception $e) {}

        header("Location: area_aluno.php");
        exit;
    } else {
        $erro_login = "Dados de acesso incorretos.";
    }
}

// ==============================================================================
// 3. TELA DE LOGIN (ESTILO NETFLIX DARK)
// ==============================================================================
if (!isset($_SESSION['aluno_id'])) {
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Entrar | Área de Membros</title>
    <link rel="icon" href="https://www.tiktok.com/favicon.ico" type="image/x-icon" />
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;900&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Inter', sans-serif; background-color: #000; color: #fff; }
        .login-bg { 
            background-image: linear-gradient(to bottom, rgba(0,0,0,0.5), rgba(0,0,0,0.8)), url('https://images.unsplash.com/photo-1574375927938-d5a98e8efe85?q=80&w=2069&auto=format&fit=crop');
            background-size: cover; background-position: center;
        }
    </style>
</head>
<body class="login-bg h-screen flex items-center justify-center p-4">
    <div class="w-full max-w-md bg-black/85 p-10 rounded-xl backdrop-blur-md border border-gray-800 shadow-2xl">
        <div class="text-center mb-8">
            <h1 class="text-3xl font-extrabold tracking-tight text-white mb-2">Bem-vindo</h1>
            <p class="text-gray-400 text-sm">Acesse seu conteúdo exclusivo</p>
        </div>

        <?php if($erro_login): ?>
            <div class="bg-red-500/20 text-red-200 text-sm p-3 rounded mb-6 border border-red-500/30 text-center">
                <?= $erro_login ?>
            </div>
        <?php endif; ?>

        <form method="POST" class="space-y-6">
            <input type="hidden" name="acao" value="entrar">
            <div class="space-y-1">
                <label class="text-xs font-bold text-gray-400 uppercase">E-mail</label>
                <input type="email" name="email" required class="w-full bg-[#333] border border-transparent focus:border-[#ff0050] text-white rounded p-3 outline-none transition duration-300">
            </div>
            <div class="space-y-1">
                <label class="text-xs font-bold text-gray-400 uppercase">Senha</label>
                <input type="password" name="senha" required class="w-full bg-[#333] border border-transparent focus:border-[#ff0050] text-white rounded p-3 outline-none transition duration-300">
            </div>
            <div class="flex justify-end">
            <a href="#" onclick="alert('Entre em contato com o suporte.')" class="text-xs text-gray-400 hover:text-white transition">Esqueceu a senha?</a>
            </div>
            <button class="w-full bg-[#e50914] hover:bg-[#f40612] text-white font-bold py-3 rounded transition text-lg mt-4 shadow-lg shadow-red-900/40">
                ENTRAR
            </button>
        </form>
    </div>
</body>
</html>
<?php
exit;
}

// ==============================================================================
// 4. ÁREA LOGADA & LÓGICA
// ==============================================================================
$aluno_id = $_SESSION['aluno_id'];

// A. AUTO MATRÍCULA
$sql_check = "SELECT p.id, c.id as curso_id FROM pedidos p JOIN cursos c ON c.produto_id = p.produto_id WHERE p.usuario_id = ? AND p.status = 'aprovado'";
$stmt = $pdo->prepare($sql_check);
$stmt->execute([$aluno_id]);
$compras = $stmt->fetchAll();
foreach($compras as $compra) {
    try {
        $pdo->prepare("INSERT IGNORE INTO matriculas (usuario_id, curso_id, ativo) VALUES (?, ?, 1)")->execute([$aluno_id, $compra['curso_id']]);
    } catch(Exception $e) {}
}

// B. BUSCA CURSOS
$stmt = $pdo->prepare("
    SELECT c.* FROM matriculas m 
    JOIN cursos c ON m.curso_id = c.id 
    WHERE m.usuario_id = ? AND m.ativo = 1 
    GROUP BY c.id
");
$stmt->execute([$aluno_id]);
$meus_cursos = $stmt->fetchAll();

// C. VITRINE
$ids_meus = array_column($meus_cursos, 'id');
$sql_vitrine = "SELECT * FROM cursos";
if (!empty($ids_meus)) { $ids_str = implode(',', $ids_meus); $sql_vitrine .= " WHERE id NOT IN ($ids_str)"; }
$vitrine = $pdo->query($sql_vitrine)->fetchAll();

// D. ROTEAMENTO
$curso_ativo_id = $_GET['curso'] ?? 0;
if ($curso_ativo_id == 0 && count($meus_cursos) == 1 && !isset($_GET['dashboard'])) { 
    $curso_ativo_id = $meus_cursos[0]['id']; 
}

// ==============================================================================
// 5. TELA: DASHBOARD (VITRINE)
// ==============================================================================
if ($curso_ativo_id == 0) {
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Início - 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@400;700;900&display=swap" rel="stylesheet">
    <style>
        body { background-color: #141414; color: #fff; font-family: 'Inter', sans-serif; }
        .hero-gradient { background: linear-gradient(to top, #141414 10%, transparent 100%); }
        .card-zoom:hover { transform: scale(1.05); z-index: 20; transition: transform 0.3s ease; box-shadow: 0 10px 20px rgba(0,0,0,0.8); }
    </style>
</head>
<body class="pb-20">
    <nav class="fixed w-full z-50 px-8 py-4 flex justify-between items-center transition-all duration-300 bg-gradient-to-b from-black/80 to-transparent">
        <div class="text-[#ff0050] font-black text-2xl tracking-tighter">THE<span class="text-white">LIKE</span></div>
        <div class="flex items-center gap-4">
            <a href="#" class="flex items-center gap-2 hover:bg-white/10 px-3 py-2 rounded transition">
                <div class="w-8 h-8 rounded-full bg-[#333] flex items-center justify-center font-bold text-xs text-[#ff0050] border border-[#ff0050]">
                    <?= strtoupper(substr($_SESSION['aluno_nome'],0,1)) ?>
                </div>
                <span class="text-sm font-bold hidden sm:block text-gray-200">Minha Conta</span>
            </a>
            <a href="?sair=true" class="text-sm bg-red-600 px-3 py-1 rounded hover:bg-red-700 font-bold">Sair</a>
        </div>
    </nav>

    <?php 
    $destaque = $meus_cursos[0] ?? $vitrine[0] ?? null; 
    $img_banner = !empty($destaque['imagem_banner']) ? $destaque['imagem_banner'] : 'https://images.unsplash.com/photo-1626814026160-2237a95fc5a0?q=80&w=2070&auto=format&fit=crop';
    if(strpos($img_banner, 'http') !== 0) $img_banner = '../'.$img_banner;
    ?>
    <div class="relative h-[80vh] w-full bg-cover bg-center" style="background-image: url('<?= $img_banner ?>');">
        <div class="absolute inset-0 bg-gradient-to-r from-black via-black/60 to-transparent"></div>
        <div class="absolute inset-0 hero-gradient"></div>
        <div class="relative z-10 h-full flex flex-col justify-center px-8 md:px-16 max-w-4xl">
            <?php if($destaque): ?>
                <h1 class="text-5xl md:text-7xl font-black mb-4 drop-shadow-lg leading-none"><?= $destaque['nome'] ?></h1>
                <p class="text-lg text-gray-200 mb-8 font-medium drop-shadow-md max-w-2xl line-clamp-3"><?= $destaque['descricao'] ?? 'Conteúdo exclusivo.' ?></p>
                <div class="flex gap-4">
                    <?php if(in_array($destaque['id'], $ids_meus ?? [])): ?>
                        <a href="?curso=<?= $destaque['id'] ?>" class="bg-white text-black font-bold py-3 px-8 rounded flex items-center gap-2 hover:bg-gray-200 transition text-lg"><i data-lucide="play" class="fill-current w-6 h-6"></i> Assistir</a>
                    <?php else: ?>
                        <a href="../checkout/?product_id=<?= $destaque['produto_id'] ?>" class="bg-[#e50914] text-white font-bold py-3 px-8 rounded flex items-center gap-2 hover:bg-red-700 transition text-lg"><i data-lucide="shopping-cart" class="w-6 h-6"></i> Comprar Agora</a>
                    <?php endif; ?>
                </div>
            <?php else: ?>
                <h1 class="text-5xl font-black mb-4">Bem-vindo</h1>
                <p>Nenhum curso disponível no momento.</p>
            <?php endif; ?>
        </div>
    </div>

    <?php if(count($meus_cursos) > 0): ?>
    <div class="px-8 md:px-16 -mt-20 relative z-20 mb-16">
        <h2 class="text-xl font-bold mb-4 text-white drop-shadow-md">Meus Cursos</h2>
        <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
            <?php foreach($meus_cursos as $c): 
                $img_capa = !empty($c['imagem_capa']) ? $c['imagem_capa'] : '';
                if($img_capa && strpos($img_capa, 'http') !== 0) $img_capa = '../'.$img_capa;
            ?>
            <a href="?curso=<?= $c['id'] ?>" class="block relative aspect-video bg-[#222] rounded-md overflow-hidden card-zoom cursor-pointer">
                <?php if($img_capa): ?><img src="<?= $img_capa ?>" class="w-full h-full object-cover"><?php else: ?><div class="w-full h-full bg-gradient-to-tr from-gray-800 to-gray-900 flex items-center justify-center"><span class="text-4xl">🎬</span></div><?php endif; ?>
                <div class="absolute bottom-0 left-0 right-0 p-3 bg-gradient-to-t from-black via-black/80 to-transparent"><h3 class="font-bold text-sm text-white truncate"><?= $c['nome'] ?></h3></div>
            </a>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <?php if(count($vitrine) > 0): ?>
    <div class="px-8 md:px-16 pb-20">
        <h2 class="text-xl font-bold mb-4 text-gray-400">Recomendados para você</h2>
        <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
            <?php foreach($vitrine as $v): 
                 $img_capa_v = !empty($v['imagem_capa']) ? $v['imagem_capa'] : '';
                 if($img_capa_v && strpos($img_capa_v, 'http') !== 0) $img_capa_v = '../'.$img_capa_v;
            ?>
            <div class="block relative aspect-video bg-[#222] rounded-md overflow-hidden group">
                <?php if($img_capa_v): ?><img src="<?= $img_capa_v ?>" class="w-full h-full object-cover grayscale group-hover:grayscale-0 transition duration-500"><?php else: ?><div class="w-full h-full bg-gradient-to-tr from-gray-800 to-gray-900 flex items-center justify-center"><span class="text-4xl text-gray-600">🔒</span></div><?php endif; ?>
                <div class="absolute inset-0 flex flex-col items-center justify-center bg-black/60 group-hover:bg-black/40 transition">
                    <i data-lucide="lock" class="w-8 h-8 text-gray-400 mb-2"></i>
                    <a href="../checkout/?product_id=<?= $v['produto_id'] ?>" class="bg-white text-black text-xs font-bold px-4 py-2 rounded hover:scale-105 transition">QUERO ACESSO</a>
                </div>
                <div class="absolute bottom-0 left-0 right-0 p-3"><h3 class="font-bold text-sm text-gray-300 truncate"><?= $v['nome'] ?></h3></div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>
    <script>lucide.createIcons();</script>
</body>
</html>
<?php exit; }

// ==============================================================================
// 6. PLAYER DE VÍDEO COMPLETO E LIMPO
// ==============================================================================

// 1. Busca Aulas
$stmt = $pdo->prepare("SELECT a.id, a.nome, a.modulo_id FROM aulas a JOIN modulos m ON a.modulo_id = m.id WHERE m.curso_id = ? ORDER BY m.ordem ASC, a.ordem ASC");
$stmt->execute([$curso_ativo_id]);
$todas_aulas = $stmt->fetchAll();

// 2. Define Aula Atual
$aula_atual = null;
$aula_index = 0;
if (isset($_GET['aula'])) {
    foreach($todas_aulas as $idx => $a) {
        if($a['id'] == $_GET['aula']) {
            $aula_index = $idx;
            $stmt = $pdo->prepare("SELECT * FROM aulas WHERE id = ?"); $stmt->execute([$a['id']]); $aula_atual = $stmt->fetch();
            break;
        }
    }
} else {
    if(count($todas_aulas) > 0) {
        $aula_index = 0;
        $stmt = $pdo->prepare("SELECT * FROM aulas WHERE id = ?"); $stmt->execute([$todas_aulas[0]['id']]); $aula_atual = $stmt->fetch();
    }
}

// 3. Navegação
$aula_anterior = ($aula_index > 0) ? $todas_aulas[$aula_index - 1] : null;
$aula_proxima = ($aula_index < count($todas_aulas) - 1) ? $todas_aulas[$aula_index + 1] : null;

// 4. Progresso
$stmt = $pdo->prepare("SELECT aula_id FROM progresso_aulas WHERE usuario_id = ?"); $stmt->execute([$aluno_id]);
$concluidas = $stmt->fetchAll(PDO::FETCH_COLUMN);
$total_aulas = count($todas_aulas);
$aulas_vistas = 0;
foreach($todas_aulas as $ta) { if(in_array($ta['id'], $concluidas)) $aulas_vistas++; }
$porcentagem = ($total_aulas > 0) ? round(($aulas_vistas / $total_aulas) * 100) : 0;

// 5. Modulos
$stmt = $pdo->prepare("SELECT * FROM modulos WHERE curso_id = ? ORDER BY ordem"); $stmt->execute([$curso_ativo_id]); $modulos = $stmt->fetchAll();

// 6. Comentários
$comentarios = [];
if ($aula_atual) {
    $stmt = $pdo->prepare("SELECT c.*, u.nome FROM comentarios_aulas c JOIN usuarios u ON c.usuario_id = u.id WHERE c.aula_id = ? ORDER BY c.id DESC");
    $stmt->execute([$aula_atual['id']]);
    $comentarios = $stmt->fetchAll();
}

function renderPlayer($url) {
    if (empty($url)) return '<div class="w-full h-full flex flex-col items-center justify-center text-gray-600"><i data-lucide="book-open" class="w-16 h-16 mb-4 opacity-30"></i><p>Material de Leitura</p></div>';
    if (preg_match('/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=|shorts\/)|youtu\.be\/)([^"&?\/\s]{11})/i', $url, $matches)) {
        $id = $matches[1];
        $params = "?modestbranding=1&rel=0&controls=1&showinfo=0&iv_load_policy=3&playsinline=1&enablejsapi=1&origin=https://" . $_SERVER['HTTP_HOST'];
        $embed = "https://www.youtube.com/embed/" . $id . $params;
        return '<iframe src="'.$embed.'" class="w-full h-full" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>';
    }
    if (strpos($url, 'vimeo.com') !== false) {
        preg_match('/vimeo\.com\/(?:channels\/(?:\w+\/)?|groups\/(?:[^\/]*)\/videos\/|album\/(?:\d+)\/video\/|video\/|)(\d+)/', $url, $matches);
        $id = $matches[1] ?? '';
        return '<iframe src="https://player.vimeo.com/video/'.$id.'?title=0&byline=0&portrait=0" class="w-full h-full" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe>';
    }
    if (strpos($url, '.mp4') !== false) { 
        return '<video controls class="w-full h-full bg-black"><source src="'.$url.'" type="video/mp4"></video>'; 
    }
    return '<iframe src="'.$url.'" class="w-full h-full" frameborder="0" allowfullscreen></iframe>';
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $aula_atual['nome'] ?? 'Curso' ?></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@400;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        body { background-color: #0f0f0f; color: #eee; font-family: 'Inter', sans-serif; }
        ::-webkit-scrollbar { width: 6px; }
        ::-webkit-scrollbar-track { background: #111; }
        ::-webkit-scrollbar-thumb { background: #333; border-radius: 3px; }
        .active-lesson { border-left: 3px solid #ff0050; background-color: #1f1f1f; color: #fff; }
        .rating { direction: rtl; display: inline-flex; }
        .rating input { display: none; }
        .rating label { color: #444; font-size: 24px; cursor: pointer; transition: color 0.2s; }
        .rating input:checked ~ label, .rating label:hover, .rating label:hover ~ label { color: #fbbf24; }

        /* --- ESTILOS DO MATERIAL DE APOIO E BOTÕES --- */
        .botoes-aula-grid {
            display: flex;
            flex-direction: column;
            gap: 15px;
            margin: 30px 0;
            justify-content: center;
        }
        @media(min-width: 768px) {
            .botoes-aula-grid {
                flex-direction: row;
                flex-wrap: wrap;
                align-items: center;
                gap: 20px;
            }
        }
        .btn-destaque-aula {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 12px;
            color: #ffffff !important;
            font-weight: 800;
            text-transform: uppercase;
            text-decoration: none;
            padding: 16px 24px;
            border-radius: 12px;
            background: linear-gradient(90deg, #ff0050 0%, #d60043 100%);
            box-shadow: 0 4px 15px rgba(255, 0, 80, 0.3);
            transition: all 0.3s ease;
            border: 1px solid rgba(255,255,255,0.1);
            font-size: 14px;
            width: 100%;
        }
        .btn-destaque-aula.btn-verde {
            background: linear-gradient(90deg, #25D366 0%, #128C7E 100%) !important;
            box-shadow: 0 4px 15px rgba(37, 211, 102, 0.3) !important;
        }
        @media(min-width: 768px) {
            .btn-destaque-aula {
                width: auto;
                min-width: 250px;
                flex: 1;
                max-width: 350px;
            }
        }
        .btn-destaque-aula:hover {
            transform: translateY(-4px);
            filter: brightness(1.15);
            box-shadow: 0 10px 25px rgba(0,0,0,0.5);
        }

        /* --- ESTILOS DE IMPRESSÃO (MODO PDF) --- */
        @media print {
            body { background-color: #fff !important; color: #000 !important; }
            nav, aside, .md\:hidden, #btnConcluir, .mt-10.border-t, .flex.gap-2.mb-8 { display: none !important; } /* Esconde menus, sidebar, botões */
            main { position: static; width: 100%; overflow: visible; background-color: #fff !important; }
            .max-w-6xl { max-width: none !important; padding: 0 !important; }
            .bg-black { border: 1px solid #ccc; background-color: #f0f0f0 !important; page-break-inside: avoid; }
            .text-white { color: #000 !important; }
            .text-gray-400, .text-gray-500 { color: #333 !important; }
            
            /* Melhoria do Material de Apoio na Impressão */
            .material-container { 
                border: none !important; 
                padding: 0 !important; 
                margin-top: 20px;
            }
            .material-content {
                font-size: 12pt;
                line-height: 1.6;
                color: #000;
            }
            /* Esconde botões de ação na impressão */
            .botoes-aula-grid, .btn-destaque-aula { display: none !important; }
        }
        
        /* Estilo do Container de Material (Na tela) */
        .material-paper {
            background-color: #1a1a1a;
            border: 1px solid #333;
            border-radius: 16px;
            padding: 30px;
            margin-bottom: 40px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.3);
        }
        .material-content h1, .material-content h2, .material-content h3 { color: #fff; font-weight: bold; margin-bottom: 10px; margin-top: 20px; }
        .material-content p { color: #ccc; margin-bottom: 15px; }
        .material-content ul { list-style: disc; padding-left: 20px; color: #ccc; margin-bottom: 15px; }
        .material-content a { color: #ff0050; text-decoration: underline; }
    </style>
</head>
<body class="h-screen flex flex-col md:flex-row overflow-hidden">

    <div class="md:hidden flex justify-between items-center p-4 bg-[#111] border-b border-[#222]">
        <a href="area_aluno.php?dashboard=true" class="text-gray-400"><i data-lucide="arrow-left"></i></a>
        <span class="font-bold text-sm text-white">Aula <?= $aula_index + 1 ?> / <?= $total_aulas ?></span>
        <button onclick="document.getElementById('sidebar').classList.toggle('hidden')"><i data-lucide="menu" class="text-white"></i></button>
    </div>

    <aside id="sidebar" class="hidden md:flex w-full md:w-80 bg-[#111] border-r border-[#222] flex-col shrink-0 h-full absolute md:relative z-50">
        <div class="p-4 border-b border-[#222] bg-[#111]">
            <a href="area_aluno.php?dashboard=true" class="text-xs font-bold text-gray-400 hover:text-white flex items-center gap-1 mb-4">
                <i data-lucide="chevron-left" class="w-4 h-4"></i> VOLTAR
            </a>
            <div class="flex justify-between items-end text-xs text-gray-400 mb-1">
                <span>SEU PROGRESSO</span>
                <span class="text-white font-bold"><?= $porcentagem ?>%</span>
            </div>
            <div class="w-full bg-gray-800 rounded-full h-1.5">
                <div class="bg-[#ff0050] h-1.5 rounded-full transition-all duration-500" style="width: <?= $porcentagem ?>%"></div>
            </div>
        </div>

        <div class="flex-1 overflow-y-auto">
            <?php foreach($modulos as $mod): ?>
                <div class="border-b border-[#222]">
                    <div class="px-5 py-4 bg-[#161616] text-xs font-bold text-gray-400 uppercase tracking-wide">
                        <?= $mod['nome'] ?>
                    </div>
                    <div>
                        <?php 
                        $stmt_a = $pdo->prepare("SELECT * FROM aulas WHERE modulo_id = ? ORDER BY ordem");
                        $stmt_a->execute([$mod['id']]);
                        foreach($stmt_a->fetchAll() as $a): 
                            $isActive = ($aula_atual && $aula_atual['id'] == $a['id']);
                            $isDone = in_array($a['id'], $concluidas);
                        ?>
                            <a href="?curso=<?= $curso_ativo_id ?>&aula=<?= $a['id'] ?>" class="flex items-center justify-between px-5 py-3 text-sm text-gray-400 hover:bg-[#1a1a1a] hover:text-white transition <?= $isActive ? 'active-lesson' : '' ?>">
                                <div class="flex items-center gap-3 overflow-hidden">
                                    <i data-lucide="<?= $isActive ? 'play-circle' : 'circle' ?>" class="w-4 h-4 shrink-0 <?= $isActive ? 'text-[#ff0050]' : 'text-gray-600' ?>"></i>
                                    <span class="truncate"><?= $a['nome'] ?></span>
                                </div>
                                <?php if($isDone): ?><i class="fas fa-check-circle text-[#00b341] text-xs"></i><?php endif; ?>
                            </a>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </aside>

    <main class="flex-1 bg-[#0f0f0f] overflow-y-auto w-full relative">
        <?php if($aula_atual): ?>
            <div class="max-w-6xl mx-auto p-4 md:p-8">
                
                <?php 
                    $is_retrato = ($aula_atual['formato_video'] ?? 'paisagem') === 'retrato';
                    $container_class = $is_retrato ? 'max-w-md mx-auto aspect-[9/16]' : 'aspect-video w-full';
                ?>
                <div class="<?= $container_class ?> bg-black rounded-xl overflow-hidden shadow-2xl border border-[#222] mb-6 relative transition-all">
                    <?= renderPlayer($aula_atual['video_url']) ?>
                </div>

                <div class="flex flex-col md:flex-row justify-between items-center gap-4 mb-8 border-b border-[#222] pb-6">
                    <div>
                        <span class="text-xs text-gray-500 font-bold uppercase tracking-wider">AULA <?= $aula_index + 1 ?> DE <?= $total_aulas ?></span>
                        <h1 class="text-xl md:text-2xl font-bold text-white mt-1"><?= $aula_atual['nome'] ?></h1>
                    </div>
                    
                    <div class="flex gap-2">
                        <?php if($aula_anterior): ?>
                            <a href="?curso=<?= $curso_ativo_id ?>&aula=<?= $aula_anterior['id'] ?>" class="flex items-center gap-2 bg-[#222] hover:bg-[#333] text-white px-4 py-2 rounded font-bold text-sm transition">
                                <i data-lucide="chevron-left" class="w-4 h-4"></i> Anterior
                            </a>
                        <?php endif; ?>
                        
                        <button id="btnConcluir" onclick="toggleConclusao(<?= $aula_atual['id'] ?>)" class="flex items-center gap-2 px-4 py-2 rounded-full font-bold text-sm transition <?= in_array($aula_atual['id'], $concluidas) ? 'bg-[#00b341] text-white' : 'bg-[#222] text-gray-400 hover:text-white' ?>">
                            <i class="fas fa-check"></i> <span id="txtConcluir"><?= in_array($aula_atual['id'], $concluidas) ? 'Concluída' : 'Marcar Concluída' ?></span>
                        </button>

                        <?php if($aula_proxima): ?>
                            <a href="?curso=<?= $curso_ativo_id ?>&aula=<?= $aula_proxima['id'] ?>" class="flex items-center gap-2 bg-[#ff0050] hover:bg-[#d90043] text-white px-4 py-2 rounded font-bold text-sm transition">
                                Próxima <i data-lucide="chevron-right" class="w-4 h-4"></i>
                            </a>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- ÁREA DE MATERIAL E DESCRIÇÃO MELHORADA -->
                <div class="material-paper">
                    <div class="flex justify-between items-center mb-6 border-b border-[#333] pb-4">
                        <h3 class="text-xl font-bold text-white flex items-center gap-2">
                            <i data-lucide="file-text" class="text-[#ff0050]"></i> Material de Apoio
                        </h3>
                        <a href="apostila.php?aula=<?= $aula_atual['id'] ?>" target="_blank" class="bg-[#333] hover:bg-[#444] text-white px-4 py-2 rounded-lg text-sm font-bold flex items-center gap-2 transition">
                            <i data-lucide="book-open" class="w-4 h-4"></i> Acessar Apostila
                        </a>
                    </div>

                    <div class="flex flex-col md:flex-row gap-8 mb-10">
                        <div class="flex-1 material-content">
                            <?php if(!empty($aula_atual['descricao_texto'])): ?>
                                <!-- Aqui entra o HTML que você vai colar no admin (botões, textos, etc) -->
                                <!-- Removi o nl2br para permitir HTML rico, mas trate com segurança se necessário -->
                                <?= $aula_atual['descricao_texto'] ?>
                            <?php else: ?>
                                <p class="text-gray-500 italic">Nenhum material adicional para esta aula.</p>
                            <?php endif; ?>
                        </div>
                        <?php if(!empty($aula_atual['material_complementar'])): ?>
                        <div class="shrink-0">
                            <a href="<?= $aula_atual['material_complementar'] ?>" target="_blank" class="inline-flex items-center gap-2 bg-[#1a1a1a] border border-[#333] text-white px-4 py-3 rounded-lg text-sm hover:border-[#ff0050] transition">
                                <i data-lucide="download" class="w-4 h-4 text-[#ff0050]"></i> Baixar Arquivo Anexo
                            </a>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="mt-10 border-t border-[#222] pt-8">
                    <h3 class="text-lg font-bold text-white mb-6">Dúvidas e Comentários</h3>
                    
                    <div class="bg-[#1a1a1a] p-5 rounded-xl border border-[#222] mb-8">
                        <div class="flex items-start gap-4">
                            <div class="w-10 h-10 rounded-full bg-[#333] flex items-center justify-center font-bold text-gray-500 shrink-0">
                                <?= strtoupper(substr($_SESSION['aluno_nome'],0,1)) ?>
                            </div>
                            <div class="flex-1">
                                <div class="mb-3">
                                    <p class="text-xs font-bold text-gray-400 mb-1 uppercase">Sua Avaliação</p>
                                    <div class="rating">
                                        <input type="radio" name="star" id="star5" value="5"><label for="star5">★</label>
                                        <input type="radio" name="star" id="star4" value="4"><label for="star4">★</label>
                                        <input type="radio" name="star" id="star3" value="3"><label for="star3">★</label>
                                        <input type="radio" name="star" id="star2" value="2"><label for="star2">★</label>
                                        <input type="radio" name="star" id="star1" value="1"><label for="star1">★</label>
                                    </div>
                                </div>
                                <textarea id="comentarioTexto" class="w-full bg-[#111] border border-[#333] rounded-lg p-3 text-sm text-white focus:outline-none focus:border-[#ff0050] transition resize-none" rows="3" placeholder="Escreva sua dúvida ou comentário aqui..."></textarea>
                                <div class="text-right mt-3">
                                    <button onclick="enviarComentario(<?= $aula_atual['id'] ?>)" class="bg-[#ff0050] hover:bg-[#d60043] text-white px-6 py-2 rounded-lg font-bold text-sm transition">Enviar Comentário</button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div id="listaComentarios" class="space-y-4">
                        <?php foreach($comentarios as $c): ?>
                            <div class="bg-[#161616] p-4 rounded-lg border border-[#222]">
                                <div class="flex justify-between items-start">
                                    <div class="flex items-center gap-3">
                                        <div class="w-8 h-8 rounded-full bg-[#ff0050] flex items-center justify-center font-bold text-xs text-white">
                                            <?= strtoupper(substr($c['nome'],0,1)) ?>
                                        </div>
                                        <div>
                                            <p class="text-sm font-bold text-white"><?= $c['nome'] ?></p>
                                            <div class="text-yellow-500 text-xs tracking-widest"><?= str_repeat('★', $c['nota']) ?></div>
                                        </div>
                                    </div>
                                    <span class="text-[10px] text-gray-500"><?= date('d/m/y H:i', strtotime($c['data_comentario'])) ?></span>
                                </div>
                                <p class="text-gray-300 text-sm mt-3 pl-11 leading-relaxed"><?= nl2br($c['comentario']) ?></p>
                            </div>
                        <?php endforeach; ?>
                        <?php if(empty($comentarios)): ?>
                            <p class="text-gray-500 text-sm text-center py-4" id="msgSemComentarios">Seja o primeiro a comentar nesta aula!</p>
                        <?php endif; ?>
                    </div>
                </div>

            </div>
        <?php else: ?>
            <div class="h-full flex items-center justify-center text-gray-500 flex-col"><i data-lucide="film" class="w-12 h-12 mb-4 opacity-20"></i><p>Selecione uma aula.</p></div>
        <?php endif; ?>
    </main>

    <script>
        lucide.createIcons();

        function toggleConclusao(id) {
            const btn = document.getElementById('btnConcluir');
            const txt = document.getElementById('txtConcluir');
            const isDone = txt.innerText === 'Concluída';
            
            if(isDone) {
                btn.className = "flex items-center gap-2 px-4 py-2 rounded-full font-bold text-sm transition bg-[#222] text-gray-400 hover:text-white";
                txt.innerText = "Marcar Concluída";
            } else {
                btn.className = "flex items-center gap-2 px-4 py-2 rounded-full font-bold text-sm transition bg-[#00b341] text-white";
                txt.innerText = "Concluída";
            }

            const data = new FormData();
            data.append('acao', 'toggle_conclusao');
            data.append('aula_id', id);
            
            fetch('ajax_aluno.php', { method: 'POST', body: data }).then(() => { setTimeout(() => location.reload(), 500); });
        }

        function enviarComentario(aulaId) {
            const texto = document.getElementById('comentarioTexto').value;
            const star = document.querySelector('input[name="star"]:checked');
            const nota = star ? star.value : 5;

            if(!texto.trim()) { alert("Escreva um comentário."); return; }

            const formData = new FormData();
            formData.append('acao', 'comentar');
            formData.append('aula_id', aulaId);
            formData.append('nota', nota);
            formData.append('comentario', texto);

            fetch('ajax_aluno.php', { method: 'POST', body: formData })
            .then(r => r.json())
            .then(data => {
                if(data.status === 'sucesso') {
                    const lista = document.getElementById('listaComentarios');
                    const msgVazia = document.getElementById('msgSemComentarios');
                    if(msgVazia) msgVazia.remove();
                    lista.insertAdjacentHTML('afterbegin', data.html);
                    document.getElementById('comentarioTexto').value = '';
                }
            });
        }
    </script>
</body>
</html>