function toggleSidebar() { document.getElementById('sidebar').classList.toggle('open'); } function showLayer(layerId) { document.querySelectorAll('.layer').forEach(layer => { layer.classList.remove('active'); }); document.getElementById('layer-' + layerId).classList.add('active'); document.body.className = ''; document.body.classList.add('theme-' + layerId); if (layerId === 'Quizz') { initQuiz(); } else if (layerId !== 'home') { fetchData(layerId); } toggleSidebar(); } const planetData = {}; const planetCols = {}; function wireSearch(planetId) { const layer = document.getElementById('layer-' + planetId); if (!layer) return; const input = layer.querySelector('.search-bar input'); if (!input) return; const fresh = input.cloneNode(true); input.parentNode.replaceChild(fresh, input); fresh.addEventListener('input', () => { filterTable(planetId, fresh.value.trim()); }); } function filterTable(planetId, query) { const tbody = document.getElementById('tbody-' + planetId); if (!tbody) return; const rows = Array.from(tbody.querySelectorAll('tr')); const cols = planetCols[planetId] || []; const data = planetData[planetId] || []; const titleIndices = cols.reduce((acc, col, i) => { const c = col.toLowerCase(); if (c === 'nom' || c === 'name' || c.includes('title') || c.includes('titre')) { acc.push(i); } return acc; }, []); const searchIndices = titleIndices.length > 0 ? titleIndices : cols.reduce((acc, col, i) => { const c = col.toLowerCase(); if (!c.includes('url') && !c.includes('desc') && !c.includes('expl') && c !== 'image' && c !== 'img') { acc.push(i); } return acc; }, []); const tokens = query.toLowerCase().split(/\s+/).filter(Boolean); const tableContainer = tbody.closest('.table-container'); const showMoreBtn = tableContainer ? tableContainer.querySelector('.show-more-btn') : null; if (tokens.length === 0) { rows.forEach((tr, index) => { tr.style.display = ''; if (data.length > 10) { if (index >= 10) tr.classList.add('hidden-row'); else tr.classList.remove('hidden-row'); } }); if (showMoreBtn) showMoreBtn.style.display = ''; return; } if (showMoreBtn) showMoreBtn.style.display = 'none'; rows.forEach((tr, index) => { const rowObj = data[index]; if (!rowObj) { tr.style.display = 'none'; return; } const haystack = searchIndices .map(i => String(rowObj[cols[i]] || '').toLowerCase()) .join(' '); const matches = tokens.every(token => haystack.includes(token)); tr.classList.remove('hidden-row'); tr.style.display = matches ? '' : 'none'; }); } async function fetchData(planetId) { const tbody = document.getElementById('tbody-' + planetId); if (!tbody) return; if (tbody.getAttribute('data-loaded') === 'true') { wireSearch(planetId); return; } tbody.innerHTML = 'Chargement des données depuis la BDD...'; try { const response = await fetch(`api.php?planet=${planetId}`); if (!response.ok) { const errorData = await response.json().catch(() => ({})); throw new Error(errorData.error || `Erreur HTTP: ${response.status}`); } const data = await response.json(); tbody.innerHTML = ''; if (data.length === 0) { tbody.innerHTML = 'Aucune donnée disponible pour le moment.'; return; } const columns = Object.keys(data[0]).filter(col => col.toLowerCase() !== 'copyright'); planetData[planetId] = data; planetCols[planetId] = columns; const thead = tbody.parentElement.querySelector('thead'); thead.innerHTML = '' + columns.map(col => { const colLower = col.toLowerCase(); const isDesc = colLower.includes('desc') || colLower.includes('expl'); const isUrl = colLower.includes('url') || colLower === 'image' || colLower === 'img'; let className = ''; if (isDesc) className = ' class="col-desc"'; else if (isUrl) className = ' class="col-url"'; return `${col.toUpperCase()}`; }).join('') + ''; data.forEach((row, index) => { const tr = document.createElement('tr'); if (index >= 10) tr.classList.add('hidden-row'); let rowHtml = ''; columns.forEach(col => { const colLower = col.toLowerCase(); if (colLower.includes('url') || colLower === 'image' || colLower === 'img') { const url = row[col]; if (url && url.trim() !== '') { rowHtml += ` ${url} `; } else { rowHtml += `N/A`; } } else if (colLower.includes('desc') || colLower.includes('expl')) { const text = row[col] || ''; let fontSizeStyle = ''; if (text.length > 200) fontSizeStyle = ' font-size: 0.75rem;'; else if (text.length > 100) fontSizeStyle = ' font-size: 0.85rem;'; rowHtml += `${text}`; } else { rowHtml += `${row[col]}`; } }); tr.innerHTML = rowHtml; tbody.appendChild(tr); }); const tableContainer = tbody.closest('.table-container'); const existingBtn = tableContainer.querySelector('.show-more-btn'); if (existingBtn) existingBtn.remove(); if (data.length > 10) { const btn = document.createElement('button'); btn.innerHTML = 'Voir la suite ⬇'; btn.className = 'show-more-btn'; btn.onclick = () => { tbody.querySelectorAll('.hidden-row').forEach(row => row.classList.remove('hidden-row')); btn.remove(); }; tableContainer.appendChild(btn); } tbody.setAttribute('data-loaded', 'true'); wireSearch(planetId); } catch (error) { console.error("Erreur de connexion à la BDD :", error); tbody.innerHTML = `Erreur technique : ${error.message}`; } } let quizQuestions = []; let currentQuizIndex = 0; let quizScore = 0; async function initQuiz() { currentQuizIndex = 0; quizScore = 0; document.getElementById('quiz-restart-btn').style.display = 'none'; document.getElementById('quiz-score').textContent = ''; if (quizQuestions.length === 0) { document.getElementById('quiz-question').textContent = "Chargement du Quizz du jour..."; document.getElementById('quiz-options').innerHTML = ''; try { const response = await fetch(`api.php?planet=quizz`); if (!response.ok) { let errMsg = "Erreur réseau"; try { const errData = await response.json(); if (errData.error) errMsg = errData.error; } catch (e) {} throw new Error(errMsg); } quizQuestions = await response.json(); if (quizQuestions.length === 0) { document.getElementById('quiz-question').textContent = "Pas assez de données dans la base pour générer un quizz."; return; } } catch (error) { console.error("Erreur Quizz:", error); document.getElementById('quiz-question').textContent = "Erreur : " + error.message; return; } } showQuizQuestion(); } function showQuizQuestion() { if (currentQuizIndex >= quizQuestions.length) { document.getElementById('quiz-question').textContent = "Quizz du jour terminé !"; document.getElementById('quiz-options').innerHTML = ""; document.getElementById('quiz-score').textContent = `Votre score : ${quizScore} / ${quizQuestions.length}`; document.getElementById('quiz-restart-btn').style.display = 'inline-block'; return; } const qObj = quizQuestions[currentQuizIndex]; document.getElementById('quiz-question').innerText = `Question ${currentQuizIndex + 1}/${quizQuestions.length} :\n\n${qObj.q}`; const optionsContainer = document.getElementById('quiz-options'); optionsContainer.innerHTML = ''; qObj.options.forEach(opt => { const btn = document.createElement('button'); btn.className = 'quiz-btn'; btn.textContent = opt; btn.onclick = () => checkAnswer(opt, qObj.a, btn); optionsContainer.appendChild(btn); }); } function checkAnswer(selected, correct, btn) { const optionsContainer = document.getElementById('quiz-options'); const buttons = optionsContainer.querySelectorAll('.quiz-btn'); buttons.forEach(b => { b.disabled = true; b.style.cursor = 'default'; }); if (selected === correct) { btn.style.backgroundColor = 'rgba(74, 222, 128, 0.4)'; btn.style.borderColor = '#4ade80'; btn.style.color = '#fff'; quizScore++; } else { btn.style.backgroundColor = 'rgba(248, 113, 113, 0.4)'; btn.style.borderColor = '#f87171'; btn.style.color = '#fff'; buttons.forEach(b => { if (b.textContent === correct) { b.style.backgroundColor = 'rgba(74, 222, 128, 0.4)'; b.style.borderColor = '#4ade80'; b.style.color = '#fff'; } }); } setTimeout(() => { currentQuizIndex++; showQuizQuestion(); }, 1500); }