<?php
/**
 * ADMIN CATEGORIES MANAGEMENT PAGE
 * File: admin/categories.php
 * CRUD operations for item categories
 */

require_once '../app/Core/init.php';

// Check admin authentication
Auth::requireAdmin();

$page_title = "Categories Management";
$active_menu = "categories";

// Initialize models
$db = Database::getInstance();
$category_model = new Category();

// Initialize models
$db = Database::getInstance();
$category_model = new Category();

function create_slug($string, $separator = '-')
{
    $string = strtolower(trim($string));
    $string = preg_replace('/[^a-z0-9]+/', $separator, $string);
    $string = trim($string, $separator);
    $string = preg_replace('/' . preg_quote($separator, '/') . '+/', $separator, $string);
    if (empty($string)) {
        return 'category' . $separator . uniqid();
    }    
    return $string;
}


// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    switch ($action) {
        case 'create':
            $name = trim($_POST['name'] ?? '');
            $description = trim($_POST['description'] ?? '');
            $icon = trim($_POST['icon'] ?? '');
            $parent_id = !empty($_POST['parent_id']) ? (int)$_POST['parent_id'] : null;
            
            if (empty($name)) {
                flash('message', ['type' => 'danger', 'message' => 'Category name is required']);
            } else {
                try {
                    $slug = create_slug($name);
                    
                    $category_model->create([
                        'name' => $name,
                        'slug' => $slug,
                        'description' => $description,
                        'icon' => $icon,
                        'parent_id' => $parent_id,
                        'status' => 'active'
                    ]);
                    
                    flash('message', ['type' => 'success', 'message' => 'Category created successfully']);
                    header('Location: categories.php');
                    exit;
                } catch (Exception $e) {
                    flash('message', ['type' => 'danger', 'message' => 'Error creating category: ' . $e->getMessage()]);
                }
            }
            break;
            
        case 'update':
            $id = (int)$_POST['id'];
            $name = trim($_POST['name'] ?? '');
            $description = trim($_POST['description'] ?? '');
            $icon = trim($_POST['icon'] ?? '');
            $parent_id = !empty($_POST['parent_id']) ? (int)$_POST['parent_id'] : null;
            $status = $_POST['status'] ?? 'active';
            $display_order = (int)($_POST['display_order'] ?? 0);
            
            if (empty($name)) {
                flash('message', ['type' => 'danger', 'message' => 'Category name is required']);
            } else {
                try {
                    $category_model->update($id, [
                        'name' => $name,
                        'description' => $description,
                        'icon' => $icon,
                        'parent_id' => $parent_id,
                        'status' => $status,
                        'display_order' => $display_order
                    ]);
                    
                    flash('message', ['type' => 'success', 'message' => 'Category updated successfully']);
                    header('Location: categories.php');
                    exit;
                } catch (Exception $e) {
                    flash('message', ['type' => 'danger', 'message' => 'Error updating category: ' . $e->getMessage()]);
                }
            }
            break;
            
        case 'delete':
            $id = (int)$_POST['id'];
            
            // Check if category has items
            $check_sql = "SELECT COUNT(*) as count FROM items WHERE category_id = ?";
            $result = $db->fetch($check_sql, [$id]);
            
            if ($result['count'] > 0) {
                flash('message', ['type' => 'danger', 'message' => 'Cannot delete category with existing items']);
            } else {
                try {
                    $category_model->delete($id);
                    flash('message', ['type' => 'success', 'message' => 'Category deleted successfully']);
                    header('Location: categories.php');
                    exit;
                } catch (Exception $e) {
                    flash('message', ['type' => 'danger', 'message' => 'Error deleting category: ' . $e->getMessage()]);
                }
            }
            break;
            
        case 'bulk_action':
            $selected_categories = $_POST['selected_categories'] ?? [];
            $bulk_action = $_POST['bulk_action'] ?? '';
            
            if (!empty($selected_categories) && !empty($bulk_action)) {
                try {
                    switch ($bulk_action) {
                        case 'activate':
                            foreach ($selected_categories as $cat_id) {
                                $category_model->update((int)$cat_id, ['status' => 'active']);
                            }
                            flash('message', ['type' => 'success', 'message' => 'Categories activated successfully']);
                            break;
                            
                        case 'deactivate':
                            foreach ($selected_categories as $cat_id) {
                                $category_model->update((int)$cat_id, ['status' => 'inactive']);
                            }
                            flash('message', ['type' => 'success', 'message' => 'Categories deactivated successfully']);
                            break;
                            
                        case 'delete':
                            foreach ($selected_categories as $cat_id) {
                                // Check for items before deletion
                                $check_sql = "SELECT COUNT(*) as count FROM items WHERE category_id = ?";
                                $result = $db->fetch($check_sql, [(int)$cat_id]);
                                if ($result['count'] == 0) {
                                    $category_model->delete((int)$cat_id);
                                }
                            }
                            flash('message', ['type' => 'success', 'message' => 'Selected categories deleted successfully']);
                            break;
                    }
                } catch (Exception $e) {
                    flash('message', ['type' => 'danger', 'message' => 'Error processing bulk action: ' . $e->getMessage()]);
                }
            }
            break;
    }
}

