<?php

class Request {
	private $type = "";
	private $headers = [];
	private $referer = "";
	private $get = [];
	private $post = [];
	private $put = [];
	private $peer = "";
	private $path = "";
	private $route = null;
	private $files = [];

	public function __construct() {
		$this->get = $_GET;
		$this->post = $_POST;
		$this->files = $_FILES;
		$this->type = strtoupper($_SERVER['REQUEST_METHOD']);
		$this->peer = $_SERVER['REMOTE_ADDR'];
		if (array_key_exists("REDIRECT_URL", $_SERVER)) {
			$this->path = $_SERVER['REDIRECT_URL'];
		} else {
			$this->path = "/";
		}

		if ($this->type == "PUT") {
			$data = file_get_contents("php://input");
			$arr = [];
			parse_str($data, $arr);
			foreach ($arr as $k=>$v) {
				$this->put[$k] = $v;
			}
		}

		foreach ($_SERVER as $k=>$v) {
			if (str_starts_with($k, "HTTP_")) {
				$header = substr($k, 5);
				$header = strtolower($header);
				$header = str_replace("_", " ", $header);
				$header = ucwords($header);
				$header = str_replace(" ", "-", $header);
				$this->headers[$header] = $v;
			}
		}

		if (array_key_exists("HTTP_REFERER", $_SERVER)) {
			$this->referer = $_SERVER['HTTP_REFERER'];
		} else {
			$this->referer = "";
		}
	}

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

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

	public function header($h) {
		if (array_key_exists($h, $this->headers)) {
			return $this->headers[$h];
		}
		return false;
	}

	public function file($name, $num = false) {
		if ($num === false) {
			return $this->files[$name];
		}
		if ($num >= count($this->files[$name]["name"])) {
			return false;
		}
		return [
			"name" => $this->files[$name]["name"][$num],
			"full_path" => $this->files[$name]["full_path"][$num],
			"type" => $this->files[$name]["type"][$num],
			"tmp_name" => $this->files[$name]["tmp_name"][$num],
			"error" => $this->files[$name]["error"][$num],
			"size" => $this->files[$name]["size"][$num],
		];
	}

	public function get($k) {
		if (!array_key_exists($k, $this->get)) return false;
		return $this->get[$k];
	}

	public function post($k) {
		if (!array_key_exists($k, $this->post)) return false;
		return $this->post[$k];
	}

	public function put($k) {
		if (!array_key_exists($k, $this->put)) return false;
		return $this->put[$k];
	}

	public function set_route($r) {
		$this->route = $r;
	}

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

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