<div class="section">
    <h2 style="padding-bottom: 15px"><strong>Edit Product: <%= edit_product.product_name %></strong></h2>

    <form method="POST" action="/admin/edit-product/<%= edit_product.id %>" enctype="multipart/form-data"
        id="editProductForm">
        <input type="hidden" name="product_options_json" id="productOptionsJson">
        <div class="row">
            <div class="col-md-8">
                <div class="mb-3">
                    <label class="form-label">Product Name *</label>
                    <input type="text" class="form-control" name="product_name" value="<%= edit_product.product_name %>"
                        required>
                </div>

                <div class="mb-3">
                    <label class="form-label">Category *</label>
                    <input type="text" class="form-control" name="category" value="<%= edit_product.category %>"
                        required>
                </div>

                <div class="mb-3">
                    <label class="form-label">Product Attributes</label>
                    <div id="productOptions">
                        <% if (edit_options && Object.keys(edit_options).length> 0) { %>
                            <% Object.entries(edit_options).forEach(function([name, value]) { %>
                                <div class="product-option d-flex align-items-center mb-2">
                                    <input type="text" class="form-control me-2 attr-name" name="user_attr_name[]"
                                        value="<%= name %>" placeholder="Attribute Name">
                                    <input type="text" class="form-control me-2 attr-value" name="user_attr_value[]"
                                        value="<%= value %>" placeholder="Attribute Value">
                                    <button type="button" class="remove-option"
                                        onclick="this.parentElement.remove()">Remove</button>
                                </div>
                                <% }); %>
                                    <% } else { %>
                                        <div class="product-option d-flex align-items-center mb-2">
                                            <input type="text" class="form-control me-2 attr-name"
                                                name="user_attr_name[]" placeholder="Attribute Name">
                                            <input type="text" class="form-control me-2 attr-value"
                                                name="user_attr_value[]" placeholder="Attribute Value">
                                        </div>
                                        <% } %>
                    </div>
                    <button type="button" class="add-option mt-2" onclick="addOption()">
                        <i class="fas fa-plus me-1"></i> Add Another Option
                    </button>
                </div>

                <div class="mb-3">
                    <label class="form-label">Product Link (Optional)</label>
                    <input type="text" class="form-control" name="product_rate"
                        value="<%= edit_product.product_rate || '' %>" placeholder="Enter rate or link">
                </div>

                <div class="mb-3">
                    <label class="form-label">Stock Status *</label>
                    <select class="form-select" name="stock_status" required>
                        <option value="in_stock" <%=edit_product.stock_status==='in_stock' ? 'selected' : '' %>>In Stock
                        </option>
                        <option value="out_of_stock" <%=edit_product.stock_status==='out_of_stock' ? 'selected' : '' %>
                            >Out of Stock</option>
                    </select>
                </div>

                <div class="mb-3">
                    <label class="form-label">Product Image</label>
                    <% if (edit_product.image_filename) { %>
                        <div class="mb-2">
                            <img src="/uploads/products/<%= edit_product.image_filename %>" class="img-fluid"
                                style="max-height: 200px;">
                            <p class="text-muted small">Current image: <%= edit_product.image_filename %>
                            </p>
                        </div>
                        <% } %>
                            <input type="file" class="form-control" name="product_image" accept="image/*">
                            <small class="text-muted">Upload a new image to replace the current one</small>
                </div>

                <div class="d-flex gap-2">
                    <button type="submit" class="btn btn-warning">Update Product</button>
                    <a href="/admin/manage-products" class="btn btn-secondary">Cancel</a>
                </div>
            </div>
        </div>
    </form>
</div>

<script>
    function addOption() {
        const container = document.getElementById('productOptions');
        const div = document.createElement('div');
        div.className = 'product-option d-flex align-items-center mb-2';
        div.innerHTML = `
        <input type="text" class="form-control me-2 attr-name" name="user_attr_name[]" placeholder="Attribute Name">
        <input type="text" class="form-control me-2 attr-value" name="user_attr_value[]" placeholder="Attribute Value">
        <button type="button" class="remove-option" onclick="this.parentElement.remove()">Remove</button>
    `;
        container.appendChild(div);
    }

    // INTERCEPT SUBMISSION - The ONLY way data is sent is via the JSON field
    document.getElementById('editProductForm').addEventListener('submit', function (e) {
        const options = {};
        const names = this.querySelectorAll('.attr-name');
        const values = this.querySelectorAll('.attr-value');

        names.forEach((nameInput, i) => {
            const name = nameInput.value.trim();
            const value = values[i].value.trim();
            // EXTREMELY IMPORTANT: Do not include keys that look like JSON themselves
            if (name && value && !name.includes('{') && !name.includes(':')) {
                options[name] = value;
            }
        });

        // Set the hidden field
        document.getElementById('productOptionsJson').value = JSON.stringify(options);
        
        // MUTE the original fields so they are NOT sent in the body
        names.forEach(input => input.name = "");
        values.forEach(input => input.name = "");
    });
</script>