// Get categories with item counts
$categories_sql = "SELECT c.*, 
                   (SELECT COUNT(*) FROM items WHERE category_id = c.id) as item_count,
                   (SELECT name FROM categories WHERE id = c.parent_id) as parent_name
                   FROM categories c 
                   ORDER BY c.display_order ASC, c.name ASC";
$categories = $db->fetchAll($categories_sql);

// Get parent categories for dropdown
$parent_categories_sql = "SELECT id, name FROM categories WHERE parent_id IS NULL ORDER BY name";
$parent_categories = $db->fetchAll($parent_categories_sql);

// Handle flash messages
$flash_message = flash('message');

// Get category for editing
$edit_category = null;
if (isset($_GET['edit'])) {
    $edit_id = (int)$_GET['edit'];
    $edit_sql = "SELECT * FROM categories WHERE id = ?";
    $edit_category = $db->fetch($edit_sql, [$edit_id]);
}

include '../templates/layouts/admin/head.php';
?>

<div class="main-content">
    <?php include '../templates/layouts/admin/header.php'; ?>

    <!-- Page Header -->
    <div style="padding: 30px; background: white; border-bottom: 1px solid #eee;">
        <h1 style="font-size: 28px; font-weight: 700; color: var(--dark); margin-bottom: 5px;">
            <i class="fas fa-tags"></i> Categories Management
        </h1>
        <div style="display: flex; gap: 8px; font-size: 14px; color: #666;">
            <a href="index.php" style="color: var(--primary); text-decoration: none;">Home</a>
            <span>/</span>
            <span>Categories</span>
        </div>
    </div>
    
    <!-- Content -->
    <div style="padding: 30px;">
        
        <!-- Flash Messages -->
        <?php if ($flash_message): ?>
            <div class="alert alert-<?= $flash_message['type'] ?>">
                <?= Security::escapeOutput($flash_message['message']) ?>
            </div>
        <?php endif; ?>
        
        <!-- Action Buttons -->
        <div style="margin-bottom: 30px; display: flex; justify-content: space-between; align-items: center;">
            <div>
                <button onclick="showCreateModal()" class="btn btn-primary">
                    <i class="fas fa-plus"></i> Add New Category
                </button>
            </div>
            
            <div style="color: #666; font-size: 14px;">
                Total: <?= count($categories) ?> categories
            </div>
        </div>
        
        <!-- Categories Table -->
        <div style="background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.05);">
            <form method="POST" id="bulkForm">
                <input type="hidden" name="action" value="bulk_action">
                
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                    <h3 style="font-size: 18px; font-weight: 600; color: var(--dark); margin: 0;">All Categories</h3>
                    
                    <?php if (!empty($categories)): ?>
                        <div style="display: flex; gap: 10px; align-items: center;">
                            <select name="bulk_action" class="form-control" style="width: auto;">
                                <option value="">Bulk Actions</option>
                                <option value="activate">Activate</option>
                                <option value="deactivate">Deactivate</option>
                                <option value="delete">Delete</option>
                            </select>
                            <button type="submit" class="btn btn-secondary" onclick="return confirm('Apply bulk action to selected categories?')">
                                Apply
                            </button>
                        </div>
                    <?php endif; ?>
                </div>
                
                <div style="overflow-x: auto;">
                    <table style="width: 100%; border-collapse: collapse;">
                        <thead>
                            <tr style="background: #f8f9fa;">
                                <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">
                                    <input type="checkbox" id="selectAll" onchange="toggleSelectAll()">
                                </th>
                                <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">Icon</th>
                                <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">Name</th>
                                <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">Parent</th>
                                <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">Items</th>
                                <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">Order</th>
                                <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">Status</th>
                                <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($categories)): ?>
                                <tr>
                                    <td colspan="8" style="padding: 30px; text-align: center; color: #999;">
                                        <i class="fas fa-tags fa-3x mb-3"></i>
                                        <p>No categories found</p>
                                        <button type="button" onclick="showCreateModal()" class="btn btn-primary">
                                            <i class="fas fa-plus"></i> Create First Category
                                        </button>
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($categories as $category): ?>
                                    <tr style="border-bottom: 1px solid #f0f0f0;">
                                        <td style="padding: 15px;">
                                            <input type="checkbox" name="selected_categories[]" value="<?= $category['id'] ?>" class="category-checkbox">
                                        </td>
                                        <td style="padding: 15px;">
                                            <?php if (!empty($category['icon'])): ?>
                                                <i class="<?= Security::escapeOutput($category['icon']) ?>" style="font-size: 20px; color: var(--primary);"></i>
                                            <?php else: ?>
                                                <i class="fas fa-folder" style="font-size: 20px; color: #ccc;"></i>
                                            <?php endif; ?>
                                        </td>
                                        <td style="padding: 15px;">
                                            <div style="font-weight: 600;">
                                                <?= Security::escapeOutput($category['name']) ?>
                                            </div>
                                            <?php if (!empty($category['description'])): ?>
                                                <small style="color: #666;">
                                                    <?= Security::escapeOutput(str_limit($category['description'], 50)) ?>
                                                </small>
                                            <?php endif; ?>
                                        </td>
                                        <td style="padding: 15px;">
                                            <?= Security::escapeOutput($category['parent_name'] ?? '-') ?>
                                        </td>
                                        <td style="padding: 15px;">
                                            <span style="background: var(--info); color: white; padding: 4px 8px; border-radius: 12px; font-size: 12px;">
                                                <?= $category['item_count'] ?>
                                            </span>
                                        </td>
                                        <td style="padding: 15px;">
                                            <input type="number" 
                                                   value="<?= $category['display_order'] ?>" 
                                                   class="form-control form-control-sm" 
                                                   style="width: 60px;"
                                                   onchange="updateOrder(<?= $category['id'] ?>, this.value)">
                                        </td>
                                        <td style="padding: 15px;">
                                            <?php
                                            $status_class = $category['status'] === 'active' ? 'status-approved' : 'status-rejected';
                                            ?>
                                            <span class="status-badge <?= $status_class ?>">
                                                <?= ucfirst($category['status']) ?>
                                            </span>
                                        </td>
                                        <td style="padding: 15px;">
                                            <div class="action-buttons">
                                                <button onclick="editCategory(<?= $category['id'] ?>)" 
                                                        class="btn-action btn-edit" 
                                                        title="Edit Category">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                
                                                <?php if ($category['item_count'] == 0): ?>
                                                    <button onclick="deleteCategory(<?= $category['id'] ?>, '<?= Security::escapeOutput($category['name']) ?>')" 
                                                            class="btn-action btn-delete" 
                                                            title="Delete Category">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                <?php endif; ?>
                                                
                                                <?php if ($category['status'] === 'active'): ?>
                                                    <button onclick="toggleStatus(<?= $category['id'] ?>, 'inactive')" 
                                                            class="btn-action btn-warning" 
                                                            title="Deactivate">
                                                        <i class="fas fa-pause"></i>
                                                    </button>
                                                <?php else: ?>
                                                    <button onclick="toggleStatus(<?= $category['id'] ?>, 'active')" 
                                                            class="btn-action btn-success" 
                                                            title="Activate">
                                                        <i class="fas fa-play"></i>
                                                    </button>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Create/Edit Category Modal -->
