<?php 
include 'views/headin-dashboard.php';

// Check if product ID is provided
if (!isset($_GET['id']) || empty($_GET['id'])) {
    header('Location: products');
    exit();
}

$product_id = intval($_GET['id']);
?>
        <!-- Edit Product Page Content -->
        <main class="p-6">
            <!-- Header Section -->
            <div class="mb-6">
                <div class="flex items-center gap-3 mb-2">
                    <a href="products" class="text-gray-600 hover:text-verdigris transition-colors">
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"/>
                        </svg>
                    </a>
                    <h1 class="text-3xl font-bold text-licorice">Edit Product</h1>
                </div>
                <p class="text-gray-600">Update product information below</p>
            </div>

            <!-- Loading State -->
            <div id="loadingState" class="text-center py-20">
                <svg class="animate-spin w-12 h-12 mx-auto text-verdigris mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                <p class="text-gray-600">Loading product data...</p>
            </div>

            <!-- Error State -->
            <div id="errorState" class="hidden text-center py-20">
                <svg class="w-24 h-24 mx-auto text-red-300 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                </svg>
                <h3 class="text-xl font-semibold text-gray-600 mb-2">Product Not Found</h3>
                <p class="text-gray-500 mb-6">The product you're looking for doesn't exist</p>
                <a href="products" class="btn-primary px-6 py-3 rounded-xl text-white font-semibold inline-flex items-center gap-2 shadow-lg">
                    Back to Products
                </a>
            </div>

            <form id="editProductForm" class="space-y-6 hidden">
                <!-- Basic Information -->
                <div class="bg-white rounded-xl shadow-md p-6">
                    <h2 class="text-xl font-bold text-licorice mb-6 flex items-center gap-2">
                        <svg class="w-6 h-6 text-verdigris" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                        </svg>
                        Basic Information
                    </h2>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <!-- Product Name -->
                        <div class="md:col-span-2">
                            <label class="block text-sm font-semibold text-gray-700 mb-2">
                                Product Name <span class="text-red-500">*</span>
                            </label>
                            <input 
                                type="text" 
                                name="product_name" 
                                id="product_name"
                                placeholder="Enter product name" 
                                required
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-hunyadi/50 focus:border-hunyadi transition-all"
                            >
                        </div>

                        <!-- Brand -->
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Brand</label>
                            <input 
                                type="text" 
                                name="brand" 
                                id="brand"
                                placeholder="Enter brand name" 
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-hunyadi/50 focus:border-hunyadi transition-all"
                            >
                        </div>

                        <!-- SKU -->
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">
                                SKU <span class="text-red-500">*</span>
                            </label>
                            <input 
                                type="text" 
                                name="sku" 
                                id="sku"
                                placeholder="e.g., PROD-001" 
                                required
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-hunyadi/50 focus:border-hunyadi transition-all"
                            >
                        </div>

                        <!-- Category -->
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">
                                Category <span class="text-red-500">*</span>
                            </label>
                            <select 
                                name="category" 
                                id="category"
                                required
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-hunyadi/50 focus:border-hunyadi transition-all"
                            >
                                <option value="">Select category</option>
                                <option value="electronics">Electronics</option>
                                <option value="clothing">Clothing</option>
                                <option value="food">Food & Beverage</option>
                                <option value="home">Home & Kitchen</option>
                                <option value="sports">Sports & Outdoors</option>
                                <option value="toys">Toys & Games</option>
                                <option value="books">Books & Media</option>
                                <option value="beauty">Beauty & Personal Care</option>
                                <option value="other">Other</option>
                            </select>
                        </div>

                        <!-- Subcategory -->
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Subcategory</label>
                            <input 
                                type="text" 
                                name="subcategory" 
                                id="subcategory"
                                placeholder="Enter subcategory" 
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-hunyadi/50 focus:border-hunyadi transition-all"
                            >
                        </div>

                        <!-- Short Description -->
                        <div class="md:col-span-2">
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Short Description</label>
                            <input 
                                type="text" 
                                name="short_description" 
                                id="short_description"
                                placeholder="Brief description (max 160 characters)" 
                                maxlength="160"
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-hunyadi/50 focus:border-hunyadi transition-all"
                            >
                        </div>

                        <!-- Full Description -->
                        <div class="md:col-span-2">
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Full Description</label>
                            <textarea 
                                name="description" 
                                id="description"
                                rows="5" 
                                placeholder="Detailed product description"
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-hunyadi/50 focus:border-hunyadi transition-all resize-none"
                            ></textarea>
                        </div>
                    </div>
                </div>

                <!-- Pricing & Inventory -->
                <div class="bg-white rounded-xl shadow-md p-6">
                    <h2 class="text-xl font-bold text-licorice mb-6 flex items-center gap-2">
                        <svg class="w-6 h-6 text-verdigris" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                        </svg>
                        Pricing & Inventory
                    </h2>

                    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                        <!-- Regular Price -->
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">
                                Regular Price ($) <span class="text-red-500">*</span>
                            </label>
                            <input 
                                type="number" 
                                name="regular_price" 
                                id="regular_price"
                                placeholder="0.00" 
                                step="0.01"
                                min="0"
                                required
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-hunyadi/50 focus:border-hunyadi transition-all"
                            >
                        </div>

                        <!-- Sale Price -->
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Sale Price ($)</label>
                            <input 
                                type="number" 
                                name="sale_price" 
                                id="sale_price"
                                placeholder="0.00" 
                                step="0.01"
                                min="0"
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-hunyadi/50 focus:border-hunyadi transition-all"
                            >
                        </div>

                        <!-- Cost Price -->
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Cost Price ($)</label>
                            <input 
                                type="number" 
                                name="cost_price" 
                                id="cost_price"
                                placeholder="0.00" 
                                step="0.01"
                                min="0"
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-hunyadi/50 focus:border-hunyadi transition-all"
                            >
                        </div>

                        <!-- Stock Quantity -->
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">
                                Stock Quantity <span class="text-red-500">*</span>
                            </label>
                            <input 
                                type="number" 
                                name="stock_quantity" 
                                id="stock_quantity"
                                placeholder="0" 
                                min="0"
                                required
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-hunyadi/50 focus:border-hunyadi transition-all"
                            >
                        </div>

                        <!-- Low Stock Alert -->
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Low Stock Alert</label>
                            <input 
                                type="number" 
                                name="low_stock_alert" 
                                id="low_stock_alert"
                                placeholder="10" 
                                min="0"
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-hunyadi/50 focus:border-hunyadi transition-all"
                            >
                        </div>

                        <!-- Stock Status -->
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Stock Status</label>
                            <select 
                                name="stock_status"
                                id="stock_status"
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-hunyadi/50 focus:border-hunyadi transition-all"
                            >
                                <option value="in_stock">In Stock</option>
                                <option value="out_of_stock">Out of Stock</option>
                                <option value="on_backorder">On Backorder</option>
                            </select>
                        </div>
                    </div>
                </div>

                <!-- Product Details -->
                <div class="bg-white rounded-xl shadow-md p-6">
                    <h2 class="text-xl font-bold text-licorice mb-6 flex items-center gap-2">
                        <svg class="w-6 h-6 text-verdigris" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
                        </svg>
                        Product Details
                    </h2>

                    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                        <!-- Weight -->
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Weight (kg)</label>
                            <input type="number" name="weight" id="weight" placeholder="0.00" step="0.01" min="0"
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-hunyadi/50 focus:border-hunyadi transition-all">
                        </div>

                        <!-- Length -->
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Length (cm)</label>
                            <input type="number" name="length" id="length" placeholder="0.00" step="0.01" min="0"
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-hunyadi/50 focus:border-hunyadi transition-all">
                        </div>

                        <!-- Width -->
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Width (cm)</label>
                            <input type="number" name="width" id="width" placeholder="0.00" step="0.01" min="0"
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-hunyadi/50 focus:border-hunyadi transition-all">
                        </div>

                        <!-- Height -->
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Height (cm)</label>
                            <input type="number" name="height" id="height" placeholder="0.00" step="0.01" min="0"
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-hunyadi/50 focus:border-hunyadi transition-all">
                        </div>

                        <!-- Material -->
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Material</label>
                            <input type="text" name="material" id="material" placeholder="e.g., Cotton, Plastic"
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-hunyadi/50 focus:border-hunyadi transition-all">
                        </div>

                        <!-- Color -->
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Color</label>
                            <input type="text" name="color" id="color" placeholder="e.g., Red, Blue"
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-hunyadi/50 focus:border-hunyadi transition-all">
                        </div>

                        <!-- Size -->
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Size</label>
                            <input type="text" name="size" id="size" placeholder="e.g., S, M, L, XL"
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-hunyadi/50 focus:border-hunyadi transition-all">
                        </div>

                        <!-- Warranty -->
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Warranty Period</label>
                            <input type="text" name="warranty" id="warranty" placeholder="e.g., 1 year, 6 months"
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-hunyadi/50 focus:border-hunyadi transition-all">
                        </div>

                        <!-- Country of Origin -->
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Country of Origin</label>
                            <input type="text" name="country_origin" id="country_origin" placeholder="e.g., USA, China"
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-hunyadi/50 focus:border-hunyadi transition-all">
                        </div>
                    </div>
                </div>

                <!-- SEO & Tags -->
                <div class="bg-white rounded-xl shadow-md p-6">
                    <h2 class="text-xl font-bold text-licorice mb-6 flex items-center gap-2">
                        <svg class="w-6 h-6 text-verdigris" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"/>
                        </svg>
                        SEO & Tags
                    </h2>

                    <div class="grid grid-cols-1 gap-6">
                        <!-- Meta Title -->
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Meta Title</label>
                            <input type="text" name="meta_title" id="meta_title" placeholder="SEO title for search engines" maxlength="60"
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-hunyadi/50 focus:border-hunyadi transition-all">
                        </div>

                        <!-- Meta Description -->
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Meta Description</label>
                            <textarea name="meta_description" id="meta_description" rows="3" placeholder="SEO description for search engines" maxlength="160"
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-hunyadi/50 focus:border-hunyadi transition-all resize-none"></textarea>
                        </div>

                        <!-- Tags -->
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Tags</label>
                            <input type="text" name="tags" id="tags" placeholder="Separate tags with commas (e.g., electronics, smartphone, android)"
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-hunyadi/50 focus:border-hunyadi transition-all">
                        </div>
                    </div>
                </div>

                <!-- Product Status -->
                <div class="bg-white rounded-xl shadow-md p-6">
                    <h2 class="text-xl font-bold text-licorice mb-6 flex items-center gap-2">
                        <svg class="w-6 h-6 text-verdigris" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
                        </svg>
                        Product Status
                    </h2>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <!-- Status -->
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Status</label>
                            <select name="status" id="status"
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-hunyadi/50 focus:border-hunyadi transition-all">
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                                <option value="draft">Draft</option>
                            </select>
                        </div>

                        <!-- Featured Product -->
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Featured Product</label>
                            <div class="flex items-center gap-4 mt-3">
                                <label class="flex items-center cursor-pointer">
                                    <input type="radio" name="featured" id="featured_yes" value="yes" class="mr-2 text-verdigris focus:ring-verdigris">
                                    <span class="text-gray-700">Yes</span>
                                </label>
                                <label class="flex items-center cursor-pointer">
                                    <input type="radio" name="featured" id="featured_no" value="no" class="mr-2 text-verdigris focus:ring-verdigris">
                                    <span class="text-gray-700">No</span>
                                </label>
                            </div>
                        </div>

                        <!-- Show on Homepage -->
                        <div>
                            <label class="flex items-center cursor-pointer">
                                <input type="checkbox" name="show_homepage" id="show_homepage" class="w-5 h-5 text-verdigris border-gray-300 rounded focus:ring-verdigris">
                                <span class="ml-3 text-gray-700 font-semibold">Show on Homepage</span>
                            </label>
                        </div>

                        <!-- Allow Reviews -->
                        <div>
                            <label class="flex items-center cursor-pointer">
                                <input type="checkbox" name="allow_reviews" id="allow_reviews" class="w-5 h-5 text-verdigris border-gray-300 rounded focus:ring-verdigris">
                                <span class="ml-3 text-gray-700 font-semibold">Allow Customer Reviews</span>
                            </label>
                        </div>
                    </div>
                </div>

                <!-- Form Actions -->
                <div class="flex items-center justify-between">
                    <button type="button" id="deleteBtn" class="px-6 py-3 bg-red-500 text-white rounded-xl font-semibold hover:bg-red-600 transition-all flex items-center gap-2">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
                        </svg>
                        Delete Product
                    </button>
                    
                    <div class="flex items-center gap-4">
                        <a href="products" class="px-6 py-3 border-2 border-gray-300 text-gray-700 rounded-xl font-semibold hover:bg-gray-50 transition-all">
                            Cancel
                        </a>
                        <button type="submit" class="btn-primary px-8 py-3 rounded-xl text-white font-semibold shadow-lg hover-lift">
                            Update Product
                        </button>
                    </div>
                </div>
            </form>
        </main>

    <script>
        const productId = <?php echo $product_id; ?>;
        
        // Mobile offcanvas menu
        const menuToggle = document.getElementById('menuToggle');
        const closeSidebar = document.getElementById('closeSidebar');
        const sidebar = document.getElementById('sidebar');
        const sidebarBackdrop = document.getElementById('sidebarBackdrop');

        function openSidebar() {
            sidebar.classList.add('active');
            sidebarBackdrop.classList.add('active');
            document.body.style.overflow = 'hidden';
        }

        function closeSidebarFunc() {
            sidebar.classList.remove('active');
            sidebarBackdrop.classList.remove('active');
            document.body.style.overflow = '';
        }

        menuToggle.addEventListener('click', function() {
            sidebar.classList.contains('active') ? closeSidebarFunc() : openSidebar();
        });

        closeSidebar.addEventListener('click', closeSidebarFunc);
        sidebarBackdrop.addEventListener('click', closeSidebarFunc);

        window.addEventListener('resize', function() {
            if (window.innerWidth >= 1024) closeSidebarFunc();
        });

        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && sidebar.classList.contains('active')) closeSidebarFunc();
        });

        // Load Categories
        async function loadCategories() {
            try {
                const response = await fetch('api/categories.php?status=active', {
                    method: 'GET'
                });
                
                const data = await response.json();
                console.log('Categories Response:', data);
                
                if (data.success === true) {
                    const categorySelect = document.getElementById('category');
                    categorySelect.innerHTML = '<option value="">Select category</option>';
                    
                    data.data.categories.forEach(category => {
                        const option = document.createElement('option');
                        option.value = category.slug;
                        option.textContent = `${category.icon || ''} ${category.name}`;
                        categorySelect.appendChild(option);
                    });
                }
            } catch (error) {
                console.error('Error loading categories:', error);
            }
        }

        // Load Product Data
        async function loadProductData() {
            // Load categories first
            await loadCategories();
            
            fetch(`api/products.php?id=${productId}`, {
                method: 'GET'
            })
            .then(response => response.json())
            .then(data => {
                console.log('Product Response:', data);
                if (data.success === true) {
                    populateForm(data.data);
                    document.getElementById('loadingState').classList.add('hidden');
                    document.getElementById('editProductForm').classList.remove('hidden');
                } else {
                    showError();
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showError();
            });
        }

        // Populate form with product data
        function populateForm(product) {
            // Basic Information
            document.getElementById('product_name').value = product.product_name || '';
            document.getElementById('brand').value = product.brand || '';
            document.getElementById('sku').value = product.sku || '';
            document.getElementById('category').value = product.category || '';
            document.getElementById('subcategory').value = product.subcategory || '';
            document.getElementById('short_description').value = product.short_description || '';
            document.getElementById('description').value = product.description || '';

            // Pricing & Inventory
            document.getElementById('regular_price').value = product.regular_price || '';
            document.getElementById('sale_price').value = product.sale_price || '';
            document.getElementById('cost_price').value = product.cost_price || '';
            document.getElementById('stock_quantity').value = product.stock_quantity || '';
            document.getElementById('low_stock_alert').value = product.low_stock_alert || '';
            document.getElementById('stock_status').value = product.stock_status || 'in_stock';

            // Product Details
            document.getElementById('weight').value = product.weight || '';
            document.getElementById('length').value = product.length || '';
            document.getElementById('width').value = product.width || '';
            document.getElementById('height').value = product.height || '';
            document.getElementById('material').value = product.material || '';
            document.getElementById('color').value = product.color || '';
            document.getElementById('size').value = product.size || '';
            document.getElementById('warranty').value = product.warranty || '';
            document.getElementById('country_origin').value = product.country_origin || '';

            // SEO & Tags
            document.getElementById('meta_title').value = product.meta_title || '';
            document.getElementById('meta_description').value = product.meta_description || '';
            document.getElementById('tags').value = product.tags || '';

            // Status
            document.getElementById('status').value = product.status || 'active';
            
            if (product.featured === 'yes') {
                document.getElementById('featured_yes').checked = true;
            } else {
                document.getElementById('featured_no').checked = true;
            }
            
            document.getElementById('show_homepage').checked = product.show_homepage == 1;
            document.getElementById('allow_reviews').checked = product.allow_reviews == 1;
        }

        // Show error state
        function showError() {
            document.getElementById('loadingState').classList.add('hidden');
            document.getElementById('errorState').classList.remove('hidden');
        }

        // Form Submission - Update Product
        document.getElementById('editProductForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const productData = {};
            
            for (let [key, value] of formData.entries()) {
                productData[key] = value || null;
            }
            
            productData.show_homepage = document.getElementById('show_homepage').checked ? 1 : 0;
            productData.allow_reviews = document.getElementById('allow_reviews').checked ? 1 : 0;
            
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<svg class="animate-spin w-5 h-5 mr-2 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>Updating...';
            
            fetch(`api/products.php?id=${productId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(productData)
            })
            .then(response => response.json())
            .then(data => {
                console.log('Update Response:', data);
                if (data.success === true) {
                    showNotification('success', 'Product updated successfully!');
                    setTimeout(() => {
                        window.location.href = 'products';
                    }, 1500);
                } else {
                    showNotification('error', data.message || 'Failed to update product');
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = originalText;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showNotification('error', 'Network error. Please try again.');
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalText;
            });
        });

        // Delete Product
        document.getElementById('deleteBtn').addEventListener('click', function() {
            const productName = document.getElementById('product_name').value;
            
            if (confirm(`Are you sure you want to delete "${productName}"? This action cannot be undone.`)) {
                const btn = this;
                btn.disabled = true;
                btn.innerHTML = '<svg class="animate-spin w-5 h-5 mr-2 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>Deleting...';
                
                fetch(`api/products.php?id=${productId}`, {
                    method: 'DELETE'
                })
                .then(response => response.json())
                .then(data => {
                    console.log('Delete Response:', data);
                    if (data.success === true) {
                        showNotification('success', 'Product deleted successfully!');
                        setTimeout(() => {
                            window.location.href = 'products';
                        }, 1500);
                    } else {
                        showNotification('error', data.message || 'Failed to delete product');
                        btn.disabled = false;
                        btn.innerHTML = '<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>Delete Product';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showNotification('error', 'Network error. Please try again.');
                    btn.disabled = false;
                    btn.innerHTML = '<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>Delete Product';
                });
            }
        });

        // Notification function
        function showNotification(type, message) {
            const notification = document.createElement('div');
            notification.className = `notification ${type} show`;
            notification.innerHTML = `
                <div class="flex items-center">
                    <svg class="w-6 h-6 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        ${type === 'success' 
                            ? '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>'
                            : '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>'
                        }
                    </svg>
                    <span>${message}</span>
                </div>
            `;
            document.body.appendChild(notification);
            
            setTimeout(() => {
                notification.remove();
            }, 5000);
        }

        // Load product data on page load
        loadProductData();
    </script>
<?php require_once 'views/fotter-dashboard.php'; ?>