<?php
declare(strict_types=1);
require_once __DIR__ . '/../lib.php';

header('Content-Type: application/json');
hw_require_auth(['admin']);

$method = $_SERVER['REQUEST_METHOD'];
$pdo = hw_db();

try {
    if ($method === 'GET') {
        // Get all categories
        $stmt = $pdo->prepare('
            SELECT id, name, slug, description
            FROM content_categories
            WHERE is_active = TRUE
            ORDER BY sort_order ASC, name ASC
        ');
        $stmt->execute();
        $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo json_encode([
            'success' => true,
            'categories' => $categories
        ]);
    } 
    else if ($method === 'POST') {
        // Create category
        $input = json_decode(file_get_contents('php://input'), true);
        
        $name = $input['name'] ?? '';
        $slug = $input['slug'] ?? '';
        $description = $input['description'] ?? '';
        
        if (!$name || !$slug) {
            echo json_encode(['success' => false, 'error' => 'Name and slug are required']);
            exit;
        }
        
        $stmt = $pdo->prepare('
            INSERT INTO content_categories (name, slug, description, is_active)
            VALUES (?, ?, ?, TRUE)
        ');
        $stmt->execute([$name, $slug, $description]);
        
        echo json_encode(['success' => true, 'message' => 'Category created', 'id' => $pdo->lastInsertId()]);
    }
    else {
        http_response_code(405);
        echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
