<?php

namespace App\Util;

class Url
{
    private $scheme;
    private $user;
    private $pass;
    private $host;
    private $port;
    private $path;
    private $query = [];
    private $fragment;

    public function __construct($url = '')
    {
        if (!empty($url)) {
            $parts = parse_url($url);

            $this->scheme = $parts['scheme'] ?? null;
            $this->user = $parts['user'] ?? null;
            $this->pass = $parts['pass'] ?? null;
            $this->host = $parts['host'] ?? null;
            $this->port = $parts['port'] ?? null;
            $this->path = $parts['path'] ?? null;
            parse_str($parts['query'] ?? '', $this->query);
            $this->fragment = $parts['fragment'] ?? null;
        }
    }

    public static function extractUrl(){
        $url = trim($_GET['url'], '/');
        $url = filter_var($url, FILTER_SANITIZE_URL);
        $url = explode('/', $url);
        return $url;
    }

    public function setScheme($scheme)
    {
        $this->scheme = $scheme;
        return $this;
    }

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

    public function setUser($user)
    {
        $this->user = $user;
        return $this;
    }

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

    // ... repeat for other properties

    public function setQueryParameter($name, $value)
    {
        $this->query[$name] = $value;
        return $this;
    }

    public function getQueryParameter($name)
    {
        return $this->query[$name] ?? null;
    }

    public function isEqual($anotherUrl)
    {
        return (string)$this == (string)$anotherUrl;
    }

    public function __toString()
    {
        $url = $this->scheme . '://';

        if ($this->user) {
            $url .= $this->user;
            if ($this->pass) {
                $url .= ':' . $this->pass;
            }
            $url .= '@';
        }

        $url .= $this->host;

        if ($this->port) {
            $url .= ':' . $this->port;
        }

        $url .= $this->path;

        if ($this->query) {
            $url .= '?' . http_build_query($this->query);
        }

        if ($this->fragment) {
            $url .= '#' . $this->fragment;
        }

        return $url;
    }
}
