<?php
class Core {
  protected $currentController = "StartUp";
  protected $currentMethod = "run";
  protected $params = [];
  protected $isAdminRequested = false;

  public function __construct() {
    $url = $this->get_url();

    if ($url && file_exists('../app/controllers/' . ucfirst($url[0]) . '.php')) {
      $this->currentController = ucfirst($url[0]);
      // unset($url[0]);
    }

    // creates shortcut, /admin will redirect to user/login
    // TODO: if any more needed, convert into function
    if (isset($url[0]) && strtolower($url[0]) == "admin") {
      $this->currentController = "User";
      $this->currentMethod = "login";
      $this->isAdminRequested = true;
    }

    // shows 404 if there is no model matching url[0]
    // first condition bypasses 404 if /admin is typed (as /admin is a redirect and not a model)
    if (!$this->isAdminRequested && isset($url[0]) && !file_exists("../app/controllers/" . ucfirst($url[0]) . ".php")) {
      $this->show_404();
    }

    ob_start();
    require_once '../app/controllers/' . $this->currentController . '.php';

    $this->currentController = new $this->currentController;

    // if there is no controller then assume default page (startupmanager/run)
    if (isset($url[0])) {
      // checks for an index method if no method is included within url, allows for cleaner URLs
      if (method_exists($this->currentController, isset($url[1]) ? $url[1] : "index")) {
        $this->currentMethod = isset($url[1]) ? $url[1] : "index";
        if (isset($url[1])) { unset($url[1]); }
      } else {
        $this->show_404();
      }
    }

    $this->params = $url ? array_values($url) : [];

    call_user_func_array([$this->currentController, $this->currentMethod], $this->params);
  }

  public function get_url() { // turns URL into array
    if (isset($_GET["url"])) {
      $url = rtrim($_GET['url'], '/');
      $url = filter_var($url, FILTER_SANITIZE_URL);
      $url = explode('/', $url);
      return $url;
    }
  }

  private function show_404() {
    http_response_code(404);
    die(0);
  }
}
?>
