Files
mon-petit-cinema/js/admin.js
T
2026-06-22 11:58:28 +02:00

655 lines
26 KiB
JavaScript

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 += '<span class="half-star">★</span>';
html += `<span class="stars-muted">${'☆'.repeat(empty)}</span>`;
return html;
}
// ── PARSER CSV RENFORCÉ ──
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) => handleCsvUpload(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 = `
<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();
const filtered = allItems.filter(item => item.type === currentAdminTab);
const selectAll = document.getElementById('select-all-checkbox');
if (selectAll) {
selectAll.checked = filtered.length > 0 && filtered.every(f => selectedIds.has(String(f.id)));
}
}
function toggleSelectAll(source) {
const filtered = allItems.filter(item => item.type === 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);
const maxButtons = 5;
let startPage = Math.max(1, currentPage - Math.floor(maxButtons / 2));
let endPage = Math.min(totalPages, startPage + maxButtons - 1);
if (endPage - startPage + 1 < maxButtons) {
startPage = Math.max(1, endPage - maxButtons + 1);
}
if (startPage > 1) {
container.appendChild(createPageBtn(1));
if (startPage > 2) container.appendChild(createEllipsis());
}
for (let i = startPage; i <= endPage; i++) {
container.appendChild(createPageBtn(i));
}
if (endPage < totalPages) {
if (endPage < totalPages - 1) container.appendChild(createEllipsis());
container.appendChild(createPageBtn(totalPages));
}
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 createPageBtn(num) {
const btn = document.createElement('button');
btn.textContent = num;
if (num === currentPage) btn.classList.add('active');
btn.onclick = () => { currentPage = num; renderAdminTable(); };
return btn;
}
function createEllipsis() {
const span = document.createElement('span');
span.textContent = '...';
span.style.color = 'var(--muted)';
span.style.padding = '0 0.5rem';
return span;
}
function showConfirmModal(actionFn) {
pendingDeleteAction = actionFn;
const modal = document.getElementById('confirm-modal');
if (modal) modal.classList.add('open');
}
function closeConfirmModal() {
const modal = document.getElementById('confirm-modal');
if (modal) modal.classList.remove('open');
pendingDeleteAction = null;
}
async function executeBulkDelete() {
const ids = Array.from(selectedIds);
if (ids.length === 0) return;
showConfirmModal(async () => {
try {
const res = await fetch(`${API_URL}?action=bulk_delete`, {
method: 'POST',
headers: { 'Authorization': localStorage.getItem('token'), 'Content-Type': 'application/json' },
body: JSON.stringify({ ids, type: currentAdminTab })
});
if (!res.ok) throw new Error("Erreur serveur.");
selectedIds.clear();
document.getElementById('bulk-actions-bar').style.display = 'none';
const selectAll = document.getElementById('select-all-checkbox');
if (selectAll) selectAll.checked = false;
loadDashboardData();
} catch (err) {
console.error('Erreur bulk delete :', err);
alert("Une erreur est survenue.");
}
});
}
async function deleteSingleFilm(id) {
showConfirmModal(async () => {
try {
const res = await fetch(`${API_URL}?action=delete_film&id=${id}&type=${currentAdminTab}`, {
method: 'DELETE',
headers: { 'Authorization': localStorage.getItem('token') }
});
if (!res.ok) throw new Error("Erreur serveur.");
loadDashboardData();
} catch (err) {
console.error('Erreur delete :', err);
alert("Une erreur est survenue.");
}
});
}
function toggleFormFields() {
const critFields = document.getElementById('form-critique-fields');
const vidFields = document.getElementById('form-videotheque-fields');
if (critFields) critFields.style.display = currentAdminTab === 'critique' ? 'block' : 'none';
if (vidFields) vidFields.style.display = currentAdminTab === 'videotheque' ? 'block' : 'none';
}
function switchAdminTab(tabName) {
currentAdminTab = tabName;
currentPage = 1;
selectedIds.clear();
const searchInput = document.getElementById('search-input');
if (searchInput) searchInput.value = '';
const physicalFilter = document.getElementById('admin-physical-checkbox');
if (physicalFilter) physicalFilter.checked = false;
document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
const btn = document.getElementById(`btn-tab-${tabName}`);
if (btn) btn.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');
document.getElementById('tmdb-key-input').placeholder = 'Pour les critiques (réalisateur, streaming)';
try {
const res = await fetch(`${API_URL}?action=get_config_keys`, { headers: { 'Authorization': localStorage.getItem('token') } });
const data = await res.json();
if (data.tmdb_api_key) document.getElementById('tmdb-key-input').placeholder = '✅ Clé configurée (laisser vide pour ne pas changer)';
} 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('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 : ''
};
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('Erreur sauvegarde :', err); }
}
// --- FONCTION D'IMPORT INTELLIGENTE (CORRIGÉE) ---
async function handleCsvUpload(input) {
if (!input.files || input.files.length === 0) return;
let allData = [];
for (const file of input.files) {
try {
const text = await file.text();
const data = parseCSV(text);
allData = allData.concat(data);
} catch(e) {
console.error('Erreur lecture fichier', file.name, e);
}
}
input.value = '';
if (allData.length === 0) {
alert('❌ Fichiers vides ou mal formatés.');
return;
}
const mergedMap = new Map();
allData.forEach(row => {
const title = (row['Title'] || row['Name'] || '').trim();
const dateStr = (row['Date'] || row['Year'] || row['year'] || '').toString();
const year = dateStr.match(/(\d{4})/)?.[1] || '';
const key = `${title.toLowerCase()}|${year}`;
if (!mergedMap.has(key)) {
mergedMap.set(key, { ...row });
} else {
const existing = mergedMap.get(key);
if ((row['Rating'] || row['rating']) && !existing['Rating']) existing['Rating'] = row['Rating'];
if ((row['Review'] || row['review']) && !existing['Review']) existing['Review'] = row['Review'];
}
});
let finalData = Array.from(mergedMap.values());
// 🔥 CORRECTION : Mapping des champs CSV vers les champs attendus par le Backend
finalData = finalData.map(row => {
const title = (row['Title'] || row['Name'] || '').trim();
const dateStr = (row['Date'] || row['Year'] || row['year'] || '').toString();
const year = dateStr.match(/(\d{4})/)?.[1] || '';
const existingDb = allItems.find(f =>
f.title.toLowerCase().trim() === title.toLowerCase() &&
String(f.year) === String(year) &&
f.type === currentAdminTab
);
return {
...row, // Garde les données brutes au cas où
// Mappe vers les noms de colonnes BDD
title: title,
year: year,
rating: (row['Rating'] || row['rating']) || (existingDb ? existingDb.rating : ''),
review: (row['Review'] || row['review']) || (existingDb ? existingDb.review : '')
};
});
showImportModal(finalData.length, currentAdminTab);
const batchSize = 10;
let processed = 0;
for (let i = 0; i < finalData.length; i += batchSize) {
const batch = finalData.slice(i, i + batchSize);
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: currentAdminTab })
});
} catch (err) {
console.error('Erreur lot import:', err);
}
processed += batch.length;
updateImportModal(processed, finalData.length);
}
closeImportModal();
alert(`✅ Import terminé ! ${finalData.length} élément(s) traité(s).`);
loadDashboardData();
}
async function saveConfigKeys() {
const keys = { 'tmdb_api_key': document.getElementById('tmdb-key-input')?.value || '' };
let successCount = 0;
for (const [keyName, keyValue] of Object.entries(keys)) {
if (keyValue) {
try {
const res = await fetch(`${API_URL}?action=save_config`, {
method: 'POST',
headers: { 'Authorization': localStorage.getItem('token'), 'Content-Type': 'application/json' },
body: JSON.stringify({ key_name: keyName, key_value: keyValue })
});
const data = await res.json();
if (data.success) successCount++;
} catch (err) { console.error(err); }
}
}
if (successCount > 0) {
alert('✅ Clés API sauvegardées !');
closeConfigModal();
} else { alert('Aucune nouvelle clé valide à sauvegarder.'); }
}
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 || !pwdConfirm) return;
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 = "Le mot de passe doit contenir au moins 4 caractères.";
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) {
pwdInput.value = '';
pwdConfirm.value = '';
errorMsg.style.display = "none";
closePasswordModal();
alert('Mot de passe mis à jour.');
loadDashboardData();
}
} catch (err) { console.error('Erreur mise à jour mot de passe :', err); }
}
// --- IMPORT PROGRESSIVE DYNAMIQUE ---
function showImportModal(total, type) {
const modal = document.getElementById('import-progress-modal');
const title = document.getElementById('import-modal-title');
const desc = document.getElementById('import-modal-desc');
title.innerHTML = type === 'critique'
? '<i class="ti ti-star"></i> Import des Critiques'
: '<i class="ti ti-video"></i> Import Vidéothèque';
desc.textContent = `Traitement de ${total} élément(s)...`;
document.getElementById('import-progress-bar').style.width = '0%';
document.getElementById('import-modal-counter').textContent = '0%';
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 fetchInfoFromEAN() {
const eanInput = document.getElementById('f-ean');
const ean = eanInput.value.trim();
if (!ean || ean.length < 8) { alert("Veuillez saisir un code EAN valide."); return; }
const btn = eanInput.nextElementSibling;
const originalHtml = btn.innerHTML;
btn.innerHTML = '<i class="ti ti-loader"></i>';
btn.disabled = true;
try {
const res = await fetch(`${API_URL}?action=search_ean_full&ean=${ean}`, {
headers: { 'Authorization': localStorage.getItem('token') }
});
const json = await res.json();
if (json.success && json.data) {
const d = json.data;
if (d.title) document.getElementById('f-title').value = d.title;
if (d.director) document.getElementById('f-director').value = d.director;
if (d.year) document.getElementById('f-year').value = d.year;
if (d.poster) document.getElementById('f-poster').value = d.poster;
if (d.publisher) document.getElementById('f-publisher').value = d.publisher;
if (d.format) document.getElementById('f-format').value = d.format;
if (d.length) document.getElementById('f-length').value = d.length;
if (d.number_of_discs) document.getElementById('f-discs').value = d.number_of_discs;
if (d.aspect_ratio) document.getElementById('f-aspect').value = d.aspect_ratio;
} else { alert("Aucune information trouvée pour ce code EAN."); }
} catch (e) {
console.error("Erreur de recherche EAN: ", e);
alert("Erreur réseau lors de la recherche du code EAN.");
} finally {
btn.innerHTML = originalHtml;
btn.disabled = false;
}
}
function updateImportInterface() {
const title = document.getElementById('import-title');
const desc = document.getElementById('import-desc');
if (currentAdminTab === 'critique') {
title.innerHTML = '<strong>Importer Critiques & Notes</strong>';
desc.textContent = 'Glissez-déposez vos fichiers "ratings.csv" et "reviews.csv" (Letterboxd).';
} else {
title.innerHTML = '<strong>Importer ma Vidéothèque</strong>';
desc.textContent = 'Glissez-déposez vos listes CSV de supports physiques (Blu-ray, DVD, 4K).';
}
}