<?php

declare(strict_types=1);

namespace System\Http;

final class Request
{
    public function method(): string
    {
        return strtoupper(
            $_SERVER['REQUEST_METHOD'] ?? 'GET'
        );
    }

    public function uri(): string
    {
        $uri = $_SERVER['REQUEST_URI'] ?? '/';

        $uri = strtok($uri, '?');

        $scriptName = $_SERVER['SCRIPT_NAME'] ?? '';

        $basePath = dirname($scriptName);

        if (
            $basePath !== '/'
            && $basePath !== '.'
            && str_starts_with($uri, $basePath)
        ) {
            $uri = substr(
                $uri,
                strlen($basePath)
            );
        }

        $uri = '/' . ltrim($uri, '/');

        return rtrim($uri, '/') ?: '/';
    }

    public function input(
        string $key,
        mixed $default = null
    ): mixed {
        return $_POST[$key]
            ?? $_GET[$key]
            ?? $default;
    }

    public function all(): array
    {
        return array_merge(
            $_GET,
            $_POST
        );
    }
}