
/**
 * Edit Product Page Script
 * -----------------------
 * Handles Quill editor, Image Upload, and Dynamic Variants Generation (Cartesian) with Data Restoration.
 */

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

    // --- 1. Initialize Quill ---
    var quill = new Quill('#productDescription', {
        theme: 'snow',
        placeholder: 'Write a description...',
        modules: {
            toolbar: [
                [{ 'header': [1, 2, false] }],
                ['bold', 'italic', 'underline'],
                ['image', 'code-block']
            ]
        }
    });

    // --- 2. Url Params ---
    const urlParams = new URLSearchParams(window.location.search);
    const productSlug = urlParams.get('slug');

    if (!productSlug) {
        alert('No product specified');
        window.location.href = 'products.php';
        return;
    }

    // --- 3. Image Handling ---
    let uploadedImages = [];
    const imageUploadInput = document.getElementById('mediaFileInput');
    const imageGrid = document.getElementById('imageGrid');

    imageUploadInput.addEventListener('change', function (e) {
        const files = Array.from(e.target.files);
        files.forEach(file => {
            const reader = new FileReader();
            reader.onload = function (ev) {
                uploadedImages.push({
                    id: Date.now() + Math.random(), // Temp frontend ID
                    src: ev.target.result,
                    file: file
                });
                renderImageGrid();
            }
            reader.readAsDataURL(file);
        });
        e.target.value = ''; // reset
    });

    function renderImageGrid() {
        if (uploadedImages.length === 0) {
            imageGrid.style.display = 'none';
            return;
        }
        imageGrid.style.display = 'grid';
        imageGrid.innerHTML = '';
        uploadedImages.forEach((img) => {
            const card = document.createElement('div');
            card.className = `image-card`;
            card.innerHTML = `
                <img src="${img.src}" class="image-card-preview">
                <div class="image-card-overlay">
                    <div class="image-card-actions">
                        <button type="button" class="image-card-btn delete" onclick="removeNewImage(${img.id})"><i class="iconoir-trash"></i></button>
                    </div>
                </div>
            `;
            imageGrid.appendChild(card);
        });
    }

    window.removeNewImage = function (id) {
        const index = uploadedImages.findIndex(img => img.id === id);
        if (index > -1) {
            uploadedImages.splice(index, 1);
            renderImageGrid();
        }
    };


    // --- 4. Load & Populate Data ---
    // Store loaded variants for matching Cartesian combos
    let loadedVariants = [];

    async function fetchProductData(slug) {
        try {
            const res = await fetch(`api/products.php?slug=${slug}`);
            const json = await res.json();

            if (!json.success) {
                alert(json.message);
                window.location.href = 'products.php';
                return;
            }

            const data = json.data;

            // Populate Fields
            document.getElementById('productId').value = data.id;
            document.getElementById('productTitle').value = data.title;
            quill.root.innerHTML = data.description || '';
            document.getElementById('productStatus').value = data.status;

            // Simple Product Fields
            const simplePrice = document.getElementById('simplePrice');
            const simpleSku = document.getElementById('simpleSku');
            const simpleInv = document.getElementById('simpleInventory');
            if (simplePrice) simplePrice.value = data.price || '0.00';
            if (simpleSku) simpleSku.value = data.sku || '';
            if (simpleInv) simpleInv.value = data.inventory_quantity || 0;

            // SEO
            document.getElementById('seoTitle').value = data.seo_title || '';
            document.getElementById('seoDescription').value = data.seo_description || '';
            if (window.updateSeoPreview) updateSeoPreview();

            // Existing Images
            if (data.images && data.images.length > 0) {
                const existingContainer = document.getElementById('existingImages');
                const list = document.getElementById('existingImagesList');
                existingContainer.style.display = 'block';

                data.images.forEach(img => {
                    const div = document.createElement('div');
                    div.className = 'position-relative border rounded p-1';
                    div.innerHTML = `
                        <img src="${img.image_path}" style="width: 100px; height: 100px; object-fit: cover;">
                        <button type="button" class="btn btn-sm btn-danger position-absolute top-0 end-0 m-1 p-0 px-1" title="Delete" onclick="deleteExistingImage(this)">×</button>
                        <input type="hidden" name="existing_images[]" value="${img.image_path}"> 
                    `;
                    list.appendChild(div);
                });
            }

            // Collections/Categories
            if (data.collections_data && data.collections_data.length > 0) {
                data.collections_data.forEach(col => {
                    addCollection({ id: col.collection_id, name: col.name });
                });
            }

            // Product Options (Structured) - Load FIRST
            if (data.options && data.options.length > 0) {
                productOptions = data.options.map(opt => ({
                    name: opt.name,
                    values: opt.values || []
                }));
            }

            // Variants - Load SECOND
            // We store these to match against generated Cartesian rows
            if (data.variants && data.variants.length > 0) {
                loadedVariants = data.variants;
            }

            // Initialize Variants Logic
            populateVariants(); // Trigger full render

        } catch (e) {
            console.error(e);
            alert('Error loading product data');
        }
    }

    // --- 5. Collections Logic ---
    let allCollections = [];
    let selectedCollectionIds = new Set();
    const categorySearch = document.getElementById('categorySearch');
    const searchResults = document.getElementById('categorySearchResults');
    const selectedContainer = document.getElementById('selectedCategories');
    const inputsContainer = document.getElementById('collectionInputsContainer');

    loadCollections();

    async function loadCollections() {
        try {
            const resCat = await fetch('api/collections.php?limit=100&status=active');
            const jsonCat = await resCat.json();
            if (jsonCat.success) allCollections = jsonCat.data;
        } catch (e) { console.error(e); }
    }

    categorySearch.addEventListener('input', function (e) {
        const query = e.target.value.toLowerCase();
        if (query.length < 1) { searchResults.style.display = 'none'; return; }
        const filtered = allCollections.filter(c => c.name.toLowerCase().includes(query) && !selectedCollectionIds.has(c.id));
        renderSearchResults(filtered);
    });

    function renderSearchResults(collections) {
        searchResults.innerHTML = '';
        if (collections.length === 0) { searchResults.style.display = 'none'; return; }
        collections.forEach(c => {
            const item = document.createElement('a');
            item.href = '#';
            item.className = 'list-group-item list-group-item-action';
            item.textContent = c.name;
            item.onclick = (e) => { e.preventDefault(); addCollection(c); };
            searchResults.appendChild(item);
        });
        searchResults.style.display = 'block';
    }

    window.addCollection = function (collection) {
        if (selectedCollectionIds.has(collection.id)) return;
        selectedCollectionIds.add(collection.id);

        const badge = document.createElement('span');
        badge.className = 'badge bg-primary-subtle text-primary p-2 d-flex align-items-center gap-2';
        badge.innerHTML = `${collection.name} <i class="iconoir-cancel fs-6" style="cursor:pointer" onclick="removeCollection(${collection.id}, this)"></i>`;
        selectedContainer.appendChild(badge);

        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'collection_ids[]';
        input.value = collection.id;
        input.id = `col-input-${collection.id}`;
        inputsContainer.appendChild(input);

        categorySearch.value = '';
        searchResults.style.display = 'none';
    }

    window.removeCollection = function (id, iconElement) {
        selectedCollectionIds.delete(id);
        iconElement.parentElement.remove();
        const input = document.getElementById(`col-input-${id}`);
        if (input) input.remove();
    }

    // --- 6. Variants Logic (Cartesian Auto-Generator) ---
    let productOptions = [];

    // Helper: Cartesian Product
    function cartesian(args) {
        var r = [], max = args.length - 1;
        function helper(arr, i) {
            for (var j = 0, l = args[i].length; j < l; j++) {
                var a = arr.slice(0);
                a.push(args[i][j]);
                if (i == max) r.push(a);
                else helper(a, i + 1);
            }
        }
        helper([], 0);
        return r;
    }

    // Helper: Retrieve current UI data to preserve edits when re-rendering
    function getExistingRowData() {
        const rows = document.querySelectorAll('#variantsTable tbody tr');
        const dataMap = {};
        rows.forEach(row => {
            const keyParts = [];
            row.querySelectorAll('.variant-option-value').forEach(input => {
                keyParts.push(input.value);
            });
            const key = keyParts.join('/');
            if (key) {
                // Must also grab the ID if present
                const idInput = row.querySelector('input[name*="[id]"]');
                dataMap[key] = {
                    id: idInput ? idInput.value : '',
                    price: row.querySelector('.variant-price').value,
                    sku: row.querySelector('.variant-sku').value,
                    inventory: row.querySelector('.variant-inventory').value
                };
            }
        });
        return dataMap;
    }

    // Helper: Find loaded variant by option values
    function findLoadedVariant(comboValues, optionNames) {
        // comboValues: ['Red', 'S']
        // optionNames: ['Color', 'Size']
        // loadedVariants: [{id: 1, options: {Color: 'Red', Size: 'S'}}, ...]

        return loadedVariants.find(v => {
            if (!v.options) return false;
            // Check if every option matches
            return optionNames.every((name, idx) => v.options[name] === comboValues[idx]);
        });
    }

    function populateVariants() {
        const container = document.getElementById('variantsContainer');
        const simplePricing = document.getElementById('simpleProductPricing');

        // Hide/Show logic
        const hasOptions = productOptions.length > 0;
        if (hasOptions) {
            if (simplePricing) simplePricing.style.display = 'none';
        } else {
            if (simplePricing) simplePricing.style.display = 'block';
        }

        const isTableVisible = hasOptions ? 'block' : 'none';

        // 1. Generate Headers
        let optionHeaders = '';
        if (hasOptions) {
            optionHeaders = productOptions.map(opt => `<th>${opt.name || 'Option'}</th>`).join('');
        } else {
            optionHeaders = `<th>Variant Name</th>`;
        }

        // 2. Render Wrapper
        container.innerHTML = `
            <!-- Options Generator Section -->
            <div class="card mb-3">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h4 class="card-title mb-0">Product Options</h4>
                    <button type="button" class="btn btn-sm btn-outline-primary" id="addOptionBtn">
                        <i class="iconoir-plus"></i> Add Option
                    </button>
                </div>
                <div class="card-body">
                    <div id="optionsList">
                        <p class="text-muted small">Add options like "Color" or "Size".</p>
                    </div>
                </div>
            </div>

            <!-- Variants Table Section -->
            <div class="card" id="variantsTableCard" style="display: ${isTableVisible};">
                <div class="card-header"><h4 class="card-title mb-0">Variants Preview</h4></div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered align-middle" id="variantsTable">
                            <thead class="table-light">
                                <tr>
                                    ${optionHeaders}
                                    <th>Price</th>
                                    <th>SKU</th>
                                    <th>Inventory</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </div>
            </div>
        `;

        // 3. Bind Add Option Event
        document.getElementById('addOptionBtn').addEventListener('click', () => {
            productOptions.push({ name: '', values: [] });
            refreshOptionsList();
            renderTableRows();
            populateVariants(); // Re-toggle visibility if needed (e.g. from 0 to 1 option)
        });

        refreshOptionsList();
        renderTableRows();
    }

    function refreshOptionsList() {
        const container = document.getElementById('optionsList');
        container.innerHTML = '';

        if (productOptions.length === 0) {
            container.innerHTML = '<p class="text-muted small">Add options like "Color" or "Size".</p>';
            return;
        }

        productOptions.forEach((opt, idx) => {
            const row = document.createElement('div');
            row.className = 'mb-3 p-3 border rounded bg-light';
            row.innerHTML = `
                <div class="d-flex justify-content-between mb-2">
                    <label class="form-label fw-bold">Option Name</label>
                    <button type="button" class="btn btn-sm btn-link text-danger p-0" onclick="removeOption(${idx})">Remove</button>
                </div>
                <input type="text" class="form-control mb-2 option-name-input" data-index="${idx}" value="${opt.name}" placeholder="e.g. Flavor">
                
                <label class="form-label small text-muted">Option Values</label>
                <div class="d-flex flex-wrap gap-2 mb-2" id="values-container-${idx}">
                    ${opt.values.map((val, vIdx) => `
                        <span class="badge bg-white text-dark border px-2 py-1 d-flex align-items-center gap-2">
                            ${val}
                            <i class="iconoir-cancel fs-6 text-muted" style="cursor:pointer" onclick="removeValue(${idx}, ${vIdx})"></i>
                        </span>
                    `).join('')}
                </div>
                <div class="input-group input-group-sm">
                    <input type="text" class="form-control new-value-input" id="newValue-${idx}" placeholder="Add value (e.g. Strawberry) & Press Enter">
                    <button class="btn btn-outline-secondary" type="button" onclick="addValue(${idx})">Add</button>
                </div>
            `;
            container.appendChild(row);

            const nameInput = row.querySelector('.option-name-input');
            nameInput.addEventListener('input', (e) => {
                productOptions[idx].name = e.target.value;
                updateHeader(idx, e.target.value);
            });

            const valInput = row.querySelector('.new-value-input');
            valInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    addValue(idx);
                }
            });
        });
    }

    function renderTableRows() {
        // Collect current UI edits first
        const uiData = getExistingRowData();

        const tbody = document.querySelector('#variantsTable tbody');
        if (!tbody) return;
        tbody.innerHTML = '';

        if (productOptions.length === 0) return;

        const validOptions = productOptions.filter(o => o.values.length > 0);
        if (validOptions.length === 0) {
            const tableCard = document.getElementById('variantsTableCard');
            if (tableCard) tableCard.style.display = 'none';
            return;
        }

        // Explicitly show table if we have options
        const tableCard = document.getElementById('variantsTableCard');
        if (tableCard) tableCard.style.display = 'block';

        const valueArrays = validOptions.map(o => o.values);
        const optionNames = validOptions.map(o => o.name);
        const combinations = cartesian(valueArrays);

        combinations.forEach((combo, idx) => {
            const key = combo.join('/');

            // Priority for recovering data: Check UI edits -> Check loaded DB variants -> Default
            let idVal = '';
            let priceVal = '0.00';
            let skuVal = `SKU-${Date.now().toString().slice(-6)}-${idx}`;
            let invVal = 0;

            if (uiData[key]) {
                // Recover matching UI edit
                idVal = uiData[key].id;
                priceVal = uiData[key].price;
                skuVal = uiData[key].sku;
                invVal = uiData[key].inventory;
            } else {
                // Try to find in original loaded data
                const dbVariant = findLoadedVariant(combo, optionNames);
                if (dbVariant) {
                    idVal = dbVariant.id;
                    priceVal = dbVariant.price;
                    skuVal = dbVariant.sku;
                    invVal = dbVariant.inventory_quantity;
                }
            }

            const tr = document.createElement('tr');

            let cellsHtml = '';
            combo.forEach((val, cIdx) => {
                const optName = validOptions[cIdx].name;
                cellsHtml += `
                    <td>
                        <input type="hidden" class="variant-option-value" 
                               name="variants[${idx}][options][${optName}]" 
                               data-option-name="${optName}"
                               value="${val}">
                        ${val}
                    </td>
                `;
            });

            tr.innerHTML = `
                <input type="hidden" name="variants[${idx}][id]" value="${idVal}">
                ${cellsHtml}
                <td>
                    <div class="input-group input-group-sm">
                        <span class="input-group-text">$</span>
                        <input type="number" class="form-control variant-price" name="variants[${idx}][price]" value="${priceVal}" step="0.01">
                    </div>
                </td>
                <td>
                    <input type="text" class="form-control form-control-sm variant-sku" name="variants[${idx}][sku]" value="${skuVal}">
                </td>
                <td>
                    <input type="number" class="form-control form-control-sm variant-inventory" name="variants[${idx}][inventory]" value="${invVal}">
                </td>
                <td>
                    <button type="button" class="btn btn-sm btn-outline-danger" onclick="this.closest('tr').remove()"><i class="iconoir-trash"></i></button>
                </td>
            `;
            tbody.appendChild(tr);
        });
    }

    function updateHeader(idx, text) {
        const ths = document.querySelectorAll('#variantsTable thead th');
        if (ths[idx]) ths[idx].textContent = text;
    }

    window.addValue = function (idx) {
        const input = document.getElementById(`newValue-${idx}`);
        const val = input.value.trim();
        if (val && !productOptions[idx].values.includes(val)) {
            productOptions[idx].values.push(val);
            input.value = '';
            refreshOptionsList();
            renderTableRows();
        }
    }

    window.removeValue = function (optIdx, valIdx) {
        productOptions[optIdx].values.splice(valIdx, 1);
        refreshOptionsList();
        renderTableRows();
    }

    window.removeOption = function (idx) {
        productOptions.splice(idx, 1);
        populateVariants(); // Full re-render
    }

    // --- 7. SEO Preview ---
    const seoTitleInput = document.getElementById('seoTitle');
    const seoDescInput = document.getElementById('seoDescription');
    const productTitleInput = document.getElementById('productTitle');

    window.updateSeoPreview = function () {
        if (!seoTitleInput || !seoDescInput) return;
        document.querySelector('.seo-title-preview').textContent = seoTitleInput.value || productTitleInput.value || 'Product Title';
        document.querySelector('.seo-description-preview').textContent = seoDescInput.value || 'Product description...';
        document.getElementById('seoTitleCount').textContent = seoTitleInput.value.length;
    }

    if (seoTitleInput && seoDescInput) {
        seoTitleInput.addEventListener('input', updateSeoPreview);
        seoDescInput.addEventListener('input', updateSeoPreview);
        productTitleInput.addEventListener('input', updateSeoPreview);
    }

    // --- 8. Form Submit ---
    const editForm = document.getElementById('editProductForm');
    if (editForm) {
        editForm.addEventListener('submit', function (e) {
            e.preventDefault();
            document.getElementById('descriptionInput').value = quill.root.innerHTML;

            const formData = new FormData(this);
            uploadedImages.forEach((img, index) => {
                formData.append(`new_images[]`, img.file);
            });

            formData.append('options_json', JSON.stringify(productOptions));

            // Manually build Variants Array
            // Note: If no variants table rows (Simple Product), we don't append variants[] here.
            // The Simple Product fields (Price, SKU) are already in the form as named inputs 'price', 'sku', etc.
            // But PHP needs to know if we are clearing variants? 
            // If productOptions is empty, PHP logic (products.php) should handle clearing variants if we send empty variants array or implicit logic.
            // Let's assume PHP handles standard form inputs for simple product.

            const rows = document.querySelectorAll('#variantsTable tbody tr');
            rows.forEach((row, idx) => {
                const idInput = row.querySelector('input[name*="[id]"]');
                const priceInput = row.querySelector('.variant-price');
                const skuInput = row.querySelector('.variant-sku');
                const invInput = row.querySelector('.variant-inventory');

                if (priceInput) {
                    const id = idInput ? idInput.value : '';
                    const price = priceInput.value || '0.00';
                    const sku = skuInput.value || '';
                    const inv = invInput.value || '0';

                    formData.append(`variants[${idx}][id]`, id);
                    formData.append(`variants[${idx}][price]`, price);
                    formData.append(`variants[${idx}][sku]`, sku);
                    formData.append(`variants[${idx}][inventory]`, inv);

                    // Dynamic Options
                    let variantNameParts = [];
                    row.querySelectorAll('.variant-option-value').forEach(input => {
                        const optName = input.dataset.optionName;
                        const optVal = input.value;
                        if (optName && optVal) {
                            formData.append(`variants[${idx}][options][${optName}]`, optVal);
                            variantNameParts.push(optVal);
                        }
                    });
                    const constructedName = variantNameParts.join(' / ');
                    formData.append(`variants[${idx}][name]`, constructedName);
                }
            });

            const submitBtn = this.querySelector('button[type="submit"]');
            submitBtn.disabled = true;
            submitBtn.innerHTML = 'Updating...';

            fetch('api/products.php', { method: 'POST', body: formData })
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        alert('Product updated successfully!');
                        window.location.href = 'products.php';
                    } else {
                        alert('Error: ' + data.message);
                        submitBtn.disabled = false;
                        submitBtn.innerHTML = 'Update Product';
                    }
                })
                .catch(err => {
                    console.error(err);
                    alert('An error occurred.');
                    submitBtn.disabled = false;
                });
        });
    }

    // --- 9. Delete Product Logic (Modal) ---
    const deleteBtn = document.getElementById('deleteProductBtn');
    const deleteModalEl = document.getElementById('deleteConfirmationModal');
    const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');

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

        // 1. Open Modal on Click
        deleteBtn.addEventListener('click', function (e) {
            e.preventDefault();

            const title = document.getElementById('productTitle').value;
            const modalTitle = document.getElementById('deleteProductName');
            if (modalTitle) modalTitle.textContent = title || 'this product';

            deleteModal.show();
        });

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

            // Change button state
            confirmDeleteBtn.disabled = true;
            confirmDeleteBtn.innerHTML = '<i class="las la-spinner la-spin"></i> Deleting...';

            // Simple URL-encoded data
            const params = new URLSearchParams();
            params.append('action', 'delete');
            params.append('id', productId);

            console.log('Sending delete request via Modal (Edit Page):', params.toString());

            fetch('api/products.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: params
            })
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        // Redirect to list
                        window.location.href = 'products.php';
                    } else {
                        alert('Error: ' + data.message);
                        confirmDeleteBtn.disabled = false;
                        confirmDeleteBtn.innerHTML = 'Delete Product';
                    }
                })
                .catch(err => {
                    console.error(err);
                    alert('An error occurred during deletion.');
                    confirmDeleteBtn.disabled = false;
                    confirmDeleteBtn.innerHTML = 'Delete Product';
                });
        });
    }

    // Global Helper for existing image deletion
    window.deleteExistingImage = function (btn) {
        const wrapper = btn.closest('div');
        const path = wrapper.querySelector('input').value;

        const deletedInput = document.createElement('input');
        deletedInput.type = 'hidden';
        deletedInput.name = 'deleted_images[]';
        deletedInput.value = path;
        document.getElementById('editProductForm').appendChild(deletedInput);

        wrapper.remove();
    }

    // Load Data
    fetchProductData(productSlug);
});
