<?php
class Dashboard extends Controller {
  protected $user_model;
  protected $visitor_model;
  protected $option_builder;

  public function __construct() {
    Controller::__construct();
    $this->user_model = $this->model("UserModel");
    $this->visitor_model = $this->model("VisitorDataManagerModel");

    require_once '../app/controllers/OptionBuilder.php';
    $this->option_builder = new OptionBuilder;
  }

  public function get_visitor_click_count() {
    return count(file("../app/config/clicks.txt"));
  }

  public function get_visitor_count() {
    return $this->visitor_model->visitor_count;
  }

  public function get_elapsed_time() {
    $installation_timestamp = file_get_contents("../app/config/installation_time");
    $elapsed_time_from_installation = time() - $installation_timestamp;

    $minutes = floor(($elapsed_time_from_installation / 60) % 60);
    $seconds = $elapsed_time_from_installation % 60;

    return "$minutes:$seconds";
  }

  public function get_visitor_click_list() {
    $visitor_click_list = file("../app/config/clicks.txt") ? file("../app/config/clicks.txt") : '';

    if ($visitor_click_list == '') { echo '<b>There are no clicks!</b>'; return; }

    foreach ($visitor_click_list as $visitor_click) {
      echo $visitor_click . '<br>';
    }
  }

  public function get_dashboard_details() {
    $this->request_helper->only_allow_get_request();

    $visitor_click_count = $this->get_visitor_click_count();
    $visitor_count = $this->get_visitor_count();
    $elapsed_time = $this->get_elapsed_time();

    echo json_encode(array(
      'visitor_click_count' => $visitor_click_count,
      'visitor_count' => $visitor_count,
      'elapsed_time' => $elapsed_time
    ));
  }

  public function index() {
    $this->installation_helper->must_be_installed();
    if (!$this->user_model->is_user_logged_in()) { header("Location: " . URLROOT . "/user/login"); return; }

    $is_user_admin = $this->user_model->is_user_admin($_SESSION["active_user_username"]);
    $this->view("dashboard/panel", ["is_user_admin" => $is_user_admin, "username" => $_SESSION["active_user_username"], "option_builder" => $this->option_builder]);
  }
}
?>
