<?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 Management';
include 'includes/admin_header.php';
?>

<div class="course-categories-page">
    <div class="admin-content">
        <div class="course-categories-header">
            <h1>Course Categories</h1>
            <p>Manage and organize your course categories with ease</p>
        </div>

        <!-- Category Stats -->
        <div class="category-stats">
            <div class="category-stat-card">
                <div class="stat-icon">
                    <i class="fas fa-tags"></i>
                </div>
                <div class="stat-content">
                    <div class="stat-number"><?php echo count($categories); ?></div>
                    <div class="stat-label">Total Categories</div>
                </div>
            </div>
            <div class="category-stat-card">
                <div class="stat-icon active">
                    <i class="fas fa-check-circle"></i>
                </div>
                <div class="stat-content">
                    <div class="stat-number"><?php echo count(array_filter($categories, function($cat) { return $cat['is_active']; })); ?></div>
                    <div class="stat-label">Active Categories</div>
                </div>
            </div>
            <div class="category-stat-card">
                <div class="stat-icon primary">
                    <i class="fas fa-folder"></i>
                </div>
                <div class="stat-content">
                    <div class="stat-number"><?php echo count(array_filter($categories, function($cat) { return $cat['parent_id'] === null; })); ?></div>
                    <div class="stat-label">Top Level Categories</div>
                </div>
            </div>
            <div class="category-stat-card">
                <div class="stat-icon secondary">
                    <i class="fas fa-folder-tree"></i>
                </div>
                <div class="stat-content">
                    <div class="stat-number"><?php echo count(array_filter($categories, function($cat) { return $cat['parent_id'] !== null; })); ?></div>
                    <div class="stat-label">Subcategories</div>
                </div>
            </div>
        </div>

        <div class="d-flex justify-content-between align-items-center mb-4">
            <div></div>
            <button class="btn btn-primary add-category-btn" data-bs-toggle="modal" data-bs-target="#createCategoryModal">
                <i class="fas fa-plus"></i> Add New Category
            </button>
        </div>

            <?php if ($message): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <?php echo htmlspecialchars($message); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <?php if ($error): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <?php echo htmlspecialchars($error); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

        <div class="categories-table-container">
            <table class="categories-table">
                <thead>
                    <tr>
                        <th>Category</th>
                        <th>Slug</th>
                        <th>Parent</th>
                        <th>Icon</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($categories)): ?>
                        <tr>
                            <td colspan="6">
                                <div class="empty-state">
                                    <div class="empty-state-icon">
                                        <i class="fas fa-tags"></i>
                                    </div>
                                    <h3>No Categories Yet</h3>
                                    <p>Get started by creating your first course category to organize your courses better.</p>
                                </div>
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($categories as $category): ?>
                            <tr>
                                <td>
                                    <div class="category-name">
                                        <?php if ($category['color']): ?>
                                            <div class="category-icon" style="background-color: <?php echo htmlspecialchars($category['color']); ?>">
                                                <i class="<?php echo htmlspecialchars($category['icon'] ?: 'fas fa-tag'); ?>"></i>
                                            </div>
                                        <?php endif; ?>
                                        <div>
                                            <strong><?php echo htmlspecialchars($category['name']); ?></strong>
                                            <?php if ($category['description']): ?>
                                                <div class="category-description"><?php echo htmlspecialchars(substr($category['description'], 0, 50)) . (strlen($category['description']) > 50 ? '...' : ''); ?></div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <span class="category-slug"><?php echo htmlspecialchars($category['slug']); ?></span>
                                </td>
                                <td>
                                    <?php if ($category['parent_name']): ?>
                                        <span class="category-parent"><?php echo htmlspecialchars($category['parent_name']); ?></span>
                                    <?php else: ?>
                                        <em class="text-muted">Top Level</em>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if ($category['icon']): ?>
                                        <code><?php echo htmlspecialchars($category['icon']); ?></code>
                                    <?php else: ?>
                                        <em class="text-muted">Default</em>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="category-status <?php echo $category['is_active'] ? 'active' : 'inactive'; ?>">
                                        <i class="fas fa-<?php echo $category['is_active'] ? 'check-circle' : 'pause-circle'; ?>"></i>
                                        <?php echo $category['is_active'] ? 'Active' : 'Inactive'; ?>
                                    </span>
                                </td>
                                <td>
                                    <div class="category-actions">
                                        <button class="category-action-btn edit" onclick="editCategory(<?php echo $category['id']; ?>)">
                                            <i class="fas fa-edit"></i> Edit
                                        </button>
                                        <button class="category-action-btn delete" onclick="deleteCategory(<?php echo $category['id']; ?>, '<?php echo htmlspecialchars($category['name']); ?>')">
                                            <i class="fas fa-trash"></i> Delete
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Create Category Modal -->
<div class="modal fade" id="createCategoryModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Create Category</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="create">
                    <div class="mb-3">
                        <label for="createName" class="form-label">Name *</label>
                        <input type="text" class="form-control" id="createName" name="name" required>
                    </div>
                    <div class="mb-3">
                        <label for="createSlug" class="form-label">Slug *</label>
                        <input type="text" class="form-control" id="createSlug" name="slug" required>
                        <div class="form-text">URL-friendly version of the name</div>
                    </div>
                    <div class="mb-3">
                        <label for="createDescription" class="form-label">Description</label>
                        <textarea class="form-control" id="createDescription" name="description" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="createIcon" class="form-label">Icon (FontAwesome class)</label>
                        <input type="text" class="form-control" id="createIcon" name="icon" placeholder="fas fa-code">
                    </div>
                    <div class="mb-3">
                        <label for="createColor" class="form-label">Color</label>
                        <input type="color" class="form-control" id="createColor" name="color" value="#007bff">
                    </div>
                    <div class="mb-3">
                        <label for="createParent" class="form-label">Parent Category</label>
                        <select class="form-select" 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>
                    <div class="mb-3 form-check">
                        <input type="checkbox" class="form-check-input" id="createActive" name="is_active" checked>
                        <label class="form-check-label" for="createActive">Active</label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Create Category</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Category Modal -->
