<?php

namespace App;

use App\Utils\Error;

class Router {
    private $routes;
    private $params = [];
    private $requestMethod;
    private $path;

    public function __construct() {
        $this->routes = [];
    }

    public function addRoute($paths, $controller, $method = 'GET') {

        if (!is_array($paths)) {
            $paths = [$paths];
        }

        foreach ($paths as $path) {
            $this->routes[$path] = [
                'controller' => $controller,
                'method' => $method
            ];
        }
    }

    public function match() {
        $path = $_SERVER['REQUEST_URI'];
        $parts = parse_url($path);
        $this->path = $parts['path'];

        $this->requestMethod = $_SERVER['REQUEST_METHOD'];

        if (isset($this->routes[$this->path])) {
            return true;
        }
        return false;
    }

    public function render($conf) {
        if ($this->requestMethod === 'GET') {
            $this->params = (object)$_GET;
        } elseif ($this->requestMethod === 'POST') {
            $this->params = (object)$_POST;
        } else {
            $error = new Error();
            $error->index((object)['status' => 405, 'message' => 'Method not allowed']);
        }

        if ($conf->webPage === false && $this->path !== '/api') {
            $error = new Error();
            $error->index((object)['status' => 404, 'message' => 'The page that you have requested could not be found.']);
        }

        if ($this->path === '/debug') {
            require_once __DIR__ . '/../bin/thumbShoter.php';
            exit();
        }

        $className = '\\' . $this->routes[$this->path]['controller'];
        $controllerInstance = new $className();
        $content = $controllerInstance->index($this->params, $conf);
        if (in_array($className, ['\App\Controllers\Home', '\App\Controllers\Backend']) && empty($this->params->showImg)) {
            require_once __DIR__ . '/../tpl/bone.php';
        }
    }
}
