<?php
class UserModel {
  protected $database;

  public function __construct() {
    $this->database = new Database("localhost", SQL_USER_NAME, SQL_USER_PASS, SQL_DATABASE_NAME, "users");
  }

  // -- Database Commands --
  // Adding Data
  public function add_user($username, $password, $is_admin) {
    $query_data = array(
      "username" => $username,
      "password" => password_hash($password, PASSWORD_DEFAULT),
      "is_admin" => $is_admin ? 'true' : 'false'
    );

    return $this->database->insert($query_data);
  }

  // Getting Data
  public function get_all_users() {
    $query_data = array(
      "username"
    );

    return $this->database->select_all_with_condition($query_data, "WHERE is_admin='false'");
  }

  public function verify_user_login($username, $password) {
    $query_data = array(
      "username",
      "password"
    );

    $result = $this->database->select($query_data, "WHERE username='$username'");

    if ($result == "NULL" || !password_verify($password, $result["password"])) { return false; }

    return true;
  }

  public function is_user_admin($username) {
    $query_data = array(
      "is_admin"
    );

    return $this->database->select($query_data, "WHERE username='$username'")["is_admin"];
  }

  // Removing Data
  public function delete_user($username) {
    return $this->database->delete("WHERE username='$username'");
  }

  // -- Session Commands --
  public function begin_login_session() {
    $_SESSION["is_user_logged_in"] = 1;
  }

  public function end_login_session() {
    $_SESSION["is_user_logged_in"] = 0;
  }

  public function set_active_user_username($username) {
    $_SESSION["active_user_username"] = $username;
  }

  public function get_active_user_username() {
    return isset($_SESSION["active_user_username"]) ? $_SESSION["active_user_username"] : false;
  }

  public function is_user_logged_in() {
    return isset($_SESSION["is_user_logged_in"]) && $_SESSION["is_user_logged_in"] == 1;
  }
}
?>
