<?php
require_once '../../includes/middleware.php';
require_once '../../config/database.php';

header('Content-Type: application/json');

$db = getDB();

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    case 'GET':
        if (isset($_GET['id'])) {
            // Get single category
            $stmt = $db->prepare("SELECT * FROM course_categories WHERE id = ?");
            $stmt->execute([$_GET['id']]);
            $category = $stmt->fetch();

            if ($category) {
                echo json_encode(['success' => true, 'category' => $category]);
            } else {
                echo json_encode(['success' => false, 'error' => 'Category not found']);
            }
        } else {
            // 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();

            echo json_encode(['success' => true, 'categories' => $categories]);
        }
        break;

    case 'POST':
        // Create category
        requirePermission('manage_course_categories');

        $data = json_decode(file_get_contents('php://input'), true);

        $name = trim($data['name']);
        $slug = trim($data['slug']);
        $description = trim($data['description'] ?? '');
        $icon = trim($data['icon'] ?? '');
        $color = trim($data['color'] ?? '#007bff');
        $parent_id = !empty($data['parent_id']) ? $data['parent_id'] : null;
        $is_active = isset($data['is_active']) ? 1 : 0;

        if (empty($name) || empty($slug)) {
            echo json_encode(['success' => false, 'error' => 'Name and slug are required']);
            exit;
        }

        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]);

            echo json_encode(['success' => true, 'id' => $db->lastInsertId()]);
        } catch (PDOException $e) {
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
        break;

    case 'PUT':
        // Update category
        requirePermission('manage_course_categories');

        $data = json_decode(file_get_contents('php://input'), true);
        $id = $data['id'];

        $name = trim($data['name']);
        $slug = trim($data['slug']);
        $description = trim($data['description'] ?? '');
        $icon = trim($data['icon'] ?? '');
        $color = trim($data['color'] ?? '#007bff');
        $parent_id = !empty($data['parent_id']) ? $data['parent_id'] : null;
        $is_active = isset($data['is_active']) ? 1 : 0;

        if (empty($name) || empty($slug)) {
            echo json_encode(['success' => false, 'error' => 'Name and slug are required']);
            exit;
        }

        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]);

            echo json_encode(['success' => true]);
        } catch (PDOException $e) {
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
        break;

    case 'DELETE':
        // Delete category
        requirePermission('manage_course_categories');

        $id = $_GET['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) {
                echo json_encode(['success' => false, 'error' => 'Cannot delete category with existing courses']);
                exit;
            }

            $stmt = $db->prepare("DELETE FROM course_categories WHERE id = ?");
            $stmt->execute([$id]);

            echo json_encode(['success' => true]);
        } catch (PDOException $e) {
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
        break;

    default:
        echo json_encode(['success' => false, 'error' => 'Method not allowed']);
        break;
}
?>