This commit is contained in:
2026-06-18 07:38:41 +02:00
parent ec815787ed
commit 2d4d139f9d
9 changed files with 1696 additions and 530 deletions
+393 -1
View File
@@ -1,3 +1,4 @@
<<<<<<< HEAD
/**
* =========================================================================
* Mon Cinéma - Module d'Administration (admin.js)
@@ -279,4 +280,395 @@ function switchTab(tabName) {
if (targetBtn) targetBtn.classList.add('active');
localStorage.setItem('mon-cinema-active-tab', tabName);
}
}
=======
// ══════════════════════════════════════════════════════════════════
// admin.js — Backoffice Mon Cinéma
// Chargé UNIQUEMENT par dashboard.html
// ══════════════════════════════════════════════════════════════════
const API_URL = '../api.php';
let allItems = [];
let currentAdminTab = 'critique';
// ── Garde de session (dashboard uniquement) ──────────────────────
(function guardSession() {
if (!localStorage.getItem('token')) {
window.location.href = 'login.html';
}
})();
// ══════════════════════════════════════════════════════════════════
// 1. CHARGEMENT & RENDU
// ══════════════════════════════════════════════════════════════════
async function loadDashboardData() {
try {
const res = await fetch(`${API_URL}?action=get_films`);
allItems = await res.json();
// Vérifier si compte sécurisé
const secRes = await fetch(`${API_URL}?action=check_security_status`);
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 switchAdminTab(tabName) {
currentAdminTab = tabName;
document.getElementById('btn-tab-critique').classList.toggle('active', tabName === 'critique');
document.getElementById('btn-tab-videotheque').classList.toggle('active', tabName === 'videotheque');
const importSection = document.getElementById('import-section');
if (importSection) importSection.style.display = tabName === 'critique' ? 'block' : 'none';
document.getElementById('admin-subtitle').textContent =
tabName === 'critique'
? 'Gestion de vos critiques de films'
: 'Gestion de votre stock physique de films';
document.getElementById('th-dynamic').textContent = tabName === 'critique' ? 'Note' : 'Format';
const selectAll = document.getElementById('select-all-checkbox');
if (selectAll) selectAll.checked = false;
renderAdminTable();
}
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; color:var(--muted); padding:3rem;">
<i class="ti ti-folder-off" style="font-size:2rem; display:block; margin-bottom:0.5rem;"></i>
Aucun film trouvé dans cette liste.</td></tr>`;
updateBulkBarVisibility();
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"><i class="ti ti-photo-off"></i></div>`;
const dynamicCell = currentAdminTab === 'critique'
? `<span class="tbl-stars">${'★'.repeat(f.rating)}<span style="opacity:.25">${'☆'.repeat(5 - f.rating)}</span></span>`
: `<span class="badge-format">${f.format || 'Physique'}</span>`;
tr.innerHTML = `
<td style="text-align:center;">
<input type="checkbox" class="film-checkbox" value="${f.id}" onclick="updateBulkBarVisibility()">
</td>
<td style="text-align:center;">${imgHTML}</td>
<td><strong style="color:var(--text);">${f.title}</strong></td>
<td style="color:var(--text-secondary);">${f.year || '&mdash;'}</td>
<td style="color:var(--text-secondary); font-style:italic;">${f.director || 'Inconnu'}</td>
<td>${dynamicCell}</td>
<td style="text-align:center;">
<div class="tbl-actions">
<button onclick="openEditModal('${f.id}')" title="Modifier"><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);
});
updateBulkBarVisibility();
}
// ══════════════════════════════════════════════════════════════════
// 2. SÉLECTION EN MASSE
// ══════════════════════════════════════════════════════════════════
function toggleSelectAll(master) {
document.querySelectorAll('.film-checkbox').forEach(cb => cb.checked = master.checked);
updateBulkBarVisibility();
}
function updateBulkBarVisibility() {
const checked = document.querySelectorAll('.film-checkbox:checked');
const bulkBar = document.getElementById('bulk-actions-bar');
const bulkCount = document.getElementById('bulk-count');
const selectAll = document.getElementById('select-all-checkbox');
if (!bulkBar || !bulkCount) return;
if (checked.length > 0) {
bulkBar.style.display = 'flex';
bulkCount.textContent = checked.length;
} else {
bulkBar.style.display = 'none';
if (selectAll) selectAll.checked = false;
}
}
async function executeBulkDelete() {
const checked = document.querySelectorAll('.film-checkbox:checked');
const idsToDelete = Array.from(checked).map(cb => cb.value);
if (!idsToDelete.length) return;
if (!confirm(`Supprimer définitivement ces ${idsToDelete.length} élément(s) ?`)) return;
try {
const res = await fetch(`${API_URL}?action=delete_multiple_films&type=${currentAdminTab}`, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json', 'Authorization': localStorage.getItem('token') },
body: JSON.stringify({ ids: idsToDelete })
});
const data = await res.json();
if (data.success) {
const selectAll = document.getElementById('select-all-checkbox');
if (selectAll) selectAll.checked = false;
loadDashboardData();
} else {
alert('Erreur suppression groupée : ' + data.error);
}
} catch (err) {
console.error('Bulk delete :', err);
}
}
// ══════════════════════════════════════════════════════════════════
// 3. SUPPRESSION UNITAIRE
// ══════════════════════════════════════════════════════════════════
async function deleteSingleFilm(id) {
if (!confirm('Supprimer définitivement cette œuvre ?')) return;
try {
const res = await fetch(`${API_URL}?action=delete_film&id=${id}&type=${currentAdminTab}`, {
method: 'DELETE',
headers: { 'Authorization': localStorage.getItem('token') }
});
const data = await res.json();
if (data.success) loadDashboardData();
} catch (err) {
console.error(err);
}
}
// ══════════════════════════════════════════════════════════════════
// 4. MODALES FILM (ouvrir / fermer / remplir)
// ══════════════════════════════════════════════════════════════════
function openAddModal() {
document.getElementById('film-form').reset();
document.getElementById('f-id').value = '';
document.getElementById('modal-form-title').textContent =
currentAdminTab === 'critique' ? 'Rédiger une Critique' : 'Ajouter un film physique';
document.getElementById('form-critique-fields').style.display = currentAdminTab === 'critique' ? 'block' : 'none';
document.getElementById('form-videotheque-fields').style.display = currentAdminTab === 'videotheque' ? 'block' : 'none';
document.getElementById('admin-modal').classList.add('open');
}
function openEditModal(id) {
const item = allItems.find(x => String(x.id) === String(id));
if (!item) return;
openAddModal();
document.getElementById('modal-form-title').textContent = "Modifier l'œuvre";
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 || '';
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 || '';
}
}
function closeAdminModal() {
document.getElementById('admin-modal').classList.remove('open');
}
// ══════════════════════════════════════════════════════════════════
// 5. SAUVEGARDE FORMULAIRE FILM
// ══════════════════════════════════════════════════════════════════
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,
poster: document.getElementById('f-poster').value
};
if (currentAdminTab === 'critique') {
payload.rating = parseInt(document.getElementById('f-rating').value);
payload.review = document.getElementById('f-review').value;
payload.streaming = document.getElementById('f-streaming').value;
} else {
payload.format = document.getElementById('f-format').value;
payload.length = document.getElementById('f-length').value;
payload.publisher = document.getElementById('f-publisher').value;
payload.aspect_ratio = document.getElementById('f-aspect').value;
payload.ean_isbn13 = document.getElementById('f-ean').value;
payload.number_of_discs = document.getElementById('f-discs').value;
payload.description = document.getElementById('f-description').value;
}
try {
const res = await fetch(`${API_URL}?action=save_film`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': localStorage.getItem('token') },
body: JSON.stringify(payload)
});
const data = await res.json();
if (data.success) {
closeAdminModal();
loadDashboardData();
} else {
alert('Erreur lors de l\'enregistrement.');
}
} catch (err) {
console.error('Erreur save :', err);
}
}
// ══════════════════════════════════════════════════════════════════
// 6. IMPORT CSV (Letterboxd)
// ══════════════════════════════════════════════════════════════════
async function handleCsvUpload(input) {
if (!input.files || input.files.length === 0) return;
const formData = new FormData();
formData.append('csv_file', input.files[0]);
try {
const res = await fetch(`${API_URL}?action=import_csv`, {
method: 'POST',
headers: { 'Authorization': localStorage.getItem('token') },
body: formData
});
const data = await res.json();
if (data.success) {
alert(`✅ Import réussi ! ${data.imported} films ajoutés ou mis à jour.`);
loadDashboardData();
} else {
alert('❌ Erreur import : ' + (data.error || 'Erreur inconnue'));
}
} catch (err) {
console.error('Erreur Import CSV :', err);
alert('Impossible d\'importer le fichier.');
} finally {
input.value = '';
}
}
// ══════════════════════════════════════════════════════════════════
// 7. MODALE TMDB
// ══════════════════════════════════════════════════════════════════
function openConfigModal() { document.getElementById('config-modal').classList.add('open'); }
function closeConfigModal() { document.getElementById('config-modal').classList.remove('open'); }
async function saveTmdbKey() {
const key = document.getElementById('tmdb-key-input').value.trim();
if (!key) { alert('Veuillez saisir une clé.'); return; }
try {
const res = await fetch(`${API_URL}?action=save_tmdb_key`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': localStorage.getItem('token') },
body: JSON.stringify({ tmdb_key: key })
});
const data = await res.json();
if (data.success) {
alert('✅ Clé TMDB chiffrée et sauvegardée.');
document.getElementById('tmdb-key-input').value = '';
closeConfigModal();
}
} catch (err) {
console.error(err);
}
}
// ══════════════════════════════════════════════════════════════════
// 8. MODALE MOT DE PASSE
// ══════════════════════════════════════════════════════════════════
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;
const errEl = document.getElementById('pwd-error');
errEl.style.display = 'none';
if (pwd1.length < 4) {
errEl.textContent = 'Le mot de passe doit faire au moins 4 caractères.';
errEl.style.display = 'block';
return;
}
if (pwd1 !== pwd2) {
errEl.textContent = 'Les mots de passe ne correspondent pas.';
errEl.style.display = 'block';
return;
}
try {
// Premier usage (compte vide) → setup_admin, sinon update_password
const secRes = await fetch(`${API_URL}?action=check_security_status`);
const secData = await secRes.json();
const action = secData.is_blank ? 'setup_admin' : 'update_password';
const res = await fetch(`${API_URL}?action=${action}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': localStorage.getItem('token') },
body: JSON.stringify({ password: pwd1, new_password: pwd1 })
});
const data = await res.json();
if (data.success || data.success === '') {
alert('✅ Mot de passe mis à jour. Vous allez être redirigé vers la connexion.');
localStorage.removeItem('token');
window.location.href = 'login.html';
}
} catch (err) {
console.error(err);
}
}
// ══════════════════════════════════════════════════════════════════
// 9. DÉCONNEXION
// ══════════════════════════════════════════════════════════════════
function logout() {
localStorage.removeItem('token');
window.location.href = 'login.html';
}
// ══════════════════════════════════════════════════════════════════
// INIT
// ══════════════════════════════════════════════════════════════════
document.addEventListener('DOMContentLoaded', loadDashboardData);
>>>>>>> 5a22e3f (all)