<?php
require_once '../includes/middleware.php';
requirePermission('manage_course_categories');
require_once '../config/database.php';
require_once '../includes/functions.php';

$db = getDB();
$message = '';
$error = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'create':
                $name = trim($_POST['name']);
                $slug = trim($_POST['slug']);
                $description = trim($_POST['description']);
                $icon = trim($_POST['icon']);
                $color = trim($_POST['color']);
                $parent_id = !empty($_POST['parent_id']) ? $_POST['parent_id'] : null;
                $is_active = isset($_POST['is_active']) ? 1 : 0;

                if (empty($name) || empty($slug)) {
                    $error = 'Name and slug are required.';
                } else {
                    try {
                        $stmt = $db->prepare("INSERT INTO course_categories (name, slug, description, icon, color, parent_id, is_active) VALUES (?, ?, ?, ?, ?, ?, ?)");
                        $stmt->execute([$name, $slug, $description, $icon, $color, $parent_id, $is_active]);
                        $message = 'Category created successfully.';
                    } catch (PDOException $e) {
                        $error = 'Error creating category: ' . $e->getMessage();
                    }
                }
                break;

            case 'update':
                $id = $_POST['id'];
                $name = trim($_POST['name']);
                $slug = trim($_POST['slug']);
                $description = trim($_POST['description']);
                $icon = trim($_POST['icon']);
                $color = trim($_POST['color']);
                $parent_id = !empty($_POST['parent_id']) ? $_POST['parent_id'] : null;
                $is_active = isset($_POST['is_active']) ? 1 : 0;

                if (empty($name) || empty($slug)) {
                    $error = 'Name and slug are required.';
                } else {
                    try {
                        $stmt = $db->prepare("UPDATE course_categories SET name = ?, slug = ?, description = ?, icon = ?, color = ?, parent_id = ?, is_active = ? WHERE id = ?");
                        $stmt->execute([$name, $slug, $description, $icon, $color, $parent_id, $is_active, $id]);
                        $message = 'Category updated successfully.';
                    } catch (PDOException $e) {
                        $error = 'Error updating category: ' . $e->getMessage();
                    }
                }
                break;

            case 'delete':
                $id = $_POST['id'];
                try {
                    // Check if category has courses
                    $stmt = $db->prepare("SELECT COUNT(*) FROM courses WHERE category_id = ?");
                    $stmt->execute([$id]);
                    $courseCount = $stmt->fetchColumn();

                    if ($courseCount > 0) {
                        $error = 'Cannot delete category with existing courses.';
                    } else {
                        $stmt = $db->prepare("DELETE FROM course_categories WHERE id = ?");
                        $stmt->execute([$id]);
                        $message = 'Category deleted successfully.';
                    }
                } catch (PDOException $e) {
                    $error = 'Error deleting category: ' . $e->getMessage();
                }
                break;
        }
    }
}

// Get all categories
$stmt = $db->query("SELECT c1.*, c2.name as parent_name FROM course_categories c1 LEFT JOIN course_categories c2 ON c1.parent_id = c2.id ORDER BY c1.sort_order, c1.name");
$categories = $stmt->fetchAll();

// Get categories for parent dropdown (only top-level)
$stmt = $db->query("SELECT id, name FROM course_categories WHERE parent_id IS NULL ORDER BY name");
$parentCategories = $stmt->fetchAll();

$pageTitle = 'Course Categories';
include 'includes/admin_header.php';
?>

