/**
 * Edit Collection Page Script
 * ----------------------------
 * Handles fetching existing data, populating form, and updating collection.
 */

document.addEventListener('DOMContentLoaded', function () {

    const collectionId = document.getElementById('collectionId').value;

    // 1. Initialize Quill Editor
    const quill = new Quill('#collectionDescription', {
        theme: 'snow',
        modules: {
            toolbar: [
                ['bold', 'italic', 'underline', 'strike'],
                [{ 'list': 'ordered' }, { 'list': 'bullet' }],
                [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                ['link', 'clean']
            ]
        },
        placeholder: 'Enter collection description...'
    });

    // 2. Load Parent Collections & Current Collection Data
    loadInitialData();

    async function loadInitialData() {
        try {
            // Load Parent Options first
            const parentsResponse = await fetch('api/collections.php?limit=100');
            const parentsData = await parentsResponse.json();

            const parentSelect = document.getElementById('parentCollection');
            if (parentsData.success && parentsData.data) {
                parentsData.data.forEach(collection => {
                    // Prevent selecting itself as parent
                    if (collection.id != collectionId) {
                        const option = document.createElement('option');
                        option.value = collection.id;
                        option.textContent = collection.name;
                        parentSelect.appendChild(option);
                    }
                });
            }

            // Load Collection Details
            const collectionResponse = await fetch(`api/collections.php?id=${collectionId}`);
            const collectionData = await collectionResponse.json();

            if (collectionData.success) {
                populateForm(collectionData.data);
            } else {
                alert('Failed to load collection details: ' + collectionData.message);
                window.location.href = 'collections.php';
            }

        } catch (error) {
            console.error('Error loading data:', error);
            alert('An error occurred while loading data.');
        }
    }

    function populateForm(data) {
        // Basic Fields
        document.getElementById('collectionTitle').value = data.name || '';
        document.getElementById('collectionSlug').value = data.slug || '';
        document.getElementById('collectionStatus').value = (data.is_active === 1 || data.is_active === '1') ? '1' : '0';
        document.getElementById('parentCollection').value = data.parent_id || '';
        document.getElementById('createdAtText').textContent = data.created_at || 'N/A';

        // SEO Fields
        document.getElementById('seoTitle').value = data.seo_title || '';
        document.getElementById('seoDescription').value = data.seo_description || '';
        document.querySelector('.seo-title-preview').textContent = data.seo_title || data.name || 'Collection Title';
        document.querySelector('.seo-description-preview').textContent = data.seo_description || 'Collection description will appear here...';

        // Update char counts
        if (data.seo_title) document.getElementById('seoTitleCount').textContent = data.seo_title.length;
        if (data.seo_description) document.getElementById('seoDescriptionCount').textContent = data.seo_description.length;

        // Description (Quill)
        if (data.description) {
            quill.root.innerHTML = data.description;
        }

        // Image
        if (data.image) {
            document.getElementById('imagePreview').src = data.image;
            document.getElementById('dropZone').style.display = 'none';
            document.getElementById('imagePreviewContainer').style.display = 'block';
        }
    }

    // 3. Image Upload Handling (Same as Add)
    const dropZone = document.getElementById('dropZone');
    const mediaFileInput = document.getElementById('mediaFileInput');
    const addMediaBtn = document.getElementById('addMediaBtn');
    const imagePreviewContainer = document.getElementById('imagePreviewContainer');
    const imagePreview = document.getElementById('imagePreview');
    const removeImageBtn = document.getElementById('removeImageBtn');

    addMediaBtn.addEventListener('click', () => mediaFileInput.click());
    dropZone.addEventListener('click', (e) => {
        if (e.target !== addMediaBtn && !addMediaBtn.contains(e.target)) {
            mediaFileInput.click();
        }
    });

    mediaFileInput.addEventListener('change', function () {
        handleFile(this.files[0]);
    });

    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        dropZone.addEventListener(eventName, preventDefaults, false);
    });

    function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }

    dropZone.addEventListener('drop', function (e) {
        const dt = e.dataTransfer;
        handleFile(dt.files[0]);
    });

    function handleFile(file) {
        if (file && file.type.startsWith('image/')) {
            const reader = new FileReader();
            reader.onload = function (e) {
                imagePreview.src = e.target.result;
                dropZone.style.display = 'none';
                imagePreviewContainer.style.display = 'block';
            };
            reader.readAsDataURL(file);
        }
    }

    removeImageBtn.addEventListener('click', function (e) {
        e.stopPropagation();
        mediaFileInput.value = '';
        imagePreview.src = '';
        imagePreviewContainer.style.display = 'none';
        dropZone.style.display = 'block';
    });

    // 4. SEO Preview Logic (Same as Add)
    // ... (Keep existing Logic for live updates) ...
    const seoTitle = document.getElementById('seoTitle');
    const seoDescription = document.getElementById('seoDescription');
    const seoTitlePreview = document.querySelector('.seo-title-preview');
    const seoDescriptionPreview = document.querySelector('.seo-description-preview');
    const seoTitleCount = document.getElementById('seoTitleCount');
    const seoDescriptionCount = document.getElementById('seoDescriptionCount');

    if (seoTitle) {
        seoTitle.addEventListener('input', function () {
            const length = this.value.length;
            seoTitleCount.textContent = length;
            seoTitlePreview.textContent = this.value || 'Collection Title';
        });
    }

    if (seoDescription) {
        seoDescription.addEventListener('input', function () {
            const length = this.value.length;
            seoDescriptionCount.textContent = length;
            seoDescriptionPreview.textContent = this.value || 'Collection description will appear here...';
        });
    }

    // 5. Form Submission (Update)
    const form = document.getElementById('editCollectionForm');
    const saveBtn = document.getElementById('saveBtn');

    form.addEventListener('submit', function (e) {
        e.preventDefault();

        document.getElementById('descriptionInput').value = quill.root.innerHTML;

        const originalBtnText = saveBtn.innerHTML;
        saveBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Updating...';
        saveBtn.disabled = true;

        const formData = new FormData(this);
        // Important: Add a field to indicate this is an update if using POST
        formData.append('action', 'update');

        fetch('api/collections.php', {
            method: 'POST',
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Collection updated successfully!');
                    window.location.href = 'collections.php';
                } else {
                    alert(data.message || 'Failed to update collection');
                    saveBtn.innerHTML = originalBtnText;
                    saveBtn.disabled = false;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred. Please try again.');
                saveBtn.innerHTML = originalBtnText;
                saveBtn.disabled = false;
            });
    });

    // 6. Delete Collection Logic
    const deleteBtn = document.getElementById('deleteCollectionBtn');
    const deleteModalEl = document.getElementById('deleteConfirmationModal');
    const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');

    if (deleteBtn && deleteModalEl && confirmDeleteBtn) {
        const deleteModal = new bootstrap.Modal(deleteModalEl);

        // Open Modal
        deleteBtn.addEventListener('click', function (e) {
            e.preventDefault();
            const name = document.getElementById('collectionTitle').value;
            document.getElementById('deleteCollectionName').textContent = name || 'this collection';
            deleteModal.show();
        });

        // Handle Confirm
        confirmDeleteBtn.addEventListener('click', function () {
            const id = document.getElementById('collectionId').value;
            if (!id) return;

            const btn = this;
            const originalText = btn.innerHTML;
            btn.disabled = true;
            btn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Deleting...';

            const params = new URLSearchParams();
            params.append('action', 'delete');
            params.append('id', id);

            fetch('api/collections.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: params
            })
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        window.location.href = 'collections.php';
                    } else {
                        alert(data.message || 'Failed to delete collection');
                        btn.disabled = false;
                        btn.innerHTML = originalText;
                    }
                })
                .catch(err => {
                    console.error(err);
                    alert('An error occurred during deletion.');
                    btn.disabled = false;
                    btn.innerHTML = originalText;
                });
        });
    }
});
