<div class="section">
    <h2 style="padding-bottom: 15px"><strong>Manage Products</strong></h2>
    <% all_categories.forEach(function(category) { %>
        <div class="product-category mb-3">
            <div class="category-header d-flex justify-content-between align-items-center" data-bs-toggle="collapse"
                data-bs-target="#<%= category.replace(/[^a-zA-Z0-9]/g, '') %>" aria-expanded="false">
                <h4 class="mb-0">
                    <%= category %>
                </h4>
                <i class="fas fa-chevron-down category-arrow"></i>
            </div>
            <div class="collapse category-content" id="<%= category.replace(/[^a-zA-Z0-9]/g, '') %>">
                <div class="category-body mt-3">
                    <div class="d-flex gap-2 mb-3">
                        <button class="btn btn-success btn-sm" onclick="openAddProductModal('<%= category %>')">
                            <i class="fas fa-plus me-1"></i> Add Product
                        </button>
                    </div>
                    <% const categoryProducts=products_by_category[category] || []; %>
                        <% if (categoryProducts.length> 0) { %>
                            <div class="row g-3">
                                <% categoryProducts.forEach(function(product) { %>
                                    <div class="col-12 col-md-6 col-lg-4">
                                        <div class="card h-100">
                                            <div class="card-body d-flex flex-column">
                                                <h5 class="card-title">
                                                    <%= product.name %>
                                                </h5>
                                                <% if (product.options && Object.keys(product.options).length> 0) { %>
                                                    <% Object.entries(product.options).forEach(function([optName,
                                                        optValue]) { %>
                                                        <div class="mb-2"><small class="text-muted">
                                                                <%= optName %>: <%= optValue %>
                                                            </small></div>
                                                        <% }); %>
                                                            <% } %>
                                                                <% if (product.rate) { %>
                                                                    <p class="mb-1"><strong>Link:</strong> <a
                                                                            href="<%= product.rate %>"
                                                                            class="text-accent">
                                                                            <%= product.rate %>
                                                                        </a></p>
                                                                    <% } %>
                                                                        <p class="mb-2">
                                                                            <strong>Stock:</strong>
                                                                            <% if (product.stock==='in_stock' ) { %>
                                                                                <span class="badge bg-success">In
                                                                                    Stock</span>
                                                                                <% } else { %>
                                                                                    <span class="badge bg-danger">Out of
                                                                                        Stock</span>
                                                                                    <% } %>
                                                                        </p>
                                                                        <% if (product.image) { %>
                                                                            <img src="/uploads/products/<%= product.image %>"
                                                                                class="img-fluid mb-2"
                                                                                style="max-height:150px; object-fit:contain; border-radius: var(--radius-md);">
                                                                            <% } else { %>
                                                                                <div class="mb-2 d-flex align-items-center justify-content-center text-muted"
                                                                                    style="height:150px; background: var(--surface-elevated); border: 1px dashed var(--surface-border); border-radius: var(--radius-md);">
                                                                                    <i class="fas fa-image me-2"></i> No
                                                                                    Image
                                                                                </div>
                                                                                <% } %>
                                                                                    <div class="mt-auto d-flex gap-2">
                                                                                        <a href="/admin/edit-product/<%= product.id %>"
                                                                                            class="btn btn-warning btn-sm flex-fill">
                                                                                            <i
                                                                                                class="fas fa-edit me-1"></i>
                                                                                            Edit
                                                                                        </a>
                                                                                        <form method="POST"
                                                                                            action="/admin/delete-product/<%= product.id %>"
                                                                                            onsubmit="return confirm('Delete this product?');"
                                                                                            style="display:inline-block;"
                                                                                            class="flex-fill">
                                                                                            <button type="submit"
                                                                                                class="btn btn-danger btn-sm w-100">
                                                                                                <i
                                                                                                    class="fas fa-trash me-1"></i>
                                                                                                Delete
                                                                                            </button>
                                                                                        </form>
                                                                                    </div>
                                            </div>
                                        </div>
                                    </div>
                                    <% }); %>
                            </div>
                            <% } else { %>
                                <p class="text-muted"><i class="fas fa-info-circle me-1"></i> No products in this
                                    category yet.</p>
                                <% } %>
                </div>
            </div>
        </div>
        <% }); %>
</div>

<!-- Add Product Modal -->
<div class="modal fade" id="addProductModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addProductModalLabel">Add New Product</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" action="/admin/add-product" enctype="multipart/form-data" id="addProductForm">
                <div class="modal-body">
                    <input type="hidden" name="category" id="productCategoryInput">
                    <input type="hidden" name="product_options_json" id="addProductOptionsJson">
                    <div class="mb-3">
                        <label class="form-label">Product Name *</label>
                        <input type="text" class="form-control" name="product_name" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Product Attributes</label>
                        <small class="text-muted d-block mb-2">(e.g: sizes, colors, specifications)</small>
                        <div id="productOptions">
                            <div class="product-option d-flex align-items-center mb-2">
                                <input type="text" class="form-control me-2 add-attr-name" name="user_attr_name[]"
                                    placeholder="Attribute Name">
                                <input type="text" class="form-control me-2 add-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" 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="">Select Stock Status</option>
                            <option value="in_stock">In Stock</option>
                            <option value="out_of_stock">Out of Stock</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Product Image (Optional)</label>
                        <input type="file" class="form-control" name="product_image" accept="image/*">
                        <small class="text-muted">Supported: JPG, PNG, GIF (Max: 5MB)</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-light" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-success">
                        <i class="fas fa-save me-1"></i> Save Product
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    function openAddProductModal(category) {
        document.getElementById('productCategoryInput').value = category;
        document.getElementById('addProductModalLabel').textContent = 'Add New Product (' + category + ')';
        new bootstrap.Modal(document.getElementById('addProductModal')).show();
    }

    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 add-attr-name" name="user_attr_name[]" placeholder="Attribute Name">
        <input type="text" class="form-control me-2 add-attr-value" name="user_attr_value[]" placeholder="Attribute Value">
        <button type="button" class="remove-option" onclick="this.parentElement.remove()"><i class="fas fa-times"></i></button>
    `;
        container.appendChild(div);
    }

    // INTERCEPT ADD SUBMISSION - The ONLY way data is sent is via the JSON field
    document.getElementById('addProductForm').addEventListener('submit', function (e) {
        const options = {};
        const names = this.querySelectorAll('.add-attr-name');
        const values = this.querySelectorAll('.add-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;
            }
        });

        document.getElementById('addProductOptionsJson').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>