<?php

namespace App\Util;

class HTTPRequest
{
    private $url;
    private $query = [];
    private $post = [];
    private $files = [];
    private $headers = [];
    private $method;
    private $isSecured = false;

    public function __construct() {
        $this->method = $_SERVER['REQUEST_METHOD'];
        $this->isSecured = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on';
        $this->query = $_GET;
        $this->post = $_POST;
        $this->files = $_FILES;
        $this->headers = getallheaders();
    }

    public function withUrl($newUrl) {
        $newRequest = clone $this;
        $newRequest->url = $newUrl;
        return $newRequest;
    }

    public function getUrl() {
        return $this->url;
    }

    public function getQuery($key = null) {
        if ($key === null) {
            return $this->query;
        }
        return $this->query[$key] ?? null;
    }

    public function getPost($key = null) {
        if ($key === null) {
            return $this->post;
        }
        return $this->post[$key] ?? null;
    }

    public static function getJsonPost() {
        return json_decode(file_get_contents('php://input'), true);
    }

    public function getFile($key) {
        return $this->files[$key] ?? null;
    }

    public function getFiles() {
        return $this->files;
    }

    public function getMethod() {
        return $this->method;
    }

    public function isMethod($method) {
        return strtolower($this->method) === strtolower($method);
    }

    public function getHeader($header) {
        return $this->headers[$header] ?? null;
    }

    public function getHeaders() {
        return $this->headers;
    }

    public function isSecured() {
        return $this->isSecured;
    }
}