<style>
    /* Custom page-specific styles */
    .page-header-gradient {
        background: linear-gradient(135deg, #1E3A8A 0%, #3B82F6 100%);
    }
    
    .stat-card {
        transition: all 0.3s ease;
    }
    
    .stat-card:hover {
        transform: translateY(-4px);
        box-shadow: 0 12px 24px rgba(0, 0, 0, 0.15);
    }
    
    .table-container {
        border-radius: 12px;
        overflow: hidden;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
    }
    
    .table-header {
        background: linear-gradient(to right, #f8fafc, #f1f5f9);
    }
    
    .table-row {
        transition: all 0.2s ease;
    }
    
    .table-row:hover {
        background: linear-gradient(to right, #f8fafc, #eff6ff);
    }
    
    .category-badge {
        display: inline-flex;
        align-items: center;
        padding: 4px 12px;
        border-radius: 9999px;
        font-size: 0.75rem;
        font-weight: 600;
    }
    
    .badge-active {
        background: linear-gradient(135deg, #dcfce7, #bbf7d0);
        color: #166534;
    }
    
    .badge-inactive {
        background: linear-gradient(135deg, #fef3c7, #fde68a);
        color: #92400e;
    }
    
    .btn-action {
        padding: 6px 12px;
        border-radius: 8px;
        font-size: 0.813rem;
        font-weight: 500;
        transition: all 0.2s ease;
        display: inline-flex;
        align-items: center;
        gap: 6px;
    }
    
    .btn-action:hover {
        transform: translateY(-1px);
    }
    
    .btn-edit {
        background: #eff6ff;
        color: #2563eb;
        border: 1px solid #bfdbfe;
    }
    
    .btn-edit:hover {
        background: #dbeafe;
        border-color: #93c5fd;
    }
    
    .btn-delete {
        background: #fef2f2;
        color: #dc2626;
        border: 1px solid #fecaca;
    }
    
    .btn-delete:hover {
        background: #fee2e2;
        border-color: #fca5a5;
    }
    
    .btn-primary-custom {
        background: linear-gradient(135deg, #1E3A8A, #3B82F6);
        color: white;
        border: none;
        padding: 10px 20px;
        border-radius: 10px;
        font-weight: 600;
        transition: all 0.3s ease;
        box-shadow: 0 4px 6px -1px rgba(30, 58, 138, 0.3);
    }
    
    .btn-primary-custom:hover {
        background: linear-gradient(135deg, #1e40af, #2563eb);
        transform: translateY(-2px);
        box-shadow: 0 8px 12px -2px rgba(30, 58, 138, 0.4);
    }
    
    /* Modal enhancements */
    .modal-header-custom {
        background: linear-gradient(to right, #f8fafc, #f1f5f9);
        border-bottom: 1px solid #e2e8f0;
        padding: 1.25rem 1.5rem;
    }
    
    .modal-footer-custom {
        background: #f8fafc;
        border-top: 1px solid #e2e8f0;
        padding: 1rem 1.5rem;
    }
    
    .form-label-custom {
        font-weight: 600;
        color: #374151;
        font-size: 0.875rem;
        margin-bottom: 0.5rem;
    }
    
    .form-input-custom {
        border: 2px solid #e2e8f0;
        border-radius: 10px;
        padding: 10px 14px;
        font-size: 0.875rem;
        transition: all 0.2s ease;
    }
    
    .form-input-custom:focus {
        border-color: #3B82F6;
        box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        outline: none;
    }
    
    .form-select-custom {
        border: 2px solid #e2e8f0;
        border-radius: 10px;
        padding: 10px 14px;
        font-size: 0.875rem;
        transition: all 0.2s ease;
        background-color: white;
    }
    
    .form-select-custom:focus {
        border-color: #3B82F6;
        box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        outline: none;
    }
    
    .color-input-wrapper {
        position: relative;
        height: 48px;
    }
    
    .color-input-wrapper input[type="color"] {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        padding: 4px;
        border: 2px solid #e2e8f0;
        border-radius: 10px;
        cursor: pointer;
    }
    
    .checkbox-custom {
        width: 20px;
        height: 20px;
        border-radius: 6px;
        border: 2px solid #d1d5db;
        cursor: pointer;
        accent-color: #3B82F6;
    }
    
    .empty-state {
        padding: 4rem 2rem;
        text-align: center;
    }
    
    .empty-state-icon {
        width: 80px;
        height: 80px;
        background: linear-gradient(135deg, #f1f5f9, #e2e8f0);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 1.5rem;
    }
    
    .empty-state-icon i {
        font-size: 2rem;
        color: #94a3b8;
    }
    
    /* Alert styles */
    .alert-custom {
        border-radius: 12px;
        padding: 1rem 1.25rem;
        border: none;
        display: flex;
        align-items: center;
        gap: 12px;
    }
    
    .alert-success-custom {
        background: linear-gradient(135deg, #dcfce7, #bbf7d0);
        color: #166534;
    }
    
    .alert-danger-custom {
        background: linear-gradient(135deg, #fee2e2, #fecaca);
        color: #991b1b;
    }
    
    .alert-icon {
        width: 24px;
        height: 24px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        flex-shrink: 0;
    }
    
    .alert-success-custom .alert-icon {
        background: #166534;
        color: white;
    }
    
    .alert-danger-custom .alert-icon {
        background: #991b1b;
        color: white;
    }
    
    /* Category icon in table */
    .category-icon-wrapper {
        width: 40px;
        height: 40px;
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
    }
    
    /* Responsive adjustments */
    @media (max-width: 768px) {
        .stats-grid {
            grid-template-columns: repeat(2, 1fr);
        }
        
        .table-container {
            overflow-x: auto;
        }
    }
    
    @media (max-width: 480px) {
        .stats-grid {
            grid-template-columns: 1fr;
        }
    }
</style>

<!-- Page Header -->
<div class="page-header-gradient rounded-xl p-6 mb-6 text-white shadow-lg">
    <div class="flex flex-col md:flex-row md:items-center md:justify-between">
        <div>
            <h1 class="text-2xl md:text-3xl font-bold flex items-center gap-3">
                <i class="fas fa-folder-tree"></i>
                Course Categories
            </h1>
            <p class="text-blue-100 mt-1">Organize and manage your course categories</p>
        </div>
        <div class="mt-4 md:mt-0">
            <button class="btn-primary-custom flex items-center gap-2" data-bs-toggle="modal" data-bs-target="#createCategoryModal">
                <i class="fas fa-plus-circle"></i>
                <span>Add New Category</span>
            </button>
        </div>
    </div>
</div>

<!-- Stats Cards -->
<div class="stats-grid grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
    <!-- Total Categories -->
    <div class="stat-card bg-white rounded-xl p-5 shadow-md border border-gray-100">
        <div class="flex items-center gap-4">
            <div class="w-14 h-14 rounded-xl bg-gradient-to-br from-blue-500 to-blue-600 flex items-center justify-center shadow-lg">
                <i class="fas fa-tags text-white text-xl"></i>
            </div>
            <div>
                <p class="text-sm text-gray-500 font-medium">Total Categories</p>
                <p class="text-2xl font-bold text-gray-800"><?php echo count($categories); ?></p>
            </div>
        </div>
    </div>
    
    <!-- Active Categories -->
    <div class="stat-card bg-white rounded-xl p-5 shadow-md border border-gray-100">
        <div class="flex items-center gap-4">
            <div class="w-14 h-14 rounded-xl bg-gradient-to-br from-green-500 to-green-600 flex items-center justify-center shadow-lg">
                <i class="fas fa-check-circle text-white text-xl"></i>
            </div>
            <div>
                <p class="text-sm text-gray-500 font-medium">Active</p>
                <p class="text-2xl font-bold text-gray-800"><?php echo count(array_filter($categories, function($cat) { return $cat['is_active']; })); ?></p>
            </div>
        </div>
    </div>
    
    <!-- Top Level -->
    <div class="stat-card bg-white rounded-xl p-5 shadow-md border border-gray-100">
        <div class="flex items-center gap-4">
            <div class="w-14 h-14 rounded-xl bg-gradient-to-br from-purple-500 to-purple-600 flex items-center justify-center shadow-lg">
                <i class="fas fa-folder text-white text-xl"></i>
            </div>
            <div>
                <p class="text-sm text-gray-500 font-medium">Top Level</p>
                <p class="text-2xl font-bold text-gray-800"><?php echo count(array_filter($categories, function($cat) { return $cat['parent_id'] === null; })); ?></p>
            </div>
        </div>
    </div>
    
    <!-- Subcategories -->
    <div class="stat-card bg-white rounded-xl p-5 shadow-md border border-gray-100">
        <div class="flex items-center gap-4">
            <div class="w-14 h-14 rounded-xl bg-gradient-to-br from-amber-500 to-orange-500 flex items-center justify-center shadow-lg">
                <i class="fas fa-sitemap text-white text-xl"></i>
            </div>
            <div>
                <p class="text-sm text-gray-500 font-medium">Subcategories</p>
                <p class="text-2xl font-bold text-gray-800"><?php echo count(array_filter($categories, function($cat) { return $cat['parent_id'] !== null; })); ?></p>
            </div>
        </div>
    </div>
</div>

<!-- Alerts -->
<?php if ($message): ?>
    <div class="alert-custom alert-success-custom mb-6" role="alert">
        <span class="alert-icon">
            <i class="fas fa-check text-sm"></i>
        </span>
        <span><?php echo htmlspecialchars($message); ?></span>
    </div>
<?php endif; ?>

<?php if ($error): ?>
    <div class="alert-custom alert-danger-custom mb-6" role="alert">
        <span class="alert-icon">
            <i class="fas fa-exclamation-triangle text-sm"></i>
        </span>
        <span><?php echo htmlspecialchars($error); ?></span>
    </div>
<?php endif; ?>

<!-- Categories Table -->
<div class="table-container bg-white mb-6">
    <div class="table-header px-6 py-4 border-b border-gray-200">
        <h2 class="text-lg font-semibold text-gray-800 flex items-center gap-2">
            <i class="fas fa-list text-blue-600"></i>
            All Categories
        </h2>
    </div>
    
    <?php if (empty($categories)): ?>
        <div class="empty-state">
            <div class="empty-state-icon">
                <i class="fas fa-folder-open"></i>
            </div>
            <h3 class="text-xl font-semibold text-gray-800 mb-2">No Categories Yet</h3>
            <p class="text-gray-500 mb-4">Get started by creating your first course category to organize your courses better.</p>
            <button class="btn-primary-custom" data-bs-toggle="modal" data-bs-target="#createCategoryModal">
                <i class="fas fa-plus mr-2"></i>
                Create First Category
            </button>
        </div>
    <?php else: ?>
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead>
                    <tr class="bg-gray-50 text-left text-sm font-semibold text-gray-600">
                        <th class="px-6 py-4">Category</th>
                        <th class="px-6 py-4">Slug</th>
                        <th class="px-6 py-4">Parent</th>
                        <th class="px-6 py-4">Icon</th>
                        <th class="px-6 py-4">Status</th>
                        <th class="px-6 py-4 text-right">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    <?php foreach ($categories as $category): ?>
                        <tr class="table-row">
                            <td class="px-6 py-4">
                                <div class="flex items-center gap-3">
                                    <?php if ($category['color']): ?>
                                        <div class="category-icon-wrapper" style="background-color: <?php echo htmlspecialchars($category['color']); ?>20; color: <?php echo htmlspecialchars($category['color']); ?>">
                                            <i class="<?php echo htmlspecialchars($category['icon'] ?: 'fas fa-tag'); ?>"></i>
                                        </div>
                                    <?php else: ?>
                                        <div class="category-icon-wrapper bg-gray-100 text-gray-600">
                                            <i class="fas fa-tag"></i>
                                        </div>
                                    <?php endif; ?>
                                    <div>
                                        <p class="font-semibold text-gray-800"><?php echo htmlspecialchars($category['name']); ?></p>
                                        <?php if ($category['description']): ?>
                                            <p class="text-sm text-gray-500"><?php echo htmlspecialchars(substr($category['description'], 0, 40)) . (strlen($category['description']) > 40 ? '...' : ''); ?></p>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </td>
                            <td class="px-6 py-4">
                                <code class="text-sm bg-gray-100 text-gray-600 px-2 py-1 rounded"><?php echo htmlspecialchars($category['slug']); ?></code>
                            </td>
                            <td class="px-6 py-4">
                                <?php if ($category['parent_name']): ?>
                                    <span class="inline-flex items-center gap-1 text-sm text-purple-600 font-medium">
                                        <i class="fas fa-level-up-alt"></i>
                                        <?php echo htmlspecialchars($category['parent_name']); ?>
                                    </span>
                                <?php else: ?>
                                    <span class="text-sm text-gray-400 italic">Top Level</span>
                                <?php endif; ?>
                            </td>
                            <td class="px-6 py-4">
                                <?php if ($category['icon']): ?>
                                    <span class="inline-flex items-center gap-2 text-sm">
                                        <i class="<?php echo htmlspecialchars($category['icon']); ?> text-gray-500"></i>
                                        <code class="text-xs bg-gray-100 text-gray-500 px-1.5 py-0.5 rounded"><?php echo htmlspecialchars($category['icon']); ?></code>
                                    </span>
                                <?php else: ?>
                                    <span class="text-sm text-gray-400 italic">Default</span>
                                <?php endif; ?>
                            </td>
                            <td class="px-6 py-4">
                                <span class="category-badge <?php echo $category['is_active'] ? 'badge-active' : 'badge-inactive'; ?>">
                                    <i class="fas fa-<?php echo $category['is_active'] ? 'check' : 'pause'; ?> mr-1"></i>
                                    <?php echo $category['is_active'] ? 'Active' : 'Inactive'; ?>
                                </span>
                            </td>
                            <td class="px-6 py-4 text-right">
                                <div class="flex items-center justify-end gap-2">
                                    <button class="btn-action btn-edit" onclick="editCategory(<?php echo $category['id']; ?>)">
                                        <i class="fas fa-edit"></i>
                                        Edit
                                    </button>
                                    <button class="btn-action btn-delete" onclick="deleteCategory(<?php echo $category['id']; ?>, '<?php echo htmlspecialchars($category['name']); ?>')">
                                        <i class="fas fa-trash-alt"></i>
                                        Delete
                                    </button>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

<!-- Create Category Modal -->
<div class="modal fade" id="createCategoryModal" tabindex="-1" aria-labelledby="createCategoryModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content rounded-xl shadow-2xl border-0">
            <div class="modal-header-custom rounded-t-xl">
                <h5 class="modal-title text-lg font-semibold text-gray-800 flex items-center gap-2" id="createCategoryModalLabel">
                    <i class="fas fa-folder-plus text-blue-600"></i>
                    Create New Category
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST">
                <div class="modal-body p-6">
                    <input type="hidden" name="action" value="create">
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                        <!-- Name -->
                        <div>
                            <label for="createName" class="form-label-custom flex items-center gap-2">
                                <i class="fas fa-tag text-blue-500"></i>
                                Name <span class="text-red-500">*</span>
                            </label>
                            <input type="text" class="form-input-custom w-full" id="createName" name="name" required placeholder="e.g., Web Development">
                        </div>
                        
                        <!-- Slug -->
                        <div>
                            <label for="createSlug" class="form-label-custom flex items-center gap-2">
                                <i class="fas fa-link text-blue-500"></i>
                                Slug <span class="text-red-500">*</span>
                            </label>
                            <input type="text" class="form-input-custom w-full" id="createSlug" name="slug" required placeholder="e.g., web-development">
                            <p class="text-xs text-gray-500 mt-1">URL-friendly version of the name</p>
                        </div>
                        
                        <!-- Description -->
                        <div class="md:col-span-2">
                            <label for="createDescription" class="form-label-custom flex items-center gap-2">
                                <i class="fas fa-align-left text-blue-500"></i>
                                Description
                            </label>
                            <textarea class="form-input-custom w-full" id="createDescription" name="description" rows="3" placeholder="Enter a brief description..."></textarea>
                        </div>
                        
                        <!-- Icon -->
                        <div>
                            <label for="createIcon" class="form-label-custom flex items-center gap-2">
                                <i class="fas fa-icons text-blue-500"></i>
                                Icon (FontAwesome)
                            </label>
                            <input type="text" class="form-input-custom w-full" id="createIcon" name="icon" placeholder="fas fa-code">
                            <p class="text-xs text-gray-500 mt-1">Use FontAwesome class (e.g., fas fa-laptop)</p>
                        </div>
                        
                        <!-- Color -->
                        <div>
                            <label for="createColor" class="form-label-custom flex items-center gap-2">
                                <i class="fas fa-palette text-blue-500"></i>
                                Color
                            </label>
                            <div class="color-input-wrapper">
                                <input type="color" class="form-control" id="createColor" name="color" value="#3B82F6">
                            </div>
                        </div>
                        
                        <!-- Parent Category -->
                        <div>
                            <label for="createParent" class="form-label-custom flex items-center gap-2">
                                <i class="fas fa-sitemap text-blue-500"></i>
                                Parent Category
                            </label>
                            <select class="form-select-custom w-full" id="createParent" name="parent_id">
                                <option value="">None (Top Level)</option>
                                <?php foreach ($parentCategories as $parent): ?>
                                    <option value="<?php echo $parent['id']; ?>"><?php echo htmlspecialchars($parent['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <!-- Active Status -->
                        <div class="flex items-center">
                            <label class="flex items-center gap-3 cursor-pointer">
                                <input type="checkbox" class="checkbox-custom" id="createActive" name="is_active" checked>
                                <span class="form-label-custom mb-0 flex items-center gap-2">
                                    <i class="fas fa-toggle-on text-green-500"></i>
                                    Active
                                </span>
                            </label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer-custom rounded-b-xl flex justify-end gap-3">
                    <button type="button" class="px-5 py-2.5 bg-gray-100 text-gray-700 rounded-lg font-medium hover:bg-gray-200 transition-colors" data-bs-dismiss="modal">
                        <i class="fas fa-times mr-2"></i>
                        Cancel
                    </button>
                    <button type="submit" class="btn-primary-custom">
                        <i class="fas fa-plus mr-2"></i>
                        Create Category
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Category Modal -->
<div class="modal fade" id="editCategoryModal" tabindex="-1" aria-labelledby="editCategoryModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content rounded-xl shadow-2xl border-0">
            <div class="modal-header-custom rounded-t-xl">
                <h5 class="modal-title text-lg font-semibold text-gray-800 flex items-center gap-2" id="editCategoryModalLabel">
                    <i class="fas fa-edit text-amber-500"></i>
                    Edit Category
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST">
                <div class="modal-body p-6">
                    <input type="hidden" name="action" value="update">
                    <input type="hidden" name="id" id="editId">
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                        <!-- Name -->
                        <div>
                            <label for="editName" class="form-label-custom flex items-center gap-2">
                                <i class="fas fa-tag text-blue-500"></i>
                                Name <span class="text-red-500">*</span>
                            </label>
                            <input type="text" class="form-input-custom w-full" id="editName" name="name" required>
                        </div>
                        
                        <!-- Slug -->
                        <div>
                            <label for="editSlug" class="form-label-custom flex items-center gap-2">
                                <i class="fas fa-link text-blue-500"></i>
                                Slug <span class="text-red-500">*</span>
                            </label>
                            <input type="text" class="form-input-custom w-full" id="editSlug" name="slug" required>
                            <p class="text-xs text-gray-500 mt-1">URL-friendly version of the name</p>
                        </div>
                        
                        <!-- Description -->
                        <div class="md:col-span-2">
                            <label for="editDescription" class="form-label-custom flex items-center gap-2">
                                <i class="fas fa-align-left text-blue-500"></i>
                                Description
                            </label>
                            <textarea class="form-input-custom w-full" id="editDescription" name="description" rows="3"></textarea>
                        </div>
                        
                        <!-- Icon -->
                        <div>
                            <label for="editIcon" class="form-label-custom flex items-center gap-2">
                                <i class="fas fa-icons text-blue-500"></i>
                                Icon (FontAwesome)
                            </label>
                            <input type="text" class="form-input-custom w-full" id="editIcon" name="icon" placeholder="fas fa-code">
                        </div>
                        
                        <!-- Color -->
                        <div>
                            <label for="editColor" class="form-label-custom flex items-center gap-2">
                                <i class="fas fa-palette text-blue-500"></i>
                                Color
                            </label>
                            <div class="color-input-wrapper">
                                <input type="color" class="form-control" id="editColor" name="color">
                            </div>
                        </div>
                        
                        <!-- Parent Category -->
                        <div>
                            <label for="editParent" class="form-label-custom flex items-center gap-2">
                                <i class="fas fa-sitemap text-blue-500"></i>
                                Parent Category
                            </label>
                            <select class="form-select-custom w-full" id="editParent" name="parent_id">
                                <option value="">None (Top Level)</option>
                                <?php foreach ($parentCategories as $parent): ?>
                                    <option value="<?php echo $parent['id']; ?>"><?php echo htmlspecialchars($parent['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <!-- Active Status -->
                        <div class="flex items-center">
                            <label class="flex items-center gap-3 cursor-pointer">
                                <input type="checkbox" class="checkbox-custom" id="editActive" name="is_active">
                                <span class="form-label-custom mb-0 flex items-center gap-2">
                                    <i class="fas fa-toggle-on text-green-500"></i>
                                    Active
                                </span>
                            </label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer-custom rounded-b-xl flex justify-end gap-3">
                    <button type="button" class="px-5 py-2.5 bg-gray-100 text-gray-700 rounded-lg font-medium hover:bg-gray-200 transition-colors" data-bs-dismiss="modal">
                        <i class="fas fa-times mr-2"></i>
                        Cancel
                    </button>
                    <button type="submit" class="btn-primary-custom">
                        <i class="fas fa-save mr-2"></i>
                        Update Category
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Category Modal -->
<div class="modal fade" id="deleteCategoryModal" tabindex="-1" aria-labelledby="deleteCategoryModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content rounded-xl shadow-2xl border-0">
            <div class="modal-header-custom rounded-t-xl">
                <h5 class="modal-title text-lg font-semibold text-gray-800 flex items-center gap-2" id="deleteCategoryModalLabel">
                    <i class="fas fa-exclamation-triangle text-red-500"></i>
                    Delete Category
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST">
                <div class="modal-body p-6 text-center">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id" id="deleteId">
                    
                    <div class="mb-4">
                        <div class="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
                            <i class="fas fa-trash-alt text-red-500 text-2xl"></i>
                        </div>
                        <p class="text-gray-700">Are you sure you want to delete the category:</p>
                        <p class="font-semibold text-lg text-gray-900 mt-2" id="deleteName"></p>
                    </div>
                    
                    <div class="bg-red-50 border border-red-200 rounded-lg p-4 text-left">
                        <div class="flex items-start gap-3">
                            <i class="fas fa-exclamation-circle text-red-500 mt-0.5"></i>
                            <div>
                                <p class="text-sm font-medium text-red-800">Warning</p>
                                <p class="text-sm text-red-600 mt-1">This action cannot be undone. Make sure the category has no associated courses.</p>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer-custom rounded-b-xl flex justify-end gap-3">
                    <button type="button" class="px-5 py-2.5 bg-gray-100 text-gray-700 rounded-lg font-medium hover:bg-gray-200 transition-colors" data-bs-dismiss="modal">
                        <i class="fas fa-times mr-2"></i>
                        Cancel
                    </button>
                    <button type="submit" class="px-5 py-2.5 bg-red-500 text-white rounded-lg font-medium hover:bg-red-600 transition-colors shadow-lg shadow-red-500/30">
                        <i class="fas fa-trash-alt mr-2"></i>
                        Delete
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    window.editCategory = function(id) {
        console.log('editCategory called with id:', id);
        
        var editModalEl = document.getElementById('editCategoryModal');
        var editIdEl = document.getElementById('editId');
        
        console.log('Modal element:', editModalEl);
        console.log('ID element:', editIdEl);
        
        if (!editModalEl) {
            alert('Error: Modal not found');
            return;
        }
        if (!editIdEl) {
            alert('Error: Hidden ID field not found');
            return;
        }
        
        var apiUrl = 'api/course_categories.php?id=' + encodeURIComponent(id);
        console.log('Fetching:', apiUrl);
        
        fetch(apiUrl, {
            credentials: 'same-origin'
        })
        .then(function(response) {
            console.log('Response status:', response.status);
            console.log('Response ok:', response.ok);
            if (!response.ok) {
                return response.text().then(function(text) {
                    throw new Error('HTTP ' + response.status + ': ' + text);
                });
            }
            return response.json();
        })
        .then(function(data) {
            console.log('Response data:', data);
            if (data.success) {
                var category = data.category;
                editIdEl.value = category.id;
                document.getElementById('editName').value = category.name || '';
                document.getElementById('editSlug').value = category.slug || '';
                document.getElementById('editDescription').value = category.description || '';
                document.getElementById('editIcon').value = category.icon || '';
                document.getElementById('editColor').value = category.color || '#3B82F6';
                document.getElementById('editParent').value = category.parent_id || '';
                document.getElementById('editActive').checked = category.is_active == 1;

                console.log('Showing modal...');
                var editModal = new bootstrap.Modal(editModalEl);
                editModal.show();
                console.log('Modal should be shown now');
            } else {
                alert('Error: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(function(error) {
            console.error('Fetch error:', error);
            alert('Failed to load category: ' + error.message);
        });
    };

    window.deleteCategory = function(id, name) {
        document.getElementById('deleteId').value = id;
        document.getElementById('deleteName').textContent = name;
        var deleteModalEl = document.getElementById('deleteCategoryModal');
        if (deleteModalEl) {
            var deleteModal = new bootstrap.Modal(deleteModalEl);
            deleteModal.show();
        }
    };

    // Auto-generate slug from name for create form
    var createNameInput = document.getElementById('createName');
    var createSlugInput = document.getElementById('createSlug');
    if (createNameInput && createSlugInput) {
        createNameInput.addEventListener('input', function() {
            var name = this.value;
            var slug = name.toLowerCase()
                .replace(/[^a-z0-9\s-]/g, '')
                .replace(/\s+/g, '-')
                .replace(/-+/g, '-')
                .trim('-');
            createSlugInput.value = slug;
        });
    }

    // Auto-generate slug from name for edit form
    var editNameInput = document.getElementById('editName');
    var editSlugInput = document.getElementById('editSlug');
    if (editNameInput && editSlugInput) {
        editNameInput.addEventListener('input', function() {
            var name = this.value;
            var slug = name.toLowerCase()
                .replace(/[^a-z0-9\s-]/g, '')
                .replace(/\s+/g, '-')
                .replace(/-+/g, '-')
                .trim('-');
            editSlugInput.value = slug;
        });
    }
});
</script>

<?php include 'includes/admin_footer.php'; ?>