<div id="categoryModal" class="modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 9999;">
    <div class="modal-content" style="background: white; margin: 50px auto; padding: 30px; border-radius: 12px; width: 90%; max-width: 500px; max-height: 90vh; overflow-y: auto;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px;">
            <h3 id="modalTitle" style="margin: 0; font-size: 20px; font-weight: 600;">
                <?= $edit_category ? 'Edit Category' : 'Add New Category' ?>
            </h3>
            <button onclick="closeModal()" style="background: none; border: none; font-size: 24px; cursor: pointer;">&times;</button>
        </div>
        
        <form method="POST" id="categoryForm">
            <?php if ($edit_category): ?>
                <input type="hidden" name="action" value="update">
                <input type="hidden" name="id" value="<?= $edit_category['id'] ?>">
            <?php else: ?>
                <!-- <input type="hidden" name="action" value="create"> -->
                 <script>
                    document.querySelectorAll('#categoryForm .form-group').forEach(group => {
                        if (group.innerHTML.includes('name="status"') || group.innerHTML.includes('name="display_order"')) {
                            group.style.display = 'none';
                        }
                    });
                </script>
            <?php endif; ?>
            
            <div class="form-group" style="margin-bottom: 20px;">
                <label style="display: block; margin-bottom: 8px; font-weight: 600; color: var(--dark);">Category Name *</label>
                <input type="text" 
                       name="name" 
                       class="form-control" 
                       value="<?= Security::escapeOutput($edit_category['name'] ?? '') ?>"
                       placeholder="Enter category name"
                       required>
            </div>
            
            <div class="form-group" style="margin-bottom: 20px;">
                <label style="display: block; margin-bottom: 8px; font-weight: 600; color: var(--dark);">Description</label>
                <textarea name="description" 
                          class="form-control" 
                          rows="3" 
                          placeholder="Enter category description"><?= Security::escapeOutput($edit_category['description'] ?? '') ?></textarea>
            </div>
            
            <div class="form-group" style="margin-bottom: 20px;">
                <label style="display: block; margin-bottom: 8px; font-weight: 600; color: var(--dark);">Icon Class</label>
                <input type="text" 
                       name="icon" 
                       class="form-control" 
                       value="<?= Security::escapeOutput($edit_category['icon'] ?? '') ?>"
                       placeholder="e.g., fas fa-laptop">
                <small style="color: #666; font-size: 12px;">Font Awesome icon class (optional)</small>
            </div>
            
            <div class="form-group" style="margin-bottom: 20px;">
                <label style="display: block; margin-bottom: 8px; font-weight: 600; color: var(--dark);">Parent Category</label>
                <select name="parent_id" class="form-control">
                    <option value="">No Parent (Root Category)</option>
                    <?php foreach ($parent_categories as $parent): ?>
                        <?php if (!$edit_category || $parent['id'] != $edit_category['id']): ?>
                            <option value="<?= $parent['id'] ?>" 
                                    <?= ($edit_category && $edit_category['parent_id'] == $parent['id']) ? 'selected' : '' ?>>
                                <?= Security::escapeOutput($parent['name']) ?>
                            </option>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <?php if ($edit_category): ?>
                <div class="form-group" style="margin-bottom: 20px;">
                    <label style="display: block; margin-bottom: 8px; font-weight: 600; color: var(--dark);">Status</label>
                    <select name="status" class="form-control">
                        <option value="active" <?= ($edit_category['status'] === 'active') ? 'selected' : '' ?>>Active</option>
                        <option value="inactive" <?= ($edit_category['status'] === 'inactive') ? 'selected' : '' ?>>Inactive</option>
                    </select>
                </div>
                
                <div class="form-group" style="margin-bottom: 20px;">
                    <label style="display: block; margin-bottom: 8px; font-weight: 600; color: var(--dark);">Display Order</label>
                    <input type="number" 
                           name="display_order" 
                           class="form-control" 
                           value="<?= $edit_category['display_order'] ?>"
                           min="0">
                </div>
            <?php endif; ?>
            
            <div style="display: flex; gap: 15px; justify-content: flex-end;">
                <button type="button" onclick="closeModal()" class="btn btn-secondary">
                    Cancel
                </button>
                <button type="submit" class="btn btn-primary">
                    <?= $edit_category ? 'Update Category' : 'Create Category' ?>
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div id="deleteModal" class="modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 9999;">
    <div class="modal-content" style="background: white; margin: 100px auto; padding: 30px; border-radius: 12px; width: 90%; max-width: 400px;">
        <h3 style="margin-bottom: 20px; font-size: 20px; font-weight: 600;">Confirm Delete</h3>
        <p id="deleteMessage" style="margin-bottom: 25px; line-height: 1.6;">Are you sure you want to delete this category?</p>
        
        <form method="POST" id="deleteForm">
            <input type="hidden" name="action" value="delete">
            <input type="hidden" name="id" id="deleteId">
            
            <div style="display: flex; gap: 15px; justify-content: flex-end;">
                <button type="button" onclick="closeDeleteModal()" class="btn btn-secondary">
                    Cancel
                </button>
                <button type="submit" class="btn btn-danger">
                    Delete Category
                </button>
            </div>
        </form>
    </div>
