<?php 
include 'views/headin-dashboard.php';
?>
        <!-- Categories Management Page -->
        <main class="p-6">
            <!-- Header Section -->
            <div class="mb-6 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                <div>
                    <h1 class="text-3xl font-bold text-licorice mb-2">Categories Management 🏷️</h1>
                    <p class="text-gray-600">Manage your product categories</p>
                </div>
                <button id="addCategoryBtn" class="btn-primary px-6 py-3 rounded-xl text-white font-semibold flex items-center justify-center gap-2 shadow-lg hover-lift">
                    <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="M12 6v6m0 0v6m0-6h6m-6 0H6"/>
                    </svg>
                    Add New Category
                </button>
            </div>

            <!-- Categories Grid -->
            <div id="categoriesGrid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                <!-- Loading State -->
                <div class="col-span-full 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 categories...</p>
                </div>
            </div>
        </main>

        <!-- Add/Edit Category Modal -->
        <div id="categoryModal" class="fixed inset-0 bg-black/50 z-50 hidden flex items-center justify-center p-4">
            <div class="bg-white rounded-2xl shadow-2xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
                <div class="p-6 border-b border-gray-200 flex items-center justify-between">
                    <h2 id="modalTitle" class="text-2xl font-bold text-licorice">Add New Category</h2>
                    <button id="closeModal" class="text-gray-400 hover:text-gray-600 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="M6 18L18 6M6 6l12 12"/>
                        </svg>
                    </button>
                </div>
                
                <form id="categoryForm" class="p-6 space-y-6">
                    <input type="hidden" id="categoryId" name="id">
                    
                    <!-- Category Name -->
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">
                            Category Name <span class="text-red-500">*</span>
                        </label>
                        <input type="text" id="categoryName" name="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"
                            placeholder="Enter category name">
                    </div>

                    <!-- Description -->
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">Description</label>
                        <textarea id="categoryDescription" name="description" rows="3"
                            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"
                            placeholder="Brief description"></textarea>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <!-- Icon -->
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Icon (Emoji)</label>
                            <input type="text" id="categoryIcon" name="icon" maxlength="2"
                                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"
                                placeholder="📦">
                        </div>

                        <!-- Color -->
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Color</label>
                            <input type="color" id="categoryColor" name="color" value="#3B82F6"
                                class="w-full h-12 px-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-hunyadi/50 focus:border-hunyadi transition-all">
                        </div>

                        <!-- Sort Order -->
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Sort Order</label>
                            <input type="number" id="categorySortOrder" name="sort_order" value="0" 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>

                        <!-- Status -->
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2">Status</label>
                            <select id="categoryStatus" name="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>
                            </select>
                        </div>
                    </div>

                    <!-- Form Actions -->
                    <div class="flex items-center justify-end gap-4 pt-4 border-t border-gray-200">
                        <button type="button" id="cancelBtn" class="px-6 py-3 border-2 border-gray-300 text-gray-700 rounded-xl font-semibold hover:bg-gray-50 transition-all">
                            Cancel
                        </button>
                        <button type="submit" class="btn-primary px-8 py-3 rounded-xl text-white font-semibold shadow-lg hover-lift">
                            Save Category
                        </button>
                    </div>
                </form>
            </div>
        </div>

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

        // Modal Management
        const modal = document.getElementById('categoryModal');
        const addCategoryBtn = document.getElementById('addCategoryBtn');
        const closeModal = document.getElementById('closeModal');
        const cancelBtn = document.getElementById('cancelBtn');
        const categoryForm = document.getElementById('categoryForm');
        let editMode = false;

        function openModal(category = null) {
            editMode = !!category;
            document.getElementById('modalTitle').textContent = editMode ? 'Edit Category' : 'Add New Category';
            
            if (editMode) {
                document.getElementById('categoryId').value = category.id;
                document.getElementById('categoryName').value = category.name;
                document.getElementById('categoryDescription').value = category.description || '';
                document.getElementById('categoryIcon').value = category.icon || '';
                document.getElementById('categoryColor').value = category.color || '#3B82F6';
                document.getElementById('categorySortOrder').value = category.sort_order || 0;
                document.getElementById('categoryStatus').value = category.status;
            } else {
                categoryForm.reset();
                document.getElementById('categoryId').value = '';
            }
            
            modal.classList.remove('hidden');
            document.body.style.overflow = 'hidden';
        }

        function closeModalFunc() {
            modal.classList.add('hidden');
            document.body.style.overflow = '';
            categoryForm.reset();
        }

        addCategoryBtn.addEventListener('click', () => openModal());
        closeModal.addEventListener('click', closeModalFunc);
        cancelBtn.addEventListener('click', closeModalFunc);

        // Close modal on backdrop click
        modal.addEventListener('click', function(e) {
            if (e.target === modal) closeModalFunc();
        });

        // Load Categories
        function loadCategories() {
            fetch('api/categories.php?parent_id=null', {
                method: 'GET'
            })
            .then(response => response.json())
            .then(data => {
                console.log('API Response:', data);
                if (data.success === true && data.data.categories.length > 0) {
                    displayCategories(data.data.categories);
                } else {
                    showEmptyState();
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showErrorState();
            });
        }

        // Display Categories
        function displayCategories(categories) {
            const grid = document.getElementById('categoriesGrid');
            let html = '';
            
            categories.forEach(category => {
                const statusBadge = category.status === 'active' 
                    ? '<span class="px-2 py-1 bg-green-100 text-green-700 rounded-full text-xs font-semibold">Active</span>'
                    : '<span class="px-2 py-1 bg-gray-100 text-gray-700 rounded-full text-xs font-semibold">Inactive</span>';
                
                html += `
                    <div class="bg-white rounded-xl shadow-md p-6 hover:shadow-xl transition-all duration-300 card-hover">
                        <div class="flex items-start justify-between mb-4">
                            <div class="text-4xl">${category.icon || '📦'}</div>
                            ${statusBadge}
                        </div>
                        <h3 class="text-xl font-bold text-licorice mb-2">${category.name}</h3>
                        <p class="text-sm text-gray-600 mb-4 line-clamp-2">${category.description || 'No description'}</p>
                        <div class="flex items-center justify-between text-sm text-gray-500 mb-4">
                            <span>📦 ${category.product_count} products</span>
                            <span>📂 ${category.subcategory_count} subcats</span>
                        </div>
                        <div class="flex items-center gap-2">
                            <button onclick="editCategory(${category.id})" class="flex-1 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors text-sm font-semibold">
                                Edit
                            </button>
                            <button onclick="deleteCategory(${category.id}, '${category.name}')" class="flex-1 px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors text-sm font-semibold">
                                Delete
                            </button>
                        </div>
                    </div>
                `;
            });
            
            grid.innerHTML = html;
        }

        // Show Empty State
        function showEmptyState() {
            document.getElementById('categoriesGrid').innerHTML = `
                <div class="col-span-full text-center py-20">
                    <svg class="w-24 h-24 mx-auto text-gray-300 mb-4" 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>
                    <h3 class="text-xl font-semibold text-gray-600 mb-2">No Categories Found</h3>
                    <p class="text-gray-500 mb-6">Get started by adding your first category</p>
                    <button onclick="openModal()" class="btn-primary px-6 py-3 rounded-xl text-white font-semibold inline-flex items-center gap-2 shadow-lg">
                        <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="M12 6v6m0 0v6m0-6h6m-6 0H6"/>
                        </svg>
                        Add First Category
                    </button>
                </div>
            `;
        }

        // Show Error State
        function showErrorState() {
            document.getElementById('categoriesGrid').innerHTML = `
                <div class="col-span-full text-center py-20 text-red-500">
                    Error loading categories
                </div>
            `;
        }

        // Form Submission
        categoryForm.addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<svg class="animate-spin w-5 h-5 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> Saving...';
            
            const formData = new FormData(this);
            const categoryData = {
                name: formData.get('name'),
                description: formData.get('description') || null,
                icon: formData.get('icon') || null,
                color: formData.get('color') || null,
                sort_order: parseInt(formData.get('sort_order')) || 0,
                status: formData.get('status'),
                parent_id: null
            };
            
            const categoryId = document.getElementById('categoryId').value;
            const url = editMode ? `api/categories.php?id=${categoryId}` : 'api/categories.php';
            const method = editMode ? 'PUT' : 'POST';
            
            try {
                const response = await fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(categoryData)
                });
                
                const data = await response.json();
                console.log('Save Response:', data);
                
                if (data.success === true) {
                    showNotification('success', editMode ? 'Category updated successfully!' : 'Category created successfully!');
                    closeModalFunc();
                    loadCategories();
                } else {
                    throw new Error(data.message);
                }
            } catch (error) {
                showNotification('error', error.message || 'Operation failed');
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalText;
            }
        });

        // Edit Category
        async function editCategory(id) {
            try {
                const response = await fetch(`api/categories.php?id=${id}`, {
                    method: 'GET'
                });
                
                const data = await response.json();
                console.log('Edit Response:', data);
                
                if (data.success === true) {
                    openModal(data.data);
                } else {
                    throw new Error(data.message);
                }
            } catch (error) {
                showNotification('error', 'Failed to load category');
            }
        }

        // Delete Category
        async function deleteCategory(id, name) {
            if (!confirm(`Are you sure you want to delete "${name}"? This action cannot be undone.`)) {
                return;
            }
            
            try {
                const response = await fetch(`api/categories.php?id=${id}`, {
                    method: 'DELETE'
                });
                
                const data = await response.json();
                console.log('Delete Response:', data);
                
                if (data.success === true) {
                    showNotification('success', 'Category deleted successfully!');
                    loadCategories();
                } else {
                    throw new Error(data.message);
                }
            } catch (error) {
                showNotification('error', error.message || 'Failed to delete category');
            }
        }

        // 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 categories on page load
        loadCategories();
    </script>
<?php require_once 'views/fotter-dashboard.php'; ?>