Actualiser js/admin.js
This commit is contained in:
+437
-73
@@ -6,140 +6,504 @@ const itemsPerPage = 12;
|
|||||||
let selectedIds = new Set();
|
let selectedIds = new Set();
|
||||||
let pendingDeleteAction = null;
|
let pendingDeleteAction = null;
|
||||||
|
|
||||||
|
// ── GÉNÉRATEUR D'ÉTOILES ──
|
||||||
|
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 ──
|
||||||
|
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] !== '') 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 === headers.length) {
|
||||||
|
const obj = {};
|
||||||
|
headers.forEach((h, idx) => obj[h] = rows[i][idx]);
|
||||||
|
data.push(obj);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── INITIALISATION ──
|
||||||
document.addEventListener('DOMContentLoaded', () => {
|
document.addEventListener('DOMContentLoaded', () => {
|
||||||
loadDashboardData();
|
loadDashboardData();
|
||||||
initEventListeners();
|
initEventListeners();
|
||||||
document.getElementById('confirm-btn').addEventListener('click', () => {
|
const confirmBtn = document.getElementById('confirm-btn');
|
||||||
if (pendingDeleteAction) pendingDeleteAction();
|
if (confirmBtn) {
|
||||||
closeConfirmModal();
|
confirmBtn.addEventListener('click', () => {
|
||||||
});
|
if (pendingDeleteAction) pendingDeleteAction();
|
||||||
|
closeConfirmModal();
|
||||||
|
});
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
function initEventListeners() {
|
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');
|
const searchInput = document.getElementById('search-input');
|
||||||
if (searchInput) {
|
if (searchInput) {
|
||||||
searchInput.addEventListener('input', () => { currentPage = 1; renderAdminTable(); });
|
searchInput.addEventListener('input', () => {
|
||||||
|
currentPage = 1;
|
||||||
|
renderAdminTable();
|
||||||
|
});
|
||||||
}
|
}
|
||||||
document.getElementById('select-all-checkbox').addEventListener('change', (e) => toggleSelectAll(e.target));
|
|
||||||
|
const selectAll = document.getElementById('select-all-checkbox');
|
||||||
|
if (selectAll) {
|
||||||
|
selectAll.addEventListener('change', (e) => toggleSelectAll(e.target));
|
||||||
|
}
|
||||||
|
|
||||||
document.addEventListener('click', (e) => {
|
document.addEventListener('click', (e) => {
|
||||||
if (e.target.classList.contains('modal-close') || e.target.closest('.modal-close') || e.target.classList.contains('overlay')) {
|
if (e.target.classList.contains('modal-close') || e.target.closest('.modal-close')) {
|
||||||
const overlay = e.target.closest('.overlay') || e.target;
|
const overlay = e.target.closest('.overlay');
|
||||||
if (overlay.classList.contains('overlay')) overlay.classList.remove('open');
|
if (overlay) overlay.classList.remove('open');
|
||||||
|
}
|
||||||
|
if (e.target.classList.contains('overlay')) {
|
||||||
|
e.target.classList.remove('open');
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── CHARGEMENT ──
|
||||||
async function loadDashboardData() {
|
async function loadDashboardData() {
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`${API_URL}?action=get_films`, { cache: 'no-store' });
|
const res = await fetch(`${API_URL}?action=get_films`, { cache: 'no-store' });
|
||||||
allItems = await res.json();
|
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();
|
renderAdminTable();
|
||||||
} catch (err) { console.error('Erreur chargement :', err); }
|
} catch (err) { console.error('Erreur chargement :', err); }
|
||||||
}
|
}
|
||||||
|
|
||||||
function getStarsHTML(rating) {
|
// ── RENDU DU TABLEAU (SANS COLONNE AFFICHE) ──
|
||||||
const r = parseFloat(rating) || 0;
|
|
||||||
const full = Math.floor(r), hasHalf = (r - full) >= 0.5, empty = 5 - Math.ceil(r);
|
|
||||||
return '★'.repeat(full) + (hasHalf ? '<span class="half-star">★</span>' : '') + `<span class="stars-muted">${'☆'.repeat(empty)}</span>`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderAdminTable() {
|
function renderAdminTable() {
|
||||||
const tbody = document.getElementById('admin-table-body');
|
const tbody = document.getElementById('admin-table-body');
|
||||||
if (!tbody) return; tbody.innerHTML = '';
|
if (!tbody) return;
|
||||||
const query = document.getElementById('search-input').value.toLowerCase();
|
tbody.innerHTML = '';
|
||||||
let filtered = allItems.filter(i => i.type === currentAdminTab);
|
|
||||||
if (query) filtered = filtered.filter(f => f.title.toLowerCase().includes(query) || (f.director && f.director.toLowerCase().includes(query)));
|
const searchInput = document.getElementById('search-input');
|
||||||
|
const currentSearch = searchInput ? searchInput.value.toLowerCase() : '';
|
||||||
document.getElementById('admin-count-label').textContent = `${filtered.length} élément(s)`;
|
|
||||||
|
let filtered = allItems.filter(item => item.type === currentAdminTab);
|
||||||
|
|
||||||
|
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)`;
|
||||||
|
|
||||||
|
// --- PAGINATION LOGIC ---
|
||||||
const totalPages = Math.ceil(filtered.length / itemsPerPage) || 1;
|
const totalPages = Math.ceil(filtered.length / itemsPerPage) || 1;
|
||||||
if (currentPage > totalPages) currentPage = totalPages;
|
if (currentPage > totalPages) currentPage = totalPages;
|
||||||
const pageItems = filtered.slice((currentPage - 1) * itemsPerPage, currentPage * itemsPerPage);
|
const startIdx = (currentPage - 1) * itemsPerPage;
|
||||||
|
const pageItems = filtered.slice(startIdx, startIdx + itemsPerPage);
|
||||||
|
// ------------------------
|
||||||
|
|
||||||
pageItems.forEach(f => {
|
pageItems.forEach(f => {
|
||||||
const tr = document.createElement('tr');
|
const tr = document.createElement('tr');
|
||||||
const info = currentAdminTab === 'critique' ? `<span class="tbl-stars">${getStarsHTML(f.rating)}</span>` : `<span class="badge-format">${f.format || '-'}</span>`;
|
const isChecked = selectedIds.has(String(f.id)) ? 'checked' : '';
|
||||||
|
|
||||||
|
// SEULEMENT 6 COLONNES (Plus d'affiche)
|
||||||
tr.innerHTML = `
|
tr.innerHTML = `
|
||||||
<td><input type="checkbox" class="film-checkbox" value="${f.id}" ${selectedIds.has(String(f.id)) ? 'checked' : ''}></td>
|
<td style="text-align:center;">
|
||||||
|
<input type="checkbox" class="film-checkbox" value="${f.id}" ${isChecked} onclick="toggleSingleSelect('${f.id}', this)">
|
||||||
|
</td>
|
||||||
<td><strong>${f.title}</strong></td>
|
<td><strong>${f.title}</strong></td>
|
||||||
<td>${f.year || '-'}</td>
|
<td>${f.year || '-'}</td>
|
||||||
<td>${f.director || '-'}</td>
|
<td>${f.director || '-'}</td>
|
||||||
<td>${info}</td>
|
<td>${currentAdminTab === 'critique' ? `<span class="tbl-stars">${getStarsHTML(f.rating)}</span>` : `<span class="badge-format">${f.format || '-'}</span>`}</td>
|
||||||
<td>
|
<td>
|
||||||
<div class="tbl-actions">
|
<div class="tbl-actions">
|
||||||
<button onclick="openEditModal('${f.id}')"><i class="ti ti-edit"></i></button>
|
<button onclick="openEditModal('${f.id}')" title="Éditer"><i class="ti ti-edit"></i></button>
|
||||||
<button class="del" onclick="deleteSingleFilm('${f.id}')"><i class="ti ti-trash"></i></button>
|
<button class="del" onclick="deleteSingleFilm('${f.id}')" title="Supprimer"><i class="ti ti-trash"></i></button>
|
||||||
</div>
|
</div>
|
||||||
</td>`;
|
</td>`;
|
||||||
tbody.appendChild(tr);
|
tbody.appendChild(tr);
|
||||||
});
|
});
|
||||||
|
|
||||||
document.querySelectorAll('.film-checkbox').forEach(cb => {
|
|
||||||
cb.onchange = (e) => {
|
|
||||||
e.target.checked ? selectedIds.add(e.target.value) : selectedIds.delete(e.target.value);
|
|
||||||
updateBulkBar();
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
renderPagination(totalPages, filtered.length);
|
renderPagination(totalPages, filtered.length);
|
||||||
|
|
||||||
const selectAll = document.getElementById('select-all-checkbox');
|
const selectAll = document.getElementById('select-all-checkbox');
|
||||||
selectAll.checked = pageItems.length > 0 && pageItems.every(f => selectedIds.has(String(f.id)));
|
if (selectAll) {
|
||||||
|
selectAll.checked = pageItems.length > 0 && pageItems.every(f => selectedIds.has(String(f.id)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── SÉLECTION ──
|
||||||
|
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) {
|
function toggleSelectAll(source) {
|
||||||
const filtered = allItems.filter(i => i.type === currentAdminTab);
|
const filtered = allItems.filter(item => item.type === currentAdminTab);
|
||||||
if (source.checked) filtered.forEach(f => selectedIds.add(String(f.id)));
|
if (source.checked) {
|
||||||
else filtered.forEach(f => selectedIds.delete(String(f.id)));
|
filtered.forEach(f => selectedIds.add(String(f.id)));
|
||||||
document.querySelectorAll('.film-checkbox').forEach(cb => cb.checked = selectedIds.has(cb.value));
|
} else {
|
||||||
|
filtered.forEach(f => selectedIds.delete(String(f.id)));
|
||||||
|
}
|
||||||
|
document.querySelectorAll('.film-checkbox').forEach(cb => {
|
||||||
|
cb.checked = selectedIds.has(cb.value);
|
||||||
|
});
|
||||||
updateBulkBar();
|
updateBulkBar();
|
||||||
}
|
}
|
||||||
|
|
||||||
function updateBulkBar() {
|
function updateBulkBar() {
|
||||||
const bar = document.getElementById('bulk-actions-bar');
|
const bulkBar = document.getElementById('bulk-actions-bar');
|
||||||
const cnt = document.getElementById('bulk-count');
|
const bulkCount = document.getElementById('bulk-count');
|
||||||
if (selectedIds.size > 0) {
|
if (selectedIds.size > 0) {
|
||||||
bar.style.display = 'flex'; cnt.textContent = selectedIds.size;
|
if (bulkBar) bulkBar.style.display = 'flex';
|
||||||
|
if (bulkCount) bulkCount.textContent = selectedIds.size;
|
||||||
} else {
|
} else {
|
||||||
bar.style.display = 'none';
|
if (bulkBar) bulkBar.style.display = 'none';
|
||||||
document.getElementById('select-all-checkbox').checked = false;
|
const selectAll = document.getElementById('select-all-checkbox');
|
||||||
|
if (selectAll) selectAll.checked = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── PAGINATION ──
|
||||||
function renderPagination(totalPages, totalItems) {
|
function renderPagination(totalPages, totalItems) {
|
||||||
const c = document.getElementById('pagination-container'); c.innerHTML = '';
|
const container = document.getElementById('pagination-container');
|
||||||
if (totalItems === 0) { c.innerHTML = '<p style="color:var(--muted); text-align:center; width:100%;">Aucun élément trouvé.</p>'; return; }
|
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;
|
if (totalPages <= 1) return;
|
||||||
const info = document.createElement('span'); info.className = 'pagination-info'; info.textContent = `Page ${currentPage} / ${totalPages}`; c.appendChild(info);
|
|
||||||
const prev = document.createElement('button'); prev.innerHTML = '<i class="ti ti-chevron-left"></i>'; prev.disabled = currentPage === 1; prev.onclick = () => { currentPage--; renderAdminTable(); }; c.appendChild(prev);
|
|
||||||
|
|
||||||
const max = 5; let s = Math.max(1, currentPage - Math.floor(max/2)), e = Math.min(totalPages, s + max - 1);
|
|
||||||
if (e - s + 1 < max) s = Math.max(1, e - max + 1);
|
|
||||||
if (s > 1) { c.appendChild(makeBtn(1)); if (s > 2) c.appendChild(makeEll()); }
|
|
||||||
for (let i = s; i <= e; i++) c.appendChild(makeBtn(i));
|
|
||||||
if (e < totalPages) { if (e < totalPages - 1) c.appendChild(makeEll()); c.appendChild(makeBtn(totalPages)); }
|
|
||||||
|
|
||||||
const next = document.createElement('button'); next.innerHTML = '<i class="ti ti-chevron-right"></i>'; next.disabled = currentPage === totalPages; next.onclick = () => { currentPage++; renderAdminTable(); }; c.appendChild(next);
|
|
||||||
}
|
|
||||||
const makeBtn = (n) => { const b = document.createElement('button'); b.textContent = n; if (n === currentPage) b.classList.add('active'); b.onclick = () => { currentPage = n; renderAdminTable(); }; return b; };
|
|
||||||
const makeEll = () => { const s = document.createElement('span'); s.textContent = '...'; s.style.color = 'var(--muted)'; s.style.padding = '0 0.5rem'; return s; };
|
|
||||||
|
|
||||||
function switchAdminTab(tab) {
|
const info = document.createElement('span');
|
||||||
currentAdminTab = tab; currentPage = 1; selectedIds.clear();
|
info.className = 'pagination-info';
|
||||||
document.getElementById('search-input').value = '';
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── MODALES & UI ──
|
||||||
|
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 = '';
|
||||||
document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
|
document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
|
||||||
document.getElementById(`btn-tab-${tab}`).classList.add('active');
|
const btn = document.getElementById(`btn-tab-${tabName}`);
|
||||||
|
if (btn) btn.classList.add('active');
|
||||||
|
toggleFormFields();
|
||||||
renderAdminTable();
|
renderAdminTable();
|
||||||
}
|
}
|
||||||
|
|
||||||
function showConfirmModal(fn) { pendingDeleteAction = fn; document.getElementById('confirm-modal').classList.add('open'); }
|
function openAddModal() {
|
||||||
function closeConfirmModal() { document.getElementById('confirm-modal').classList.remove('open'); pendingDeleteAction = null; }
|
document.getElementById('film-form').reset();
|
||||||
async function executeBulkDelete() { if (selectedIds.size === 0) return; showConfirmModal(async () => { await post(`${API_URL}?action=bulk_delete`, { ids: Array.from(selectedIds), type: currentAdminTab }); selectedIds.clear(); updateBulkBar(); loadDashboardData(); }); }
|
document.getElementById('f-id').value = '';
|
||||||
async function deleteSingleFilm(id) { showConfirmModal(async () => { await del(`${API_URL}?action=delete_film&id=${id}&type=${currentAdminTab}`); loadDashboardData(); }); }
|
toggleFormFields();
|
||||||
|
document.getElementById('admin-modal').classList.add('open');
|
||||||
|
}
|
||||||
|
|
||||||
function openAddModal() { document.getElementById('film-form').reset(); document.getElementById('f-id').value = ''; document.getElementById('admin-modal').classList.add('open'); }
|
function openEditModal(id) {
|
||||||
function openEditModal(id) { const f = allItems.find(x => String(x.id) === String(id)); if (!f) return; document.getElementById('f-id').value = f.id; document.getElementById('f-title').value = f.title; document.getElementById('f-year').value = f.year || ''; document.getElementById('f-director').value = f.director || ''; document.getElementById('f-poster').value = f.poster || ''; document.getElementById('admin-modal').classList.add('open'); }
|
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 openConfigModal() { document.getElementById('config-modal').classList.add('open'); }
|
||||||
function logout() { localStorage.removeItem('token'); window.location.href = 'login.html'; }
|
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';
|
||||||
|
}
|
||||||
|
|
||||||
const post = async (url, body) => await fetch(url, { method: 'POST', headers: { 'Authorization': localStorage.getItem('token'), 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
|
// ── SAUVEGARDES ──
|
||||||
const del = async (url) => await fetch(url, { method: 'DELETE', headers: { 'Authorization': localStorage.getItem('token') } });
|
async function saveFilmForm(e) {
|
||||||
document.getElementById('film-form').onsubmit = async (e) => { e.preventDefault(); await post(`${API_URL}?action=save_film`, Object.fromEntries(new FormData(e.target))); document.getElementById('admin-modal').classList.remove('open'); loadDashboardData(); };
|
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); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleCsvUpload(input) {
|
||||||
|
if (!input.files || input.files.length === 0) return;
|
||||||
|
const file = input.files[0];
|
||||||
|
input.value = '';
|
||||||
|
try {
|
||||||
|
const text = await file.text();
|
||||||
|
const allData = parseCSV(text);
|
||||||
|
if (allData.length === 0) { alert('❌ Le fichier CSV est vide ou mal formaté.'); return; }
|
||||||
|
closeConfigModal();
|
||||||
|
|
||||||
|
const progressOverlay = document.getElementById('progress-overlay');
|
||||||
|
const progressBar = document.getElementById('progress-bar');
|
||||||
|
const progressCount = document.getElementById('progress-count');
|
||||||
|
if(progressOverlay) progressOverlay.classList.add('open');
|
||||||
|
|
||||||
|
const batchSize = 5;
|
||||||
|
let processed = 0;
|
||||||
|
for (let i = 0; i < allData.length; i += batchSize) {
|
||||||
|
const batch = allData.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 sur un lot:', err); }
|
||||||
|
processed += batch.length;
|
||||||
|
const pct = Math.round((processed / allData.length) * 100);
|
||||||
|
if(progressBar) progressBar.style.width = pct + '%';
|
||||||
|
if(progressCount) progressCount.textContent = `${processed} / ${allData.length}`;
|
||||||
|
}
|
||||||
|
if(progressOverlay) progressOverlay.classList.remove('open');
|
||||||
|
alert(`✅ Import terminé ! ${allData.length} élément(s) traité(s).`);
|
||||||
|
loadDashboardData();
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Erreur lecture CSV :', err);
|
||||||
|
alert('Impossible de lire le fichier CSV.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveTmdbKey() {
|
||||||
|
const input = document.getElementById('tmdb-key-input');
|
||||||
|
if (input && input.value) {
|
||||||
|
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: 'tmdb_api_key', key_value: input.value })
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
if (data.success) { alert('✅ Clé API sauvegardée !'); closeConfigModal(); }
|
||||||
|
else { alert('❌ Erreur : ' + (data.error || 'Impossible de sauvegarder.')); }
|
||||||
|
} catch (err) { alert('Erreur de communication avec le 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 || !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); }
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user