<?php
namespace NeurogenesisTheme\Core;

use NeurogenesisTheme\Traits\HasTemplate;

class Router {
    use HasTemplate;    
    /**
     * namespace
     *
     * @var string
     */
    private $namespace;  
    
    /**
     * route
     *
     * @var mixed
     */
    private $route = false;
    
    public function __construct($namespace)
    {
        $this->namespace = $namespace;
        
        $this->resolveRoute();
    }

    /**
     * Return the display callback
     *
     * @return array
     */
    public function display()
    {
        return $this->route;
    }
    
    /**
     * Try to get the corresponding route
     *
     * @return void
     */
    public function resolveRoute()
    {
        if (isset($_GET['page']) && $_GET['page'] == $this->namespace) {
            if (isset($_GET['route'])) {
                $this->route = $this->loadRoute($_GET['route']);                
            } else {
                $this->route = $this->loadRoute(false);
            }
        } else {
            $this->route = [$this, 'empty'];
        }
    }
    
    /**
     * Empty controller function
     *
     * @return void
     */
    public function empty() {}
    
    /**
     * No route was found
     *
     * @return void
     */
    public function notFound()
    {
        $this->template('_not_found', []);
    }
    
    /**
     * Load the corresponding route
     *
     * @param  mixed $route
     * @return array
     */
    public function loadRoute($route = false)
    {
        $routes = neurogenesis_theme_registry_get('neurogenesis_theme.routes.web', []); 
        $found = false;

        if(array_key_exists($this->namespace, $routes) ) {
            if( $route == false ) {
                // we show the first record from the routes array. this is the default route
                $default = array_key_first($routes[$this->namespace]);
                neurogenesis_theme_registry_set('neurogenesis_theme.routes.current', $default);

                $found = [new $routes[$this->namespace][$default][0], $routes[$this->namespace][$default][1]];
            }elseif(array_key_exists($route, $routes[$this->namespace])) {
                // we show the corresponding route
                $found = [new $routes[$this->namespace][$route][0], $routes[$this->namespace][$route][1]];
                neurogenesis_theme_registry_set('neurogenesis_theme.routes.current', $route);
            } else {
                // we found no corresponding route so we return a 404 template
                $found = [$this, 'notFound'];
            }
        } else {
            // we found no corresponding route so we return a 404 template
            $found = [$this, 'notFound'];
        }
        
        return $found;
    }
}