<?php
require_once BACK . 'bootstrap.php';
final class Controller {
  private $action = '';
  private $target = '';
  public function __construct() {
    $this->action = empty($_GET['action']) ? 'Login' : $_GET['action'];
    $this->target = empty($_GET['target']) ? 'index' : $_GET['target'];
    $_POST['option'] = $_GET['option'];
  }
  public function dispatch() {
    $this->action = NamingUtils::toUpperCamelCase($this->action);
    require_once BACK . 'app' . DS . $this->action . '.php';
    $class = new $this->action();
    $result = $class->invoke($this->target);
    if ($result instanceof Forward) {
      $this->forward($result);
    } elseif ($result instanceof Redirect) {
      $this->redirect($result);
    } elseif ($result instanceof Direct) {
      $this->direct();
    } else {
      exit('404 Not Found');
    }
  }
  private function forward(Forward $result) {
    $html = is_null($result->getPath()) ? NamingUtils::toLowerSnakeCase($this->action) : $result->getPath();
    ob_start();
    extract($result->getResponse(), EXTR_OVERWRITE);
    require_once BACK . 'html' . DS . $html . '.html';
    exit(ob_get_clean());
  }
  private function redirect(Redirect $result) {
    header('Location: /' . $result->getPath());
    exit();
  }
  private function direct() {
    exit();
  }
}
// EOF.
