<?php
require_once 'config/db.php';
require_once 'includes/auth.php';
require_once 'includes/functions.php';

requireLogin();

$course_id = $_GET['id'] ?? 1;
$stmt = $pdo->prepare("SELECT * FROM cursos WHERE id = ?");
$stmt->execute([$course_id]);
$curso = $stmt->fetch();

if (!$curso) {
    header("Location: index.php");
    exit;
}

$categories = getCategoriesWithProgress($course_id, $pdo);
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $curso['nome']; ?> - MEC Command Center</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://unpkg.com/lucide@latest"></script>
    <!-- Quill Editor -->
    <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
    <script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
    
    <!-- Jspreadsheet CE -->
    <script src="https://bossanova.uk/jspreadsheet/v4/jexcel.js"></script>
    <link rel="stylesheet" href="https://bossanova.uk/jspreadsheet/v4/jexcel.css" type="text/css" />
    <script src="https://jsuites.net/v4/jsuites.js"></script>
    <link rel="stylesheet" href="https://jsuites.net/v4/jsuites.css" type="text/css" />
    
    <style>
        body { font-family: 'Inter', sans-serif; background-color: #f8fafc; }
        .sidebar-active { background-color: <?php echo $curso['cor_tema']; ?>10; color: <?php echo $curso['cor_tema']; ?>; border-right: 4px solid <?php echo $curso['cor_tema']; ?>; }
        .card-tile:hover { transform: translateY(-5px); box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.05), 0 10px 10px -5px rgba(0, 0, 0, 0.02); }
    </style>
