<?php
declare(strict_types=1);

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

function get_json_input(): array
{
    $input = json_decode(file_get_contents('php://input'), true);

    if (!is_array($input)) {
        json_response(400, [
            'success' => false,
            'message' => 'Format request tidak valid.',
        ]);
    }

    return $input;
}

function sanitize_wkt(string $wkt, string $expectedType): string
{
    $trimmed = trim($wkt);

    if ($trimmed === '') {
        json_response(422, [
            'success' => false,
            'message' => 'Geometri WKT wajib diisi.',
        ]);
    }

    $normalized = strtoupper($trimmed);

    if (strpos($normalized, $expectedType . '(') !== 0 && strpos($normalized, $expectedType . ' (') !== 0) {
        json_response(422, [
            'success' => false,
            'message' => 'Tipe geometri tidak sesuai. Diharapkan ' . $expectedType . '.',
        ]);
    }

    return $trimmed;
}
