Files
mon-petit-cinema/js/admin.js
T
2026-07-01 17:01:14 +02:00

595 lines
26 KiB
JavaScript

const API_URL = '../api.php';
let dataStore = { critiques: [], videotheque: [] };
let currentAdminTab = 'critique';
let currentPage = 1;
const itemsPerPage = 12;
let selectedIds = new Set();
let pendingDeleteAction = null;
function getStarsHTML(rating) {
let r = parseFloat(String(rating).replace(',', '.')) || 0;
r = Math.min(Math.max(r, 0), 5);
const full = Math.floor(r);
const hasHalf = (r - full) >= 0.5;
const empty = Math.max(0, 5 - Math.ceil(r));
let html = '★'.repeat(full);
if (hasHalf) html += '<span class="half-star">★</span>';
html += `<span class="stars-muted">${'☆'.repeat(empty)}</span>`;
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();
updateImportInterface();
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' });
const data = await res.json(); // Reçoit {critiques: [...], videotheque: [...]}
dataStore = data;
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');
// On prend directement la bonne liste dans dataStore
let filtered = dataStore[currentAdminTab] || [];
if (physicalFilter && physicalFilter.checked && currentAdminTab === 'critique') {
filtered = filtered.filter(f => f.streaming && f.streaming.toLowerCase().includes('support physique'));
}
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 = `
<td style="text-align:center;"><input type="checkbox" class="film-checkbox" value="${f.id}" ${isChecked} onclick="toggleSingleSelect('${f.id}', this)"></td>
<td style="text-align:center;">${f.poster ? `<img src="${f.poster}" class="thumb" alt="Affiche">` : '<div class="thumb-ph"><i class="ti ti-photo"></i></div>'}</td>
<td><strong>${f.title}</strong></td>
<td>${f.year || '-'}</td>
<td>${f.director || '-'}</td>
<td>${currentAdminTab === 'critique' ? `<span class="tbl-stars">${getStarsHTML(f.rating)}</span>` : `<span class="badge-format">${f.format || '-'}</span>`}</td>
<td>
<div class="tbl-actions">
<button onclick="openEditModal('${f.id}')" title="Éditer"><i class="ti ti-edit"></i></button>
<button class="del" onclick="deleteSingleFilm('${f.id}')" title="Supprimer"><i class="ti ti-trash"></i></button>
</div>
</td>`;
tbody.appendChild(tr);
});
renderPagination(totalPages, filtered.length);
const selectAll = document.getElementById('select-all-checkbox');
if (selectAll) selectAll.checked = pageItems.length > 0 && pageItems.every(f => selectedIds.has(String(f.id)));
}
function toggleSingleSelect(id, checkbox) {
if (checkbox.checked) selectedIds.add(String(id));
else selectedIds.delete(String(id));
updateBulkBar();
}
function toggleSelectAll(source) {
const filtered = dataStore[currentAdminTab] || [];
if (source.checked) filtered.forEach(f => selectedIds.add(String(f.id)));
else filtered.forEach(f => selectedIds.delete(String(f.id)));
document.querySelectorAll('.film-checkbox').forEach(cb => { cb.checked = selectedIds.has(cb.value); });
updateBulkBar();
}
function updateBulkBar() {
const bulkBar = document.getElementById('bulk-actions-bar');
const bulkCount = document.getElementById('bulk-count');
if (selectedIds.size > 0) {
if (bulkBar) bulkBar.style.display = 'flex';
if (bulkCount) bulkCount.textContent = selectedIds.size;
} else {
if (bulkBar) bulkBar.style.display = 'none';
const selectAll = document.getElementById('select-all-checkbox');
if (selectAll) selectAll.checked = false;
}
}
function renderPagination(totalPages, totalItems) {
const container = document.getElementById('pagination-container');
if (!container) return;
container.innerHTML = '';
if (totalItems === 0) {
container.innerHTML = '<p style="color:var(--muted); text-align:center; width:100%;">Aucun élément trouvé.</p>';
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 = '<i class="ti ti-chevron-left"></i>';
prevBtn.disabled = currentPage === 1;
prevBtn.onclick = () => { currentPage--; renderAdminTable(); };
container.appendChild(prevBtn);
let startPage = Math.max(1, currentPage - 2);
let endPage = Math.min(totalPages, currentPage + 2);
if (startPage > 1) {
const firstBtn = document.createElement('button');
firstBtn.textContent = '1';
firstBtn.onclick = () => { currentPage = 1; renderAdminTable(); };
container.appendChild(firstBtn);
if (startPage > 2) {
const dots = document.createElement('span');
dots.textContent = '...';
container.appendChild(dots);
}
}
for (let i = startPage; i <= endPage; i++) {
const btn = document.createElement('button');
btn.textContent = i;
if (i === currentPage) btn.classList.add('active');
btn.onclick = () => { currentPage = i; renderAdminTable(); };
container.appendChild(btn);
}
if (endPage < totalPages) {
if (endPage < totalPages - 1) {
const dots = document.createElement('span');
dots.textContent = '...';
container.appendChild(dots);
}
const lastBtn = document.createElement('button');
lastBtn.textContent = totalPages;
lastBtn.onclick = () => { currentPage = totalPages; renderAdminTable(); };
container.appendChild(lastBtn);
}
const nextBtn = document.createElement('button');
nextBtn.innerHTML = '<i class="ti ti-chevron-right"></i>';
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');
if (physicalFilter) 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 = (dataStore[currentAdminTab] || []).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-actors').value = item.actors || '';
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();
const tmdbIn = document.getElementById('tmdb-key-input');
if (tmdbIn) tmdbIn.placeholder = data.tmdb_api_key ? '✅ Clé TMDB configurée' : 'Entrez votre clé TMDB';
const upcIn = document.getElementById('upcmdb-key-input');
if (upcIn) upcIn.placeholder = data.upcmdb_api_key ? '✅ Clé UPCMDB configurée' : 'Clé gratuite sur upcmdb.com';
} 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') ? document.getElementById('f-rating').value : '',
review: document.getElementById('f-review') ? document.getElementById('f-review').value : '',
streaming: document.getElementById('f-streaming') ? document.getElementById('f-streaming').value : '',
format: document.getElementById('f-format') ? document.getElementById('f-format').value : '',
length: document.getElementById('f-length') ? document.getElementById('f-length').value : '',
publisher: document.getElementById('f-publisher') ? document.getElementById('f-publisher').value : '',
aspect_ratio: document.getElementById('f-aspect') ? document.getElementById('f-aspect').value : '',
ean_isbn13: document.getElementById('f-ean') ? document.getElementById('f-ean').value : '',
number_of_discs: document.getElementById('f-discs') ? document.getElementById('f-discs').value : 1,
description: document.getElementById('f-description') ? document.getElementById('f-description').value : '',
actors: document.getElementById('f-actors') ? document.getElementById('f-actors').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); }
}
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 += 3) {
const batch = allData.slice(i, i + 3);
try {
const response = 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' }) });
if (!response.ok) throw new Error(`Erreur serveur ${response.status}`);
const result = await response.json();
if (!result.success) throw new Error(result.error || "Erreur inconnue.");
} catch (err) {
closeImportModal(); alert("❌ Échec de l'import : " + err.message); input.value = ''; return;
}
processed += batch.length;
updateImportModal(processed, allData.length);
}
input.value = ''; closeImportModal();
showSuccessModal(`${allData.length} critique(s) importée(s) avec succès.`);
loadDashboardData();
}
// ✅ MODIFIÉ : Ne retourne QUE l'EAN
function normalizeVideothequeRow(row) {
let ean = row['ean_isbn13'] || row['EAN'] || row['ean'] || row['Barcode'] || row['UPC'] || row['upc_isbn10'] || '';
ean = String(ean).replace(/[^0-9]/g, '');
// Si pas d'EAN valide, on ignore la ligne
if (!ean || ean.length < 8) return null;
return { ean: ean };
}
function handleVideothequeUpload(input) {
const file = input.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = async (e) => {
const text = e.target.result;
const parsed = parseCSV(text);
if (!parsed.length) { alert("❌ CSV vide."); return; }
// ✅ Ne garde que les EANs valides
const items = parsed.map(row => normalizeVideothequeRow(row)).filter(Boolean);
if (!items.length) { alert("❌ Aucun code EAN valide trouvé dans le CSV."); return; }
showImportModal(items.length, 'videotheque');
let processed = 0, totalImp = 0, totalSkp = 0;
try {
// Envoi par lot de 1 pour respecter le throttle de Blu-ray.com
for (let i = 0; i < items.length; i += 1) {
const batch = items.slice(i, i + 1);
const res = await fetch(`${API_URL}?action=import_batch`, {
method: 'POST',
headers: { 'Authorization': localStorage.getItem('token'), 'Content-Type': 'application/json' },
body: JSON.stringify({ type: 'videotheque', items: batch })
});
if (!res.ok) throw new Error(`Erreur HTTP ${res.status}`);
const data = await res.json();
if (!data.success) throw new Error(data.error || "Échec API");
totalImp += data.imported || 0;
totalSkp += data.skipped || 0;
processed += batch.length;
updateImportModal(processed, items.length);
await new Promise(r => setTimeout(r, 300)); // Petit délai réseau
}
input.value = '';
closeImportModal();
const msg = totalSkp > 0 ? ` (${totalSkp} ignoré(s))` : '';
showSuccessModal(`${totalImp} édition(s) importée(s).${msg}`);
loadDashboardData();
} catch (err) {
console.error(err);
closeImportModal();
alert("❌ Échec import : " + err.message);
input.value = '';
}
};
reader.readAsText(file);
}
function showImportModal(total, type) {
document.getElementById('import-modal-title').innerHTML = type === 'critique' ? '<i class="ti ti-star"></i> Import Critiques' : '<i class="ti ti-video"></i> 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 tmdb = document.getElementById('tmdb-key-input').value.trim();
const upcmdb = document.getElementById('upcmdb-key-input').value.trim();
try {
if (tmdb) 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:tmdb}) });
if (upcmdb) await fetch(`${API_URL}?action=save_config`, { method:'POST', headers:{'Authorization':localStorage.getItem('token'),'Content-Type':'application/json'}, body:JSON.stringify({key_name:'upcmdb_api_key',key_value:upcmdb}) });
alert('✅ Clés sauvegardées !');
closeConfigModal();
} catch(e) { 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 === 'videotheque') {
title.innerHTML = '<strong>Importer ma Vidéothèque</strong>';
desc.textContent = 'Importez votre CSV. Le système extraira uniquement les codes EAN pour récupérer les jaquettes HD et métadonnées via Blu-ray.com, MovieCovers et TMDB.';
} else {
title.innerHTML = '<strong>Importer Critiques & Notes</strong>';
desc.textContent = 'Importez vos fichiers CSV de notes et critiques (ex: Letterboxd).';
}
}
function showSuccessModal(message) {
const msgEl = document.getElementById('success-modal-message');
const modalEl = document.getElementById('success-modal');
if (msgEl) msgEl.textContent = message;
if (modalEl) modalEl.classList.add('open');
}
function closeSuccessModal() {
const modalEl = document.getElementById('success-modal');
if (modalEl) modalEl.classList.remove('open');
}
// 1. Ouvre le choix entre Manuel ou EAN
function openAddMethodModal() {
document.getElementById('add-choice-modal').classList.add('open');
}
// 2. Ouvre la saisie EAN et ferme le choix
function openEanModal() {
document.getElementById('add-choice-modal').classList.remove('open');
document.getElementById('ean-input-modal').classList.add('open');
}
// 3. Ouvre votre formulaire manuel existant (Adaptez le nom selon votre code actuel)
function openManualForm() {
document.getElementById('add-choice-modal').classList.remove('open');
// On appelle ici l'ancienne fonction qui ouvre le formulaire manuel
openAddModal();
}
function closeEanModal() {
document.getElementById('ean-input-modal').classList.remove('open');
}
// 4. Soumission de l'EAN
async function submitEan() {
const ean = document.getElementById('ean-input').value.trim();
if (!ean) return;
closeEanModal();
showImportModal(1, 'videotheque');
document.getElementById('import-modal-desc').textContent = "Récupération des infos et de la jaquette...";
try {
const response = await fetch(`${API_URL}?action=add_item_by_ean`, {
method: 'POST',
headers: { 'Authorization': localStorage.getItem('token'), 'Content-Type': 'application/json' },
body: JSON.stringify({ ean })
});
const data = await response.json();
closeImportModal();
if (data.success) {
showSuccessModal("Œuvre ajoutée avec succès !");
loadDashboardData();
} else {
alert("Erreur : " + (data.error || "Impossible de trouver le film avec cet EAN."));
}
} catch (err) {
closeImportModal();
alert("Erreur de communication.");
}
}