<?php

namespace Webuccino\Install\Core;

use Webuccino\Install\Core\Middleware\Authenticated;
use Webuccino\Install\Core\Middleware\Guest;
use Webuccino\Install\Core\Middleware\Middleware;

class Router
{
    protected $routes = [];

    public function add($method, $uri, $controller)
    {
        $this->routes[] = [
            'uri' => $uri,
            'controller' => $controller,
            'method' => $method,
            'middleware' => null
        ];

        return $this;
    }

    public function get($uri, $controller)
    {
        return $this->add('GET', $uri, $controller);
    }

    public function post($uri, $controller)
    {
        return $this->add('POST', $uri, $controller);
    }

    public function delete($uri, $controller)
    {
        return $this->add('DELETE', $uri, $controller);
    }

    public function patch($uri, $controller)
    {
        return $this->add('PATCH', $uri, $controller);
    }

    public function put($uri, $controller)
    {
        return $this->add('PUT', $uri, $controller);
    }

    public function only($key)
    {
        $this->routes[array_key_last($this->routes)]['middleware'] = $key;

        return $this;
    }

    public function route_native($uri, $method)
    {
        $uri = str_replace("/index.php", "", $uri);
        foreach ($this->routes as $route) {
            // $uri = strlen($uri) > 1 ? rtrim($uri) : $uri;
            if (rtrim($route['uri'], "/") === rtrim($uri, "/")  && $route['method'] === strtoupper($method)) {
                Middleware::resolve($route['middleware']);

                return require base_path_native('Http/controllers/' . $route['controller']);
            }
        }

        $this->abort_native();
    }

    public function previousUrl()
    {
        return $_SERVER['HTTP_REFERER'];
    }

    protected function abort_native()
    {
        // http_response_code($code);

        // require base_path_native("views/installer.php");

        // die();
        return redirect_native(route_native('/'));
    }
}