<div class="modal fade" id="editCategoryModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Category</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="update">
                    <input type="hidden" name="id" id="editId">
                    <div class="mb-3">
                        <label for="editName" class="form-label">Name *</label>
                        <input type="text" class="form-control" id="editName" name="name" required>
                    </div>
                    <div class="mb-3">
                        <label for="editSlug" class="form-label">Slug *</label>
                        <input type="text" class="form-control" id="editSlug" name="slug" required>
                        <div class="form-text">URL-friendly version of the name</div>
                    </div>
                    <div class="mb-3">
                        <label for="editDescription" class="form-label">Description</label>
                        <textarea class="form-control" id="editDescription" name="description" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="editIcon" class="form-label">Icon (FontAwesome class)</label>
                        <input type="text" class="form-control" id="editIcon" name="icon" placeholder="fas fa-code">
                    </div>
                    <div class="mb-3">
                        <label for="editColor" class="form-label">Color</label>
                        <input type="color" class="form-control" id="editColor" name="color">
                    </div>
                    <div class="mb-3">
                        <label for="editParent" class="form-label">Parent Category</label>
                        <select class="form-select" 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>
                    <div class="mb-3 form-check">
                        <input type="checkbox" class="form-check-input" id="editActive" name="is_active">
                        <label class="form-check-label" for="editActive">Active</label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update Category</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Category Modal -->
<div class="modal fade" id="deleteCategoryModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Delete Category</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id" id="deleteId">
                    <p>Are you sure you want to delete the category "<span id="deleteName"></span>"?</p>
                    <div class="alert alert-warning">
                        <strong>Warning:</strong> This action cannot be undone. Make sure the category has no associated courses.
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Delete Category</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function editCategory(id) {
    // Fetch category data and populate edit modal
    fetch(`../api/course_categories.php?id=${id}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const category = data.category;
                document.getElementById('editId').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 || '#007bff';
                document.getElementById('editParent').value = category.parent_id || '';
                document.getElementById('editActive').checked = category.is_active == 1;

                new bootstrap.Modal(document.getElementById('editCategoryModal')).show();
            }
        })
        .catch(error => console.error('Error:', error));
}

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

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

document.getElementById('editName').addEventListener('input', function() {
    const name = this.value;
    const slug = name.toLowerCase()
        .replace(/[^a-z0-9\s-]/g, '')
        .replace(/\s+/g, '-')
        .replace(/-+/g, '-')
        .trim('-');
    document.getElementById('editSlug').value = slug;
});
</script>

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