
/**
 * Add Product Page Script
 * -----------------------
 * Handles Quill editor, Image Upload (Drag & Drop), and Dynamic Variants Generation (Cartesian).
 */

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

    // --- 0. Interactive Category Selection (Shared 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 response = await fetch('api/collections.php?limit=100&status=active');
            const data = await response.json();
            if (data.success) {
                allCollections = data.data;
            }
        } catch (error) {
            console.error('Error loading collections:', error);
        }
    }

    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);
    });

    document.addEventListener('click', function (e) {
        if (!categorySearch.contains(e.target) && !searchResults.contains(e.target)) {
            searchResults.style.display = 'none';
        }
    });

    function renderSearchResults(collections) {
        if (collections.length === 0) { searchResults.style.display = 'none'; return; }
        searchResults.innerHTML = '';
        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';
    }

    function addCollection(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();
    }


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


    // --- 2. Image Upload Logic (Drag & Drop) ---
    let uploadedImages = [];
    let imageIdCounter = 0;
    const dropZone = document.getElementById('dropZone');
    const mediaFileInput = document.getElementById('mediaFileInput');
    const imageGrid = document.getElementById('imageGrid');

    document.getElementById('addMediaBtn').addEventListener('click', (e) => {
        e.preventDefault();
        mediaFileInput.click();
    });

    dropZone.addEventListener('click', (e) => {
        if (e.target === dropZone || e.target.closest('.drop-zone-content')) {
            mediaFileInput.click();
        }
    });

    mediaFileInput.addEventListener('change', function () {
        if (this.files.length) handleFiles(this.files);
    });

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

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

    ['dragenter', 'dragover'].forEach(eventName => {
        dropZone.addEventListener(eventName, () => dropZone.classList.add('drag-over'), false);
    });

    ['dragleave', 'drop'].forEach(eventName => {
        dropZone.addEventListener(eventName, () => dropZone.classList.remove('drag-over'), false);
    });

    dropZone.addEventListener('drop', (e) => {
        const dt = e.dataTransfer;
        handleFiles(dt.files);
    });

    function handleFiles(files) {
        [...files].forEach(file => {
            if (file.type.startsWith('image/')) {
                const reader = new FileReader();
                reader.onload = (e) => {
                    uploadedImages.push({
                        id: imageIdCounter++,
                        file: file,
                        src: e.target.result,
                        featured: uploadedImages.length === 0
                    });
                    renderImageGrid();
                };
                reader.readAsDataURL(file);
            }
        });
    }

    function renderImageGrid() {
        if (uploadedImages.length === 0) {
            imageGrid.style.display = 'none';
            dropZone.style.display = 'block';
            return;
        }
        imageGrid.style.display = 'grid';
        dropZone.style.display = 'block';

        imageGrid.innerHTML = '';
        uploadedImages.forEach((img) => {
            const card = document.createElement('div');
            card.className = `image-card ${img.featured ? 'featured' : ''}`;
            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" onclick="setFeatured(${img.id})" title="Set Featured"><i class="iconoir-star"></i></button>
                        <button type="button" class="image-card-btn delete" onclick="removeImage(${img.id})" title="Remove"><i class="iconoir-trash"></i></button>
                    </div>
                </div>
            `;
            imageGrid.appendChild(card);
        });
    }

    window.removeImage = function (id) {
        uploadedImages = uploadedImages.filter(img => img.id !== id);
        if (uploadedImages.length > 0 && !uploadedImages.some(img => img.featured)) {
            uploadedImages[0].featured = true;
        }
        renderImageGrid();
    }

    window.setFeatured = function (id) {
        uploadedImages.forEach(img => img.featured = (img.id === id));
        renderImageGrid();
    }


    // --- 3. Variants Logic (Cartesian Auto-Generation) ---
    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: Restore table data state before re-render
    function getExistingRowData() {
        const rows = document.querySelectorAll('#variantsTable tbody tr');
        const dataMap = {}; // Key: "Red/S", Value: { price: ..., sku: ..., inv: ... }
        rows.forEach(row => {
            // Reconstruct Key
            const keyParts = [];
            row.querySelectorAll('.variant-option-value').forEach(input => {
                keyParts.push(input.value);
                // Note: We use the value in the input, which might be what we generated.
            });
            const key = keyParts.join('/');
            if (key) {
                dataMap[key] = {
                    price: row.querySelector('.variant-price').value,
                    sku: row.querySelector('.variant-sku').value,
                    inventory: row.querySelector('.variant-inventory').value
                };
            }
        });
        return dataMap;
    }

    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 (Options + Table)
        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(); // Re-render table 
        });

        refreshOptionsList();
        renderTableRows();
    }

    // Render Options List Inputs
    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);

            // Bind Events
            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);
                }
            });
        });
    }

    // Auto-Generate Table Rows (Cartesian)
    function renderTableRows() {
        // Collect existing data to preserve improvements (Price/SKU)
        const oldData = getExistingRowData();

        const tbody = document.querySelector('#variantsTable tbody');
        if (!tbody) return; // if table hidden/not rendered yet

        tbody.innerHTML = '';

        // If no options, stop (table should be hidden anyway)
        if (productOptions.length === 0) return;

        // Filter options that have at least one value? 
        // Or render generic rows if no values?
        // Behavior: If Option defined but no values, we cannot generate combinations.
        // We only generate combinations of valid values.

        const validOptions = productOptions.filter(o => o.values.length > 0);

        if (validOptions.length === 0) {
            // If no valid options (e.g. option added but no values), hide table card or show empty state?
            // Hide card to match "no variants" state
            const tableCard = document.getElementById('variantsTableCard');
            if (tableCard) tableCard.style.display = 'none';
            return;
        }

        // Get arrays of values
        const valueArrays = validOptions.map(o => o.values);
        // Generate combinations
        const combinations = cartesian(valueArrays);

        combinations.forEach((combo, idx) => {
            // Combo is array ['Red', 'S']
            const key = combo.join('/');

            // Try to recover data
            const existing = oldData[key] || {};
            const priceVal = existing.price || document.querySelector('input[name="price"]')?.value || '0.00'; // Fallback to simple price if set
            const skuVal = existing.sku || `SKU-${Date.now().toString().slice(-6)}-${idx}`;
            const invVal = existing.inventory || document.querySelector('input[name="inventory"]')?.value || 0;

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

            // Render Dynamic Cells (Read-Only or Hidden Input + Display)
            // Users usually don't rename the specific cell value here, they rename the option value.
            // So we display text and hidden input.
            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}]" 
                               value="${val}">
                        ${val}
                    </td>
                `;
            });

            tr.innerHTML = `
                ${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);
        });

        // Ensure table card is visible if we have rows
        const tableCard = document.getElementById('variantsTableCard');
        if (tableCard) {
            tableCard.style.display = 'block';
        }
    }


    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(); // Re-generate
        }
    }

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

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


    // Initialize Variants UI
    populateVariants();


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

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

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


    // --- 5. Form Submission ---
    const form = document.getElementById('addProductForm');
    form.addEventListener('submit', function (e) {
        e.preventDefault();

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

        const formData = new FormData(this);

        // Append Images
        uploadedImages.forEach((img, index) => {
            formData.append(`images[${index}]`, img.file);
            if (img.featured) {
                formData.append('featured_image_index', index);
            }
        });

        // Append Options JSON (for consistency)
        formData.append('options_json', JSON.stringify(productOptions));

        // Generate Variants Names for PHP
        // PHP expects `variants[idx][name]`.
        // If Simple Product (no variants table), this logic skips and PHP uses main fields? 
        // Actually PHP `products.php` handles `variants` array. If empty array, it uses main fields.

        const rows = document.querySelectorAll('#variantsTable tbody tr');
        rows.forEach((row, idx) => {
            let variantNameParts = [];
            row.querySelectorAll('.variant-option-value').forEach(input => {
                if (input.value) variantNameParts.push(input.value);
            });
            const constructedName = variantNameParts.join(' / ');
            formData.append(`variants[${idx}][name]`, constructedName);

            // The other fields (price, sku, inventory, options) are already inputs with correct names in the TR
        });

        // Send Request
        const submitBtn = this.querySelector('button[type="submit"]');
        const originalText = submitBtn.innerHTML;
        submitBtn.innerHTML = 'Saving...';
        submitBtn.disabled = true;

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

});
