<?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'];
        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="recuperar.php" 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) {
    $pdo->prepare("INSERT IGNORE INTO matriculas (usuario_id, curso_id, ativo) VALUES (?, ?, 1)")->execute([$aluno_id, $compra['curso_id']]);
}

// B. BUSCA CURSOS (COM GROUP BY PARA NÃO REPETIR)
$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 INTELIGENTE (CORRIGIDO)
$curso_ativo_id = $_GET['curso'] ?? 0;

// Só redireciona automaticamente se:
// 1. Não selecionou curso
// 2. Tem apenas 1 curso
// 3. NÃO clicou no botão "Voltar" (dashboard=true)
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">
            <span class="text-sm font-bold hidden sm:block"><?= explode(' ', $_SESSION['aluno_nome'])[0] ?></span>
            <a href="?sair=true" class="text-sm bg-red-600 px-3 py-1 rounded hover:bg-red-700">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';
    ?>
    <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="index.php?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): ?>
            <a href="?curso=<?= $c['id'] ?>" class="block relative aspect-video bg-[#222] rounded-md overflow-hidden card-zoom cursor-pointer">
                <?php if(!empty($c['imagem_capa'])): ?><img src="../<?= $c['imagem_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): ?>
            <div class="block relative aspect-video bg-[#222] rounded-md overflow-hidden opacity-80 hover:opacity-100 transition duration-300">
                <?php if(!empty($v['imagem_capa'])): ?><img src="../<?= $v['imagem_capa'] ?>" class="w-full h-full object-cover grayscale group-hover:grayscale-0 transition"><?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="index.php?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 (COM AVALIAÇÃO E COMENTÁRIOS)
// ==============================================================================

// 1. Busca todas as aulas do curso para navegação
$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. Define Próxima e Anterior
$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. Menu Lateral
$stmt = $pdo->prepare("SELECT * FROM modulos WHERE curso_id = ? ORDER BY ordem"); $stmt->execute([$curso_ativo_id]); $modulos = $stmt->fetchAll();

// 6. Busca Comentários da Aula
$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();
}

// FUNÇÃO PLAYER INTELIGENTE
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 (strpos($url, 'youtube.com') !== false || strpos($url, 'youtu.be') !== false) {
        $embed = $url;
        if (strpos($url, 'watch?v=') !== false) { parse_str(parse_url($url)['query'], $query); $embed = "https://www.youtube.com/embed/" . $query['v']; }
        elseif (strpos($url, 'youtu.be/') !== false) { $parts = explode('/', $url); $embed = "https://www.youtube.com/embed/" . end($parts); }
        return '<iframe src="'.$embed.'" class="w-full h-full" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe>';
    }
    if (strpos($url, 'vimeo.com') !== false) { $id = (int) substr(parse_url($url, PHP_URL_PATH), 1); return '<iframe src="https://player.vimeo.com/video/'.$id.'" class="w-full h-full" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe>'; }
    if (strpos($url, '.mp4') !== false || strpos($url, '.webm') !== 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" allow="autoplay; fullscreen" 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; }
        /* Estrelas */
        .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; }
    </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">
                
                <div class="aspect-video bg-black rounded-xl overflow-hidden shadow-2xl border border-[#222] mb-6 relative">
                    <?= 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>

                <div class="flex flex-col md:flex-row gap-8 mb-10">
                    <div class="flex-1">
                        <?php if(!empty($aula_atual['descricao_texto'])): ?>
                            <div class="text-gray-400 text-sm leading-relaxed prose prose-invert max-w-none">
                                <?= nl2br($aula_atual['descricao_texto']) ?>
                            </div>
                        <?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 Material
                        </a>
                    </div>
                    <?php endif; ?>
                </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>