document.addEventListener('DOMContentLoaded', function() { // Initialisation de l'éditeur Quill const quill = new Quill('#editor', { theme: 'snow', modules: { toolbar: [ ['bold', 'italic', 'underline'], [{ 'list': 'ordered'}, { 'list': 'bullet' }], ['clean'] ] } }); // Variables globales const chaptersList = document.getElementById('chaptersList'); const modal = document.getElementById('chapterEditor'); const addChapterBtn = document.getElementById('addChapter'); let currentChapterId = null; const storyId = document.querySelector('input[name="id"]')?.value; // Initialisation du tri par glisser-déposer if (chaptersList) { new Sortable(chaptersList, { animation: 150, ghostClass: 'sortable-ghost', onEnd: async function() { // Récupérer le nouvel ordre des chapitres const chapters = Array.from(chaptersList.children).map((item, index) => ({ id: item.dataset.id, order: index })); try { const response = await fetch('api/reorder-chapters.php', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ storyId: storyId, chapters: chapters }) }); if (!response.ok) { throw new Error('Erreur lors de la réorganisation'); } // Mettre à jour les numéros affichés chapters.forEach((chapter, index) => { const element = document.querySelector(`[data-id="${chapter.id}"] .chapter-number`); if (element) { element.textContent = index + 1; } }); } catch (error) { console.error('Erreur:', error); alert('Erreur lors de la réorganisation des chapitres'); } } }); } // Gestion de l'ajout d'un nouveau chapitre if (addChapterBtn) { addChapterBtn.addEventListener('click', () => { currentChapterId = null; document.getElementById('chapterTitle').value = ''; quill.setContents([{ insert: '\n' }]); modal.style.display = 'block'; }); } // Gestion de l'édition d'un chapitre chaptersList?.addEventListener('click', async (e) => { if (e.target.matches('.edit-chapter')) { const chapterItem = e.target.closest('.chapter-item'); currentChapterId = chapterItem.dataset.id; try { const response = await fetch(`api/get-chapter.php?storyId=${storyId}&chapterId=${currentChapterId}`); if (!response.ok) throw new Error('Erreur lors de la récupération du chapitre'); const chapter = await response.json(); document.getElementById('chapterTitle').value = chapter.title; try { if (typeof chapter.content === 'string') { quill.root.innerHTML = chapter.content; } else { quill.setContents(chapter.content); } } catch (error) { console.error('Erreur lors du chargement du contenu:', error); quill.root.innerHTML = chapter.content; } modal.style.display = 'block'; } catch (error) { console.error('Erreur:', error); alert('Erreur lors de la récupération du chapitre'); } } }); // Gestion de la suppression d'un chapitre chaptersList?.addEventListener('click', async (e) => { if (e.target.matches('.delete-chapter')) { if (!confirm('Voulez-vous vraiment supprimer ce chapitre ?')) return; const chapterItem = e.target.closest('.chapter-item'); const chapterId = chapterItem.dataset.id; try { const response = await fetch('api/delete-chapter.php', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ storyId: storyId, chapterId: chapterId }) }); if (!response.ok) throw new Error('Erreur lors de la suppression'); chapterItem.remove(); // Mettre à jour les numéros des chapitres document.querySelectorAll('.chapter-number').forEach((num, index) => { num.textContent = index + 1; }); } catch (error) { console.error('Erreur:', error); alert('Erreur lors de la suppression du chapitre'); } } }); // Gestion de la sauvegarde d'un chapitre document.getElementById('saveChapter')?.addEventListener('click', async () => { const title = document.getElementById('chapterTitle').value; if (!title.trim()) { alert('Le titre du chapitre est requis'); return; } try { const response = await fetch('api/save-chapter.php', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ storyId: storyId, chapterId: currentChapterId, title: title, content: quill.root.innerHTML }) }); if (!response.ok) throw new Error('Erreur lors de la sauvegarde'); const result = await response.json(); if (!currentChapterId) { // Nouveau chapitre - ajouter à la liste const newChapter = document.createElement('div'); newChapter.className = 'chapter-item'; newChapter.dataset.id = result.chapterId; newChapter.innerHTML = ` ${document.querySelectorAll('.chapter-item').length + 1}

${title}

`; chaptersList.appendChild(newChapter); } else { // Mise à jour du titre dans la liste const chapterItem = document.querySelector(`[data-id="${currentChapterId}"] .chapter-title`); if (chapterItem) { chapterItem.textContent = title; } } modal.style.display = 'none'; } catch (error) { console.error('Erreur:', error); alert('Erreur lors de la sauvegarde du chapitre'); } }); // Fermeture de la modale document.getElementById('cancelEdit')?.addEventListener('click', () => { modal.style.display = 'none'; }); // Fermeture de la modale en cliquant en dehors modal?.addEventListener('click', (e) => { if (e.target === modal) { modal.style.display = 'none'; } }); });