Actualiser js/admin.js

This commit is contained in:
2026-06-18 10:48:48 +02:00
parent 42ad65a781
commit d84acb183e
+74 -53
View File
@@ -10,13 +10,13 @@ let currentAdminTab = 'critique';
// ── 1. GARDE DE SESSION ──
(function guardSession() {
if (window.location.pathname.includes('dashboard.html') && !localStorage.getItem('token')) {
if (!localStorage.getItem('token')) {
window.location.href = 'login.html';
}
})();
// ══════════════════════════════════════════════════════════════════
// CHARGEMENT & RENDU (DASHBOARD)
// CHARGEMENT & RENDU
// ══════════════════════════════════════════════════════════════════
async function loadDashboardData() {
try {
@@ -29,40 +29,25 @@ async function loadDashboardData() {
if (banner) banner.style.display = secData.is_blank ? 'flex' : 'none';
renderAdminTable();
} catch (err) {
console.error('Erreur chargement :', err);
}
} catch (err) { console.error('Erreur chargement :', err); }
}
function renderAdminTable() {
const tbody = document.getElementById('admin-table-body');
const countLabel = document.getElementById('admin-count-label');
if (!tbody) return;
tbody.innerHTML = '';
const filtered = allItems.filter(item => item.type === currentAdminTab);
if (countLabel) countLabel.textContent = `${filtered.length} élément(s) dans cette catégorie`;
if (filtered.length === 0) {
tbody.innerHTML = `<tr><td colspan="7" style="text-align:center; padding:3rem;">Aucun film trouvé.</td></tr>`;
return;
}
filtered.forEach(f => {
const tr = document.createElement('tr');
const imgHTML = f.poster ? `<img src="${f.poster}" class="thumb" alt="${f.title}">` : `<div class="thumb-ph"></div>`;
const dynamicCell = currentAdminTab === 'critique'
? `<span class="tbl-stars">${'★'.repeat(f.rating)}</span>`
: `<span class="badge-format">${f.format || 'Physique'}</span>`;
tr.innerHTML = `
<td><input type="checkbox" class="film-checkbox" value="${f.id}"></td>
<td>${imgHTML}</td>
<td>${f.poster ? `<img src="${f.poster}" class="thumb" width="40">` : '-'}</td>
<td><strong>${f.title}</strong></td>
<td>${f.year || ''}</td>
<td>${f.director || ''}</td>
<td>${dynamicCell}</td>
<td>${currentAdminTab === 'critique' ? '★'.repeat(f.rating || 0) : (f.format || '-')}</td>
<td>
<button onclick="openEditModal('${f.id}')">Éditer</button>
<button onclick="deleteSingleFilm('${f.id}')">Supprimer</button>
@@ -72,45 +57,72 @@ function renderAdminTable() {
}
// ══════════════════════════════════════════════════════════════════
// IMPORT / EXPORT CSV
// MODALES & ACTIONS
// ══════════════════════════════════════════════════════════════════
function exportToCSV() {
if (!allItems.length) return alert("Aucune donnée.");
const headers = ['ID', 'Titre', 'Annee', 'Realisateur', 'Note', 'Critique', 'URL_Affiche'];
const csvRows = [headers.join(';')];
allItems.forEach(f => {
csvRows.push([f.id, `"${f.title}"`, f.year, `"${f.director}"`, f.rating, `"${f.review}"`, `"${f.poster}"`].join(';'));
});
const blob = new Blob(["\uFEFF" + csvRows.join("\n")], { type: 'text/csv;charset=utf-8;' });
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = "export_cinema.csv";
link.click();
function openAddModal() {
document.getElementById('film-form').reset();
document.getElementById('f-id').value = '';
document.getElementById('admin-modal').classList.add('open');
}
async function handleCsvUpload(input) {
if (!input.files[0]) return;
const formData = new FormData();
formData.append('csv_file', input.files[0]);
try {
const res = await fetch(`${API_URL}?action=import_csv`, {
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('admin-modal').classList.add('open');
}
function closeAdminModal() { document.getElementById('admin-modal').classList.remove('open'); }
async function saveFilmForm(e) {
e.preventDefault();
const payload = {
type: currentAdminTab,
id: document.getElementById('f-id').value || null,
title: document.getElementById('f-title').value,
year: document.getElementById('f-year').value,
director: document.getElementById('f-director').value
};
await fetch(`${API_URL}?action=save_film`, {
method: 'POST',
headers: { 'Authorization': localStorage.getItem('token') },
body: formData
headers: { 'Content-Type': 'application/json', 'Authorization': localStorage.getItem('token') },
body: JSON.stringify(payload)
});
const data = await res.json();
if (data.success) {
alert(`Succès : ${data.imported} films ajoutés.`);
closeAdminModal();
loadDashboardData();
}
} catch (e) { console.error(e); }
}
// ══════════════════════════════════════════════════════════════════
// GESTION ACTIONS UNITAIRES
// GESTION COMPTE & SÉCURITÉ
// ══════════════════════════════════════════════════════════════════
function logout() { localStorage.removeItem('token'); window.location.href = 'login.html'; }
function openConfigModal() { document.getElementById('config-modal').classList.add('open'); }
function closeConfigModal() { document.getElementById('config-modal').classList.remove('open'); }
function openPasswordModal() { document.getElementById('password-modal').classList.add('open'); }
function closePasswordModal() { document.getElementById('password-modal').classList.remove('open'); }
async function saveNewPassword() {
const pwd1 = document.getElementById('new-password-input').value;
const pwd2 = document.getElementById('new-password-confirm').value;
if (pwd1 !== pwd2) return alert("Les mots de passe ne correspondent pas.");
await fetch(`${API_URL}?action=update_password`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': localStorage.getItem('token') },
body: JSON.stringify({ password: pwd1 })
});
alert("Mot de passe mis à jour.");
closePasswordModal();
}
// ══════════════════════════════════════════════════════════════════
// UTILS
// ══════════════════════════════════════════════════════════════════
async function deleteSingleFilm(id) {
if (!confirm('Supprimer cette œuvre ?')) return;
if (!confirm('Supprimer ?')) return;
await fetch(`${API_URL}?action=delete_film&id=${id}&type=${currentAdminTab}`, {
method: 'DELETE',
headers: { 'Authorization': localStorage.getItem('token') }
@@ -120,12 +132,21 @@ async function deleteSingleFilm(id) {
function switchAdminTab(tabName) {
currentAdminTab = tabName;
document.getElementById('btn-tab-critique').classList.toggle('active', tabName === 'critique');
document.getElementById('btn-tab-videotheque').classList.toggle('active', tabName === 'videotheque');
renderAdminTable();
}
// ── INITIALISATION ──
document.addEventListener('DOMContentLoaded', () => {
if (document.getElementById('admin-table-body')) {
async function handleCsvUpload(input) {
if (!input.files[0]) return;
const formData = new FormData();
formData.append('csv_file', input.files[0]);
await fetch(`${API_URL}?action=import_csv`, {
method: 'POST',
headers: { 'Authorization': localStorage.getItem('token') },
body: formData
});
loadDashboardData();
}
});
}
document.addEventListener('DOMContentLoaded', loadDashboardData);