</div>

<style>
.modal {
    animation: fadeIn 0.3s;
}

.modal-content {
    animation: slideIn 0.3s;
}

@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}

@keyframes slideIn {
    from { transform: translateY(-50px); opacity: 0; }
    to { transform: translateY(0); opacity: 1; }
}

.status-approved {
    background: var(--success);
    color: white;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
}

.status-rejected {
    background: var(--danger);
    color: white;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
}

.action-buttons {
    display: flex;
    gap: 5px;
}

.btn-action {
    background: none;
    border: 1px solid #ddd;
    padding: 8px;
    border-radius: 5px;
    cursor: pointer;
    transition: all 0.3s;
    color: #666;
    font-size: 14px;
}

.btn-action:hover {
    transform: translateY(-2px);
    box-shadow: 0 2px 5px rgba(0,0,0,0.2);
}

.btn-edit:hover {
    border-color: var(--primary);
    color: var(--primary);
}

.btn-delete:hover {
    border-color: var(--danger);
    color: var(--danger);
}

.btn-warning:hover {
    border-color: var(--warning);
    color: var(--warning);
}

.btn-success:hover {
    border-color: var(--success);
    color: var(--success);
}

.form-control {
    border: 1px solid #ddd;
    border-radius: 6px;
    padding: 10px 12px;
    font-size: 14px;
    transition: border-color 0.3s;
}

