<?php

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

require_once '../db/functions.php';
require_once '../db/categories/category.php';

$category = new Category($conn);

$method = $_SERVER['REQUEST_METHOD'];
$id = $_GET['id'] ?? null;
$input = json_decode(file_get_contents('php://input'), true);

switch ($method) {
    case 'GET':
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode($id ? $category->get($id) : $category->getAll());
        break;

    case 'POST':
        header('Content-Type: application/json; charset=utf-8');
        $newId = $category->create($input);
        echo json_encode(['id' => $newId]);
        break;

    case 'PUT':
        if ($id) {
            $category->update($id, $input);
            echo json_encode(['status' => 'updated']);
        }
        break;

    case 'DELETE':
        if ($id) {
            $category->delete($id);
            echo json_encode(['status' => 'deleted']);
        }
        break;

    default:
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
        break;
}