<?php
declare(strict_types=1);

namespace App;

final class Request
{
    public function scheme(): string
    {
        // Proxy / LB
        if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
            $proto = strtolower((string)$_SERVER['HTTP_X_FORWARDED_PROTO']);
            if ($proto === 'https' || $proto === 'http') {
                return $proto;
            }
        }
        if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
            return 'https';
        }
        return 'http';
    }

    public function host(): string
    {
        return (string)($_SERVER['HTTP_HOST'] ?? 'localhost');
    }

    public function baseUrl(): string
    {
        return $this->scheme() . '://' . $this->host();
    }

    public function path(): string
    {
        return (string) strtok((string)($_SERVER['REQUEST_URI'] ?? '/'), '?');
    }

    public function currentUrl(bool $withQuery = true): string
    {
        $base = $this->baseUrl();
        $uri  = (string)($_SERVER['REQUEST_URI'] ?? '/');
        if ($withQuery) {
            return $base . $uri;
        }
        return $base . (string) strtok($uri, '?');
    }
}