.form-control:focus {
    outline: none;
    border-color: var(--primary);
    box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}

.btn {
    border: none;
    border-radius: 6px;
    padding: 10px 20px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s;
    text-decoration: none;
    display: inline-block;
    font-size: 14px;
}

.btn-primary {
    background: var(--primary);
    color: white;
}

.btn-primary:hover {
    background: #0056b3;
    transform: translateY(-2px);
}

.btn-secondary {
    background: #6c757d;
    color: white;
}

.btn-secondary:hover {
    background: #545b62;
}

.btn-danger {
    background: var(--danger);
    color: white;
}

.btn-danger:hover {
    background: #c82333;
}

.alert {
    padding: 15px 20px;
    border-radius: 8px;
    margin-bottom: 20px;
}

.alert-success {
    background: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
}

.alert-danger {
    background: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
}
</style>

<script>
// Menu Toggle
document.getElementById('menuToggle')?.addEventListener('click', function() {
    document.getElementById('sidebar').classList.toggle('active');
});

// Show modal
function showCreateModal() {
    document.getElementById('modalTitle').textContent = 'Add New Category';
    document.getElementById('categoryForm').reset();
    document.querySelector('#categoryForm [name="action"]').value = 'create';
    
    // Remove hidden id field if exists
    const idField = document.querySelector('#categoryForm [name="id"]');
    if (idField) idField.remove();

    // Hide edit-only fields
    document.querySelectorAll('#categoryForm .form-group').forEach(group => {
        if (group.innerHTML.includes('name="status"') || group.innerHTML.includes('name="display_order"')) {
            group.style.display = 'none';
        }
    });

    document.getElementById('categoryModal').style.display = 'block';
}

