Files
mon-petit-cinema/js/admin.js
T
2026-06-21 09:15:27 +02:00

295 lines
11 KiB
JavaScript

const API_URL = '../api.php';
let allItems = [];
let currentAdminTab = 'critique';
let currentPage = 1;
const itemsPerPage = 12;
let searchQuery = '';
let selectedIds = new Set();
// ── 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;
}
// ── BARRE DE PROGRESSION ──
function showProgressModal(total) {
document.getElementById('progress-text').textContent = 'Traitement des films et récupération TMDB...';
document.getElementById('progress-bar').style.width = '0%';
document.getElementById('progress-count').textContent = `0 / ${total}`;
document.getElementById('progress-overlay').classList.add('open');
}
function updateProgressModal(current, total) {
const pct = Math.round((current / total) * 100);
document.getElementById('progress-bar').style.width = pct + '%';
document.getElementById('progress-count').textContent = `${current} / ${total}`;
}
function closeProgressModal() {
document.getElementById('progress-overlay').classList.remove('open');
}
// ── 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));
const searchInput = document.getElementById('search-input');
if (searchInput) {
searchInput.addEventListener('input', () => {
currentPage = 1; // Reset page on search
renderAdminTable();
});
}
// Fix: Select All Checkbox Event
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');
}
});
}
// ── CHARGEMENT DES DONNÉES ──
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); }
}
// ── RENDU DU TABLEAU (FIXED PAGINATION) ──
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() : '';
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;
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);
});
// Render pagination controls
renderPagination(totalPages, filtered.length);
// Update Select All state
const selectAll = document.getElementById('select-all-checkbox');
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();
// Update select-all state
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';
}
}
// ── PAGINATION ──
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; // Hide pagination if only 1 page
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;
}
// ... [Les autres fonctions (Modales, Suppressions, CSV, etc.) restent identiques mais assurez-vous d'utiliser le code nettoyé ci-dessous pour éviter les erreurs de syntaxe] ...