<?php

 	require_once 'app/core/routeconfig.php';
    require_once 'app/core/route.php';

    $route = new Route($routes);
    $route -> Run();
?>

<?php 

class Route{

    public $any = '([A-Za-z]+)';
    private $num = '([0-9]+)';
    public $controller;
    public $action;
    public $params = array();
    public $routes;
    
    
    public function __construct($routes) {
    	$this->routes = $routes;
    }

    function getUrl(){

        return rtrim($_SERVER['REQUEST_URI'], '/');

    }
    
    function getRoute(){
        $i = 0;

        foreach ($this->routes as $route){

            $pattern = $route['pattern'];
            $pattern = str_replace(':any', $this->any, $pattern);
            $pattern = str_replace(':num', $this->num, $pattern);

            //get uri
            $uri = $this->getUrl();

            if(preg_match('#^'.$pattern.'$#', $uri)){

                $this->controller = $route['path']['controller'];
                $this->action = $route['path']['action'];
                if(!empty($route[$i]['path']['params'])){
                    foreach ($route[$i]['path']['params'] as $param => $value) {

                        $params = array($param => $value);
                    }
                }

                break;

            } $i++;
        }
        return array($this->controller, $this->action);
    }

    public function Run(){
        $route = $this->getRoute();
        $controller = $route[0];
        $action_name = 'Action_'.$route[1];
        $controller_name = $this->connectionFile($controller);

        $controller = new $controller_name;
        $controller -> $action_name(); 
    }

    function connectionFile($controller){

        $this->controller = $controller;

        $controller_name = 'Controller_'.$controller;
        $controller_file = strtolower($controller_name).'.php';
        $model_name = 'Model_'.$controller;
        $model_file = strtolower($model_name).'.php';

        if(file_exists('app/controllers/'.$controller_file)){
            include 'app/controllers/'.$controller_file;
        }else{

        }

        if(file_exists('app/models/'.$model_file)){
            include 'app/models/'.$model_file;
        }

        return $controller_name;
	}
}