// Edit category
function editCategory(id) {
    fetch(`category-get.php?id=${id}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const cat = data.category;
                
                document.getElementById('modalTitle').textContent = 'Edit Category';
                document.querySelector('#categoryForm [name="action"]').value = 'update';
                document.querySelector('#categoryForm [name="id"]').value = cat.id;
                document.querySelector('#categoryForm [name="name"]').value = cat.name;
                document.querySelector('#categoryForm [name="description"]').value = cat.description || '';
                document.querySelector('#categoryForm [name="icon"]').value = cat.icon || '';
                document.querySelector('#categoryForm [name="parent_id"]').value = cat.parent_id || '';
                document.querySelector('#categoryForm [name="status"]').value = cat.status;
                document.querySelector('#categoryForm [name="display_order"]').value = cat.display_order;

                // Show status and order fields only in edit mode
                document.querySelectorAll('#categoryForm .form-group').forEach(group => {
                    if (group.querySelector('[name="status"]') || group.querySelector('[name="display_order"]')) {
                        group.style.display = 'block';
                    }
                });

                document.getElementById('categoryModal').style.display = 'block';
            } else {
                alert('Failed to load category');
            }
        })
        .catch(() => alert('Error loading category'));
}

// Close modal
function closeModal() {
    document.getElementById('categoryModal').style.display = 'none';
    if (window.location.search.includes('edit=')) {
        window.location.href = 'categories.php';
    }
}

// Delete category
function deleteCategory(id, name) {
    document.getElementById('deleteId').value = id;
    document.getElementById('deleteMessage').textContent = `Are you sure you want to delete the category "${name}"? This action cannot be undone.`;
    document.getElementById('deleteModal').style.display = 'block';
}

function closeDeleteModal() {
    document.getElementById('deleteModal').style.display = 'none';
}

// Toggle status
function toggleStatus(id, status) {
    if (!confirm(`Are you sure you want to ${status === 'active' ? 'activate' : 'deactivate'} this category?`)) return;

    fetch('category-toggle-status.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `id=${id}&status=${status}`
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
            alert(data.message || 'Failed to update status');
        }
    });
}

// Update display order
function updateOrder(id, order) {
    // This would typically be done via AJAX
    fetch('category-update-order.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `id=${id}&display_order=${order}`
    }).then(response => {
        if (response.ok) {
            console.log('Order updated');
        }
    });
}

// Toggle select all
function toggleSelectAll() {
    const selectAll = document.getElementById('selectAll');
    const checkboxes = document.querySelectorAll('.category-checkbox');
    
    checkboxes.forEach(checkbox => {
        checkbox.checked = selectAll.checked;
    });
}

// Close modals when clicking outside
window.onclick = function(event) {
    const categoryModal = document.getElementById('categoryModal');
    const deleteModal = document.getElementById('deleteModal');
    
    if (event.target === categoryModal) {
        closeModal();
    }
    if (event.target === deleteModal) {
        closeDeleteModal();
    }
}

// Auto-hide success messages
setTimeout(function() {
    const alerts = document.querySelectorAll('.alert-success');
    alerts.forEach(alert => {
        alert.style.transition = 'opacity 0.5s';
        alert.style.opacity = '0';
        setTimeout(() => alert.remove(), 500);
    });
}, 3000);
</script>

<?php include '../templates/layouts/admin/footer.php'; ?>