<?php

declare(strict_types=1);

namespace App\Core;

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

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

        $uri = rawurldecode(
            (string) $uri
        );

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

        return $uri === '//'
            ? '/'
            : $uri;
    }

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

    public static function string(
        string $key,
        string $default = ''
    ): string {
        return trim(
            (string) self::input(
                $key,
                $default
            )
        );
    }

    public static function integer(
        string $key,
        ?int $default = null
    ): ?int {
        $value = self::input($key);

        if (
            $value === null ||
            $value === ''
        ) {
            return $default;
        }

        $filtered = filter_var(
            $value,
            FILTER_VALIDATE_INT
        );

        return $filtered === false
            ? $default
            : (int) $filtered;
    }

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

    public static function isPost(): bool
    {
        return self::method() === 'POST';
    }

    public static function ip(): string
    {
        return $_SERVER['REMOTE_ADDR']
            ?? '0.0.0.0';
    }

    public static function userAgent(): string
    {
        return $_SERVER['HTTP_USER_AGENT']
            ?? '';
    }
}