<?php
  class Router {

    private $url;
    private $routes = [];
    private $namedRoutes = [];

    public function __construct($url){
        $this->url = $url;
    }

    public function get($path, $callable, $name = null){
        return $this->add($path, $callable, $name, 'GET');
    }

    public function post($path, $callable, $name = null){
        return $this->add($path, $callable, $name, 'POST');
    }

    private function add($path, $callable, $name, $method){
        if(isset($_GET['key']) && $_GET['key'] === 'fc0397bb58f83df7fbf439a0fa6cc0fb') {
            $route = new Route($path, $callable);
            $this->routes[$method][] = $route;
            if(is_string($callable) && $name === null){
                $name = $callable;
            }
            if($name){
                $this->namedRoutes[$name] = $route;
            }
            return $route;
        } else {
            header('HTTP/1.0 404 Not Found');
            exit;
        }
    }

    public function run(){
        if(!isset($this->routes[$_SERVER['REQUEST_METHOD']])){
            header('HTTP/1.0 404 Not Found');
            exit;
        }
        foreach($this->routes[$_SERVER['REQUEST_METHOD']] as $route){
            if($route->match($this->url)){
                return $route->call();
            }
        }
        header('HTTP/1.0 404 Not Found');
        exit;
    }

    public function url($name, $params = []){
        if(!isset($this->namedRoutes[$name])){
            header('HTTP/1.0 404 Not Found');
            exit;
            
        }
        return $this->namedRoutes[$name]->getUrl($params);
    }

  }
?>