394 lines
16 KiB
JavaScript
394 lines
16 KiB
JavaScript
const API_URL = '../api.php';
|
|
let allItems = [];
|
|
let currentAdminTab = 'critique';
|
|
|
|
// ── INITIALISATION ──
|
|
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));
|
|
|
|
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');
|
|
}
|
|
});
|
|
}
|
|
|
|
// ── CHARGEMENT DES DONNÉES (Anti-cache) ──
|
|
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 filtered = allItems.filter(item => item.type === currentAdminTab);
|
|
|
|
const countLabel = document.getElementById('admin-count-label');
|
|
if(countLabel) countLabel.textContent = `${filtered.length} élément(s)`;
|
|
|
|
filtered.forEach(f => {
|
|
const tr = document.createElement('tr');
|
|
tr.innerHTML = `
|
|
<td style="text-align:center;">
|
|
<input type="checkbox" class="film-checkbox" value="${f.id}" onclick="updateBulkBar()">
|
|
</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">${'★'.repeat(f.rating || 0)}</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);
|
|
});
|
|
}
|
|
|
|
// ── GESTION DE MASSE ──
|
|
function toggleSelectAll(source) {
|
|
document.querySelectorAll('.film-checkbox').forEach(cb => cb.checked = source.checked);
|
|
updateBulkBar();
|
|
}
|
|
|
|
function updateBulkBar() {
|
|
const checked = document.querySelectorAll('.film-checkbox:checked');
|
|
const bulkBar = document.getElementById('bulk-actions-bar');
|
|
const bulkCount = document.getElementById('bulk-count');
|
|
|
|
if (checked.length > 0) {
|
|
if(bulkBar) bulkBar.style.display = 'flex';
|
|
if(bulkCount) bulkCount.textContent = checked.length;
|
|
} else {
|
|
if(bulkBar) bulkBar.style.display = 'none';
|
|
const selectAll = document.getElementById('select-all-checkbox');
|
|
if(selectAll) selectAll.checked = false;
|
|
}
|
|
}
|
|
|
|
// ── POP-UP CONFIRMATION SUPPRESSION ──
|
|
let pendingDeleteAction = null;
|
|
|
|
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;
|
|
}
|
|
|
|
// ── ACTIONS CRUD (SUPPRESSION SÉCURISÉE) ──
|
|
async function executeBulkDelete() {
|
|
const ids = Array.from(document.querySelectorAll('.film-checkbox:checked')).map(cb => cb.value);
|
|
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 lors de la suppression multiple.");
|
|
|
|
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 lors de la suppression.");
|
|
}
|
|
});
|
|
}
|
|
|
|
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 lors de la suppression.");
|
|
loadDashboardData();
|
|
} catch (err) {
|
|
console.error('Erreur delete :', err);
|
|
alert("Une erreur est survenue lors de la suppression.");
|
|
}
|
|
});
|
|
}
|
|
|
|
// ── MODALES & UI ──
|
|
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;
|
|
document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
|
|
const btn = document.getElementById(`btn-tab-${tabName}`);
|
|
if(btn) btn.classList.add('active');
|
|
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'); }
|
|
function openConfigModal() { document.getElementById('config-modal').classList.add('open'); }
|
|
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';
|
|
}
|
|
|
|
// ── SAUVEGARDE FILM ──
|
|
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); }
|
|
}
|
|
|
|
// ── IMPORT CSV ──
|
|
async function handleCsvUpload(input) {
|
|
if (!input.files || input.files.length === 0) return;
|
|
|
|
const file = input.files[0];
|
|
const formData = new FormData();
|
|
formData.append('csv_file', file);
|
|
formData.append('type', currentAdminTab);
|
|
|
|
try {
|
|
await fetch(`${API_URL}?action=import_csv`, {
|
|
method: 'POST',
|
|
headers: { 'Authorization': localStorage.getItem('token') },
|
|
body: formData
|
|
});
|
|
input.value = '';
|
|
closeConfigModal();
|
|
loadDashboardData();
|
|
} catch (err) { console.error('Erreur import CSV :', err); }
|
|
}
|
|
|
|
// ── SAUVEGARDE CLÉ TMDB ──
|
|
function saveTmdbKey() {
|
|
const input = document.getElementById('tmdb-key-input');
|
|
if (input && input.value) {
|
|
localStorage.setItem('tmdb_key', input.value);
|
|
alert('Clé sauvegardée localement.');
|
|
closeConfigModal();
|
|
}
|
|
}
|
|
|
|
// ── SAUVEGARDE MOT DE PASSE ──
|
|
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); }
|
|
}
|
|
|
|
// ── ENRICHISSEMENT TMDB AUTOMATIQUE ──
|
|
async function enrichirTMDB() {
|
|
const tmdbKey = localStorage.getItem('tmdb_key');
|
|
if (!tmdbKey) {
|
|
alert("Veuillez d'abord sauvegarder votre clé TMDB juste au-dessus !");
|
|
return;
|
|
}
|
|
|
|
// On cherche les films qui n'ont pas d'affiche
|
|
const missingFilms = allItems.filter(f => !f.poster || f.poster.trim() === '');
|
|
|
|
if (missingFilms.length === 0) {
|
|
alert("Bonne nouvelle : tous vos films ont déjà une affiche !");
|
|
return;
|
|
}
|
|
|
|
if (!confirm(`${missingFilms.length} films n'ont pas d'affiche ou de réalisateur. Voulez-vous lancer la récupération TMDB ? (Cela peut prendre un peu de temps)`)) {
|
|
return;
|
|
}
|
|
|
|
const btn = document.getElementById('btn-enrichir');
|
|
if (btn) btn.innerHTML = '<i class="ti ti-loader"></i> Recherche en cours...';
|
|
|
|
let updatedCount = 0;
|
|
|
|
for (let f of missingFilms) {
|
|
try {
|
|
// 1. Recherche du film par titre et année
|
|
const searchRes = await fetch(`https://api.themoviedb.org/3/search/movie?api_key=${tmdbKey}&query=${encodeURIComponent(f.title)}&year=${f.year}&language=fr-FR`);
|
|
const searchData = await searchRes.json();
|
|
|
|
if (searchData.results && searchData.results.length > 0) {
|
|
const movie = searchData.results[0];
|
|
f.poster = movie.poster_path ? `https://image.tmdb.org/t/p/w500${movie.poster_path}` : f.poster;
|
|
|
|
// 2. Recherche du réalisateur
|
|
const creditsRes = await fetch(`https://api.themoviedb.org/3/movie/${movie.id}/credits?api_key=${tmdbKey}`);
|
|
const creditsData = await creditsRes.json();
|
|
|
|
if (creditsData.crew) {
|
|
const director = creditsData.crew.find(c => c.job === 'Director');
|
|
if (director) f.director = director.name;
|
|
}
|
|
|
|
// 3. Sauvegarde automatique en base de données
|
|
await fetch(`${API_URL}?action=save_film`, {
|
|
method: 'POST',
|
|
headers: { 'Authorization': localStorage.getItem('token'), 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(f)
|
|
});
|
|
updatedCount++;
|
|
}
|
|
} catch (e) {
|
|
console.error(`Erreur TMDB pour ${f.title}`, e);
|
|
}
|
|
}
|
|
|
|
alert(`Terminé ! ${updatedCount} affiches et réalisateurs ont été récupérés avec succès.`);
|
|
if (btn) btn.innerHTML = '<i class="ti ti-movie"></i> Lancer la récupération';
|
|
closeConfigModal();
|
|
loadDashboardData();
|
|
} |