</head>
<body class="text-slate-800 flex h-screen overflow-hidden">

    <!-- Sidebar -->
    <aside class="w-64 bg-white border-r border-slate-200 hidden md:flex flex-col">
        <div class="h-16 flex items-center px-6 border-b border-slate-100">
            <div class="w-8 h-8 rounded-lg flex items-center justify-center text-white mr-3" style="background-color: <?php echo $curso['cor_tema']; ?>;">
                <i data-lucide="shield-check" class="w-5 h-5"></i>
            </div>
            <span class="font-bold text-slate-800">MEC Center</span>
        </div>
        <nav class="flex-1 p-4 space-y-1">
            <a href="index.php" class="flex items-center px-4 py-3 text-slate-600 hover:bg-slate-50 rounded-xl transition-colors">
                <i data-lucide="layout-dashboard" class="w-5 h-5 mr-3"></i> Dashboard Geral
            </a>
            <div class="pt-4 pb-2 px-4 text-xs font-bold text-slate-400 uppercase tracking-widest">Cursos</div>
            <?php 
            $all_cursos = getCursos($pdo);
            foreach ($all_cursos as $c): 
            ?>
            <a href="curso.php?id=<?php echo $c['id']; ?>" class="flex items-center px-4 py-3 rounded-xl transition-all <?php echo $c['id'] == $course_id ? 'sidebar-active font-semibold' : 'text-slate-600 hover:bg-slate-50'; ?>">
                <i data-lucide="graduation-cap" class="w-5 h-5 mr-3"></i> <?php echo $c['nome']; ?>
            </a>
            <?php endforeach; ?>

            <?php if (isAdmin()): ?>
            <div class="pt-4 pb-2 px-4 text-xs font-bold text-slate-400 uppercase tracking-widest">Sistema</div>
            <a href="admin.php" class="flex items-center px-4 py-3 text-slate-600 hover:bg-slate-50 rounded-xl transition-colors">
                <i data-lucide="settings" class="w-5 h-5 mr-3"></i> Administração
            </a>
            <?php endif; ?>
        </nav>
        <div class="p-4 border-t border-slate-100">
            <div class="flex items-center p-2 rounded-xl bg-slate-50">
                <div class="w-8 h-8 rounded-full bg-slate-200 flex items-center justify-center font-bold text-xs text-slate-600">
                    <?php echo substr($_SESSION['user_nome'], 0, 2); ?>
                </div>
                <div class="ml-3 overflow-hidden">
                    <p class="text-xs font-bold text-slate-800 truncate"><?php echo $_SESSION['user_nome']; ?></p>
                    <p class="text-[10px] text-slate-500 uppercase"><?php echo $_SESSION['user_role']; ?></p>
                </div>
            </div>
        </div>
    </aside>

    <!-- Main Content -->
    <main class="flex-1 flex flex-col overflow-hidden">
        <header class="h-16 bg-white/80 backdrop-blur-md border-b border-slate-200 flex items-center justify-between px-8">
            <div class="flex items-center">
                <button class="md:hidden mr-4 p-2 text-slate-600">
                    <i data-lucide="menu" class="w-6 h-6"></i>
                </button>
                <div>
                    <h1 class="text-lg font-bold text-slate-800"><?php echo $curso['nome']; ?></h1>
                    <p class="text-xs text-slate-500"><?php echo $curso['campus']; ?> • Ciclo de Avaliação 2026</p>
                </div>
            </div>
            <div class="flex items-center space-x-3">
                <div class="px-3 py-1 bg-green-50 text-green-600 rounded-full text-xs font-bold border border-green-100">
                    Ativo
                </div>
            </div>
        </header>

        <div class="flex-1 overflow-y-auto p-8 bg-slate-50/50">
            <div class="max-w-6xl mx-auto">
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    <?php foreach ($categories as $cat): ?>
                    <button onclick="openCategory(<?php echo $cat['id']; ?>)" 
                        class="card-tile text-left bg-white p-6 rounded-3xl border border-slate-200 transition-all duration-300">
                        <div class="flex justify-between items-start mb-4">
                            <div class="w-12 h-12 rounded-2xl flex items-center justify-center" style="background-color: <?php echo $curso['cor_tema']; ?>15; color: <?php echo $curso['cor_tema']; ?>;">
                                <i data-lucide="<?php echo $cat['icone']; ?>" class="w-6 h-6"></i>
                            </div>
                            <span class="text-sm font-bold" style="color: <?php echo $curso['cor_tema']; ?>;"><?php echo $cat['progress']; ?>%</span>
                        </div>
                        <h3 class="text-lg font-bold text-slate-800 mb-1"><?php echo $cat['nome']; ?></h3>
                        <p class="text-xs text-slate-400 mb-4"><?php echo $cat['prontos']; ?> de <?php echo $cat['total_itens']; ?> itens concluídos</p>
                        
                        <!-- Mini Progress Bar -->
                        <div class="w-full h-2 bg-slate-100 rounded-full overflow-hidden">
                            <div class="h-full" style="width: <?php echo $cat['progress']; ?>%; background-color: <?php echo $curso['cor_tema']; ?>;"></div>
                        </div>
                    </button>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </main>

    <!-- Modal Placeholder (JS will fill this) -->
    <div id="modal-container" class="fixed inset-0 z-50 hidden flex items-center justify-center p-4 bg-slate-900/40 backdrop-blur-sm">
        <div id="modal-content" class="bg-white w-full max-w-4xl max-h-[90vh] rounded-3xl shadow-2xl overflow-hidden flex flex-col scale-95 transition-transform duration-300">
            <!-- Dynamic Content -->
        </div>
    </div>

    <script>
        lucide.createIcons();

        function openCategory(catId) {
            const container = document.getElementById('modal-container');
            const content = document.getElementById('modal-content');
            
            container.classList.remove('hidden');
            setTimeout(() => content.classList.remove('scale-95'), 10);

            fetch(`ajax_handler.php?action=get_category_details&cat_id=${catId}&course_id=<?php echo $course_id; ?>`)
                .then(r => r.text())
                .then(html => {
                    content.innerHTML = html;
                    lucide.createIcons();
                });
        }

        function editItem(itemId) {
            const content = document.getElementById('modal-content');
            fetch(`ajax_handler.php?action=get_item_editor&item_id=${itemId}&course_id=<?php echo $course_id; ?>`)
                .then(r => r.text())
                .then(html => {
                    content.innerHTML = html;
                    lucide.createIcons();
                });
        }

        function saveItem(itemId) {
            const status = document.getElementById('item-status').value;
            let conteudo = '';
            
            const editor = document.querySelector('.ql-editor');
            if (editor) {
                conteudo = editor.innerHTML;
            } else if (window.mySpreadsheet) {
                conteudo = JSON.stringify(window.mySpreadsheet.getData());
            }

            fetch('ajax_handler.php?action=save_item', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    item_id: itemId,
                    course_id: <?php echo $course_id; ?>,
                    status: status,
                    conteudo: conteudo
                })
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    alert('Alterações salvas com sucesso!');
                }
            });
        }

        function handleFileUpload(itemId) {
            const fileInput = document.getElementById('item-file');
            if (fileInput.files.length === 0) return;

            const formData = new FormData();
            formData.append('file', fileInput.files[0]);
            formData.append('item_id', itemId);
            formData.append('course_id', <?php echo $course_id; ?>);

            const fileList = document.getElementById('file-list');
            fileList.innerHTML = '<div class="animate-pulse">Enviando...</div>';

            fetch('ajax_handler.php?action=upload_file', {
                method: 'POST',
                body: formData
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    fileList.innerHTML = `<div class="flex items-center text-green-600 font-bold"><i data-lucide="check" class="w-3 h-3 mr-1"></i> ${data.filename} enviado!</div>`;
                    lucide.createIcons();
                } else {
                    alert('Erro: ' + data.error);
                    fileList.innerHTML = 'Erro no envio.';
                }
            });
        }

        function deleteFile(fileId, itemId) {
            if (!confirm('Tem certeza que deseja excluir este arquivo? Esta ação não pode ser desfeita.')) return;

            fetch('ajax_handler.php?action=delete_file', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ file_id: fileId })
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    editItem(itemId); // Recarrega a tela de edição do item
                } else {
                    alert('Erro ao excluir: ' + data.error);
                }
            });
        }

        function closeModal() {
            const container = document.getElementById('modal-container');
            const content = document.getElementById('modal-content');
            content.classList.add('scale-95');
            setTimeout(() => container.classList.add('hidden'), 200);
        }

        // Close on escape
        window.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') closeModal();
        });
    </script>
</body>
</html>
