<?php

declare(strict_types=1);

function json_response(array $payload, int $statusCode = 200): void
{
    http_response_code($statusCode);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($payload, JSON_UNESCAPED_SLASHES);
    exit;
}

function ok(array $data = []): void
{
    json_response(['success' => true, 'data' => $data], 200);
}

function fail(string $message, int $statusCode = 400, array $details = []): void
{
    $payload = ['success' => false, 'error' => $message];
    if (!empty($details)) {
        $payload['details'] = $details;
    }
    json_response($payload, $statusCode);
}

function require_method(string $method): void
{
    if (strtoupper($_SERVER['REQUEST_METHOD'] ?? '') !== strtoupper($method)) {
        fail('Method not allowed', 405);
    }
}

function read_json_body(): array
{
    $raw = file_get_contents('php://input');
    if ($raw === false || trim($raw) === '') {
        return [];
    }

    $decoded = json_decode($raw, true);
    if (!is_array($decoded)) {
        fail('Invalid JSON body', 400);
    }

    return $decoded;
}
