const API_URL = '../api.php'; let allItems = []; let currentAdminTab = 'critique'; let currentPage = 1; const itemsPerPage = 12; let selectedIds = new Set(); let pendingDeleteAction = null; function getStarsHTML(rating) { const r = parseFloat(rating) || 0; const full = Math.floor(r); const hasHalf = (r - full) >= 0.5; const empty = 5 - Math.ceil(r); let html = '★'.repeat(full); if (hasHalf) html += '★'; html += `${'☆'.repeat(empty)}`; return html; } function parseCSV(text) { if (text.charCodeAt(0) === 0xFEFF) text = text.slice(1); const rows = []; let col = '', row = [], inQuotes = false; for (let i = 0; i < text.length; i++) { const c = text[i]; if (inQuotes) { if (c === '"') { if (text[i+1] === '"') { col += '"'; i++; } else inQuotes = false; } else col += c; } else { if (c === '"') inQuotes = true; else if (c === ',') { row.push(col); col = ''; } else if (c === '\n' || c === '\r') { if (c === '\r' && text[i+1] === '\n') i++; row.push(col); col = ''; if (row.length > 1 || row[0].trim() !== '') rows.push(row); row = []; } else col += c; } } if (col !== '' || row.length > 0) { row.push(col); rows.push(row); } if (rows.length === 0) return []; const headers = rows[0].map(h => h.trim()); const data = []; for (let i = 1; i < rows.length; i++) { if (rows[i].length === 1 && rows[i][0].trim() === '') continue; const obj = {}; headers.forEach((h, idx) => { obj[h] = rows[i][idx] !== undefined ? rows[i][idx] : ''; }); data.push(obj); } return data; } document.addEventListener('DOMContentLoaded', () => { loadDashboardData(); initEventListeners(); const confirmBtn = document.getElementById('confirm-btn'); if (confirmBtn) { confirmBtn.addEventListener('click', () => { if (pendingDeleteAction) pendingDeleteAction(); closeConfirmModal(); }); } }); function initEventListeners() { const filmForm = document.getElementById('film-form'); if (filmForm) filmForm.addEventListener('submit', saveFilmForm); const csvInput = document.getElementById('csv-file'); if (csvInput) { csvInput.addEventListener('change', (e) => { if (currentAdminTab === 'critique') handleCritiqueUpload(e.target); else handleVideothequeUpload(e.target); }); } const searchInput = document.getElementById('search-input'); if (searchInput) searchInput.addEventListener('input', () => { currentPage = 1; renderAdminTable(); }); const selectAll = document.getElementById('select-all-checkbox'); if (selectAll) selectAll.addEventListener('change', (e) => toggleSelectAll(e.target)); document.addEventListener('click', (e) => { if (e.target.classList.contains('modal-close') || e.target.closest('.modal-close')) { const overlay = e.target.closest('.overlay'); if (overlay) overlay.classList.remove('open'); } if (e.target.classList.contains('overlay')) e.target.classList.remove('open'); }); const physicalFilter = document.getElementById('admin-physical-checkbox'); if (physicalFilter) physicalFilter.addEventListener('change', () => { currentPage = 1; renderAdminTable(); }); } async function loadDashboardData() { try { const res = await fetch(`${API_URL}?action=get_films`, { cache: 'no-store' }); allItems = await res.json(); const secRes = await fetch(`${API_URL}?action=check_security_status`, { cache: 'no-store' }); const secData = await secRes.json(); const banner = document.getElementById('security-banner'); if (banner) banner.style.display = secData.is_blank ? 'flex' : 'none'; renderAdminTable(); } catch (err) { console.error('Erreur chargement :', err); } } function renderAdminTable() { const tbody = document.getElementById('admin-table-body'); if (!tbody) return; tbody.innerHTML = ''; const searchInput = document.getElementById('search-input'); const currentSearch = searchInput ? searchInput.value.toLowerCase() : ''; const physicalFilter = document.getElementById('admin-physical-checkbox'); let filtered = allItems.filter(item => item.type === currentAdminTab); if (physicalFilter && physicalFilter.checked) { filtered = filtered.filter(f => f.format && !['dématérialisé', 'vod', 'digital', 'streaming'].includes(f.format.toLowerCase())); } if (currentSearch) { filtered = filtered.filter(f => f.title.toLowerCase().includes(currentSearch) || (f.director && f.director.toLowerCase().includes(currentSearch))); } const countLabel = document.getElementById('admin-count-label'); if (countLabel) countLabel.textContent = `${filtered.length} élément(s)`; const totalPages = Math.ceil(filtered.length / itemsPerPage) || 1; if (currentPage > totalPages) currentPage = totalPages; const startIdx = (currentPage - 1) * itemsPerPage; const pageItems = filtered.slice(startIdx, startIdx + itemsPerPage); pageItems.forEach(f => { const tr = document.createElement('tr'); const isChecked = selectedIds.has(String(f.id)) ? 'checked' : ''; tr.innerHTML = `
Aucun élément trouvé.
'; return; } if (totalPages <= 1) return; const info = document.createElement('span'); info.className = 'pagination-info'; info.textContent = `Page ${currentPage} sur ${totalPages}`; container.appendChild(info); const prevBtn = document.createElement('button'); prevBtn.innerHTML = ''; prevBtn.disabled = currentPage === 1; prevBtn.onclick = () => { currentPage--; renderAdminTable(); }; container.appendChild(prevBtn); for (let i = 1; i <= totalPages; i++) { const btn = document.createElement('button'); btn.textContent = i; if (i === currentPage) btn.classList.add('active'); btn.onclick = () => { currentPage = i; renderAdminTable(); }; container.appendChild(btn); } const nextBtn = document.createElement('button'); nextBtn.innerHTML = ''; nextBtn.disabled = currentPage === totalPages; nextBtn.onclick = () => { currentPage++; renderAdminTable(); }; container.appendChild(nextBtn); } function showConfirmModal(actionFn) { pendingDeleteAction = actionFn; document.getElementById('confirm-modal').classList.add('open'); } function closeConfirmModal() { document.getElementById('confirm-modal').classList.remove('open'); pendingDeleteAction = null; } async function executeBulkDelete() { const ids = Array.from(selectedIds); if (ids.length === 0) return; showConfirmModal(async () => { try { await fetch(`${API_URL}?action=bulk_delete`, { method: 'POST', headers: { 'Authorization': localStorage.getItem('token'), 'Content-Type': 'application/json' }, body: JSON.stringify({ ids, type: currentAdminTab }) }); selectedIds.clear(); document.getElementById('bulk-actions-bar').style.display = 'none'; loadDashboardData(); } catch (err) { alert("Erreur serveur."); } }); } async function deleteSingleFilm(id) { showConfirmModal(async () => { try { await fetch(`${API_URL}?action=delete_film&id=${id}&type=${currentAdminTab}`, { method: 'DELETE', headers: { 'Authorization': localStorage.getItem('token') } }); loadDashboardData(); } catch (err) { alert("Erreur serveur."); } }); } function toggleFormFields() { document.getElementById('form-critique-fields').style.display = currentAdminTab === 'critique' ? 'block' : 'none'; document.getElementById('form-videotheque-fields').style.display = currentAdminTab === 'videotheque' ? 'block' : 'none'; } function switchAdminTab(tabName) { currentAdminTab = tabName; currentPage = 1; selectedIds.clear(); document.getElementById('search-input').value = ''; const physicalFilter = document.getElementById('admin-physical-checkbox'); physicalFilter.checked = false; const wrapper = document.querySelector('.physical-filter-admin'); if (wrapper) wrapper.style.display = (tabName === 'videotheque') ? 'none' : 'flex'; document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active')); document.getElementById(`btn-tab-${tabName}`).classList.add('active'); updateImportInterface(); toggleFormFields(); renderAdminTable(); } function openAddModal() { document.getElementById('film-form').reset(); document.getElementById('f-id').value = ''; toggleFormFields(); document.getElementById('admin-modal').classList.add('open'); } function openEditModal(id) { const item = allItems.find(x => String(x.id) === String(id)); if (!item) return; document.getElementById('f-id').value = item.id; document.getElementById('f-title').value = item.title; document.getElementById('f-year').value = item.year || ''; document.getElementById('f-director').value = item.director || ''; document.getElementById('f-poster').value = item.poster || ''; toggleFormFields(); if (currentAdminTab === 'critique') { document.getElementById('f-rating').value = item.rating || 3; document.getElementById('f-review').value = item.review || ''; document.getElementById('f-streaming').value = item.streaming || ''; } else { document.getElementById('f-format').value = item.format || ''; document.getElementById('f-length').value = item.length || ''; document.getElementById('f-publisher').value = item.publisher || ''; document.getElementById('f-aspect').value = item.aspect_ratio || ''; document.getElementById('f-ean').value = item.ean_isbn13 || ''; document.getElementById('f-discs').value = item.number_of_discs || 1; document.getElementById('f-description').value = item.description || ''; } document.getElementById('admin-modal').classList.add('open'); } function closeAdminModal() { document.getElementById('admin-modal').classList.remove('open'); } async function openConfigModal() { document.getElementById('config-modal').classList.add('open'); try { const res = await fetch(`${API_URL}?action=get_config_keys`, { headers: { 'Authorization': localStorage.getItem('token') } }); const data = await res.json(); document.getElementById('tmdb-key-input').value = ''; document.getElementById('tmdb-key-input').placeholder = data.tmdb_api_key ? '✅ Clé configurée (laisser vide pour garder)' : 'Entrez votre clé TMDB'; } catch(e) { console.error(e); } } function closeConfigModal() { document.getElementById('config-modal').classList.remove('open'); } function openPasswordModal() { document.getElementById('pwd-error').style.display = 'none'; document.getElementById('new-password-input').value = ''; document.getElementById('new-password-confirm').value = ''; document.getElementById('password-modal').classList.add('open'); } function closePasswordModal() { document.getElementById('password-modal').classList.remove('open'); } function logout() { localStorage.removeItem('token'); window.location.href = 'login.html'; } async function saveFilmForm(e) { e.preventDefault(); const payload = { type: currentAdminTab, id: document.getElementById('f-id').value, title: document.getElementById('f-title').value, year: document.getElementById('f-year').value, director: document.getElementById('f-director').value, poster: document.getElementById('f-poster').value, rating: document.getElementById('f-rating')?.value || '', review: document.getElementById('f-review')?.value || '', streaming: document.getElementById('f-streaming')?.value || '', format: document.getElementById('f-format')?.value || '', length: document.getElementById('f-length')?.value || '', publisher: document.getElementById('f-publisher')?.value || '', aspect_ratio: document.getElementById('f-aspect')?.value || '', ean_isbn13: document.getElementById('f-ean')?.value || '', number_of_discs: document.getElementById('f-discs')?.value || 1, description: document.getElementById('f-description')?.value || '' }; try { await fetch(`${API_URL}?action=save_film`, { method: 'POST', headers: { 'Authorization': localStorage.getItem('token'), 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }); closeAdminModal(); loadDashboardData(); } catch (err) { console.error(err); } } // ══════════════════════════════════════════════════════════════ // IMPORT CRITIQUE // ══════════════════════════════════════════════════════════════ async function handleCritiqueUpload(input) { if (!input.files || input.files.length === 0) return; let allData = []; for (const file of input.files) { try { allData = allData.concat(parseCSV(await file.text())); } catch(e) {} } if (allData.length === 0) { input.value = ''; return alert('❌ Fichier vide.'); } showImportModal(allData.length, 'critique'); let processed = 0; for (let i = 0; i < allData.length; i += 10) { const batch = allData.slice(i, i + 10); try { await fetch(`${API_URL}?action=import_batch`, { method: 'POST', headers: { 'Authorization': localStorage.getItem('token'), 'Content-Type': 'application/json' }, body: JSON.stringify({ items: batch, type: 'critique' }) }); } catch (err) { console.error(err); } processed += batch.length; updateImportModal(processed, allData.length); } input.value = ''; closeImportModal(); alert(`✅ ${allData.length} critique(s) importée(s).`); loadDashboardData(); } // ══════════════════════════════════════════════════════════════ // IMPORT VIDÉOTHÈQUE // ══════════════════════════════════════════════════════════════ async function handleVideothequeUpload(input) { if (!input.files || input.files.length === 0) return; let allData = []; for (const file of input.files) { try { allData = allData.concat(parseCSV(await file.text())); } catch(e) {} } if (allData.length === 0) { input.value = ''; return alert('❌ Fichier vide.'); } showImportModal(allData.length, 'videotheque'); let processed = 0; for (let i = 0; i < allData.length; i += 10) { const batch = allData.slice(i, i + 10); try { await fetch(`${API_URL}?action=import_batch`, { method: 'POST', headers: { 'Authorization': localStorage.getItem('token'), 'Content-Type': 'application/json' }, body: JSON.stringify({ items: batch, type: 'videotheque' }) }); } catch (err) { console.error(err); } processed += batch.length; updateImportModal(processed, allData.length); } input.value = ''; closeImportModal(); alert(`✅ ${allData.length} support(s) importé(s).`); loadDashboardData(); } function showImportModal(total, type) { document.getElementById('import-modal-title').innerHTML = type === 'critique' ? ' Import Critiques' : ' Import Vidéothèque'; document.getElementById('import-modal-desc').textContent = `Traitement de ${total} élément(s)...`; document.getElementById('import-progress-bar').style.width = '0%'; document.getElementById('import-modal-counter').textContent = '0%'; document.getElementById('import-progress-modal').classList.add('open'); } function updateImportModal(current, total) { const pct = Math.round((current / total) * 100); document.getElementById('import-progress-bar').style.width = pct + '%'; document.getElementById('import-modal-counter').textContent = `${pct}%`; } function closeImportModal() { document.getElementById('import-progress-modal').classList.remove('open'); } async function saveConfigKeys() { const keyValue = document.getElementById('tmdb-key-input').value.trim(); if (!keyValue) { closeConfigModal(); return; } try { await fetch(`${API_URL}?action=save_config`, { method: 'POST', headers: { 'Authorization': localStorage.getItem('token'), 'Content-Type': 'application/json' }, body: JSON.stringify({ key_name: 'tmdb_api_key', key_value: keyValue }) }); alert('✅ Clé sauvegardée !'); closeConfigModal(); } catch (err) { alert('Erreur serveur.'); } } async function saveNewPassword() { const pwdInput = document.getElementById('new-password-input'); const pwdConfirm = document.getElementById('new-password-confirm'); const errorMsg = document.getElementById('pwd-error'); if (pwdInput.value !== pwdConfirm.value) { errorMsg.textContent = "Les mots de passe ne correspondent pas."; errorMsg.style.display = "block"; return; } if (pwdInput.value.length < 4) { errorMsg.textContent = "4 caractères minimum."; errorMsg.style.display = "block"; return; } try { const response = await fetch(`${API_URL}?action=update_password`, { method: 'POST', headers: { 'Authorization': localStorage.getItem('token'), 'Content-Type': 'application/json' }, body: JSON.stringify({ new_password: pwdInput.value }) }); const data = await response.json(); if (data.success) { alert('Mot de passe mis à jour.'); closePasswordModal(); } } catch (err) { console.error(err); } } function updateImportInterface() { const title = document.getElementById('import-title'); const desc = document.getElementById('import-desc'); if (currentAdminTab === 'critique') { title.innerHTML = 'Importer Critiques & Notes'; desc.textContent = 'Sélectionnez vos fichiers "ratings.csv" et "reviews.csv" (Letterboxd).'; } else { title.innerHTML = 'Importer ma Vidéothèque'; desc.textContent = 'Sélectionnez vos listes CSV de supports physiques (Blu-ray, DVD, 4K).'; } }