<?php
/*
    =========================================
        Router
    =========================================
*/

require('Route.php');

class Router
{
  private $url;
  private $routes = [];
  private $pages;
  private $server_method;

  function __construct($url)
  {
    $this->url = $url;
    $this->server_method = $_SERVER['REQUEST_METHOD'];
  }

  private function add($path, $name, $method = 'GET')
  {
    $route = new Route($path, $name);
    $this->routes[$method][] = $route;

    return $route;
  }

  public function run()
  {
    $this->process_routes();

    foreach ($this->routes['GET'] as $route)
    // foreach ($this->routes[$this->server_method] as $route)
      if ($route->match($this->url))
        return $route->call_view();

    $this->error_404();
  }

  private function process_routes()
  {
    $routes_config = new SiteConfig();
    $this->pages = $routes_config->routes();

    foreach ($this->pages as $page)
    {
      $temp = $this->add(
        $page['url'],
        $page['name']
      );

      if ( isset($page['regex']) )
        foreach ($page['regex'] as $k_regex => $v_regex)
          $temp->add_param($k_regex, $v_regex);
    }
  }

  private function error_404 ()
  {
    include TPL . '404' . '.php';
  }

}
