<?php
/*
    =========================================
        Route
    =========================================
*/

require_once( CONTROLLERS . 'Controller.php' );

class Route
{
  private $path;
  private $matches = [];
  private $params = [];

  function __construct($path, $name)
  {
    $this->path = trim($path, '/');
    $this->name = $name;
  }

  public function add_param($param, $regex)
  {
    $this->params[$param] = str_replace('(', '(?:', $regex);
    return $this;
  }

  public function match($url)
  {
    $url = trim($url, '/');
    $path = preg_replace_callback('#:([\w]+)#', [$this, 'param_match'], $this->path);

    $regex = "#^$path$#i";

    if (!preg_match($regex, $url, $matches)) return false;

    array_shift($matches);

    $this->matches = $matches;
    return true;
  }

  private function param_match ($match)
  {
    if (isset($this->params[$match[1]]))
      return '(' . $this->params[$match[1]] . ')';

    return '([^/]+)';
  }

  public function call_view()
  {
    $controller = new Controller( $this->name, $this->matches );
    $controller -> run();
  }

}
