<?php

namespace Origo\Entity;

use Origo\Services\Database;

class User {

  protected $id;
  protected $username;
  protected $email;
  protected $permissions = [];
  protected $database;

  public function __construct() {
    $this->database = new Database();
  }

  public function get($property) {
    return $this->{$property};
  }

  public function set($property, $value) {
    $this->{$property} = $value;
  }

  public function getPermissions() {
    return $this->permissions;
  }

  public function hasPermission($permission) {
    return in_array($permission, $this->permissions);
  }

  public function login($username, $password) {
    $statement = $this->database->prepare("SELECT username, id from users where username = ? AND password = ?");
    $statement->execute([
      $username,
      $password
    ]);
    $result = $statement->fetch();
    if (!$result) {
      return FALSE;
    }
    return $this->createSession($result['id']);
  }

  private function createSession(int $user_id = 0) {
    // Bail out early if id is less than 1.
    if ($user_id < 1) {
      return FALSE;
    }
    $session_id = 'ORIGO' . bin2hex(random_bytes(16));
    $stmt = $this->database->prepare("INSERT INTO sessions (user_id, session_id) VALUES (:user_id, :session_id)");
    $stmt->bindParam(':user_id', $user_id);
    $stmt->bindParam(':session_id', $session_id);
    $success = $stmt->execute();
    if ($success) {
      setcookie("ORIGOSESS", $session_id, time() + 3600);
      return $session_id;
    }
  }

  public function loadUserFromSession(string $session_id) {
    $statement = $this->database->prepare("SELECT user_id FROM sessions WHERE session_id = ?");
    $statement->execute([$session_id]);
    $result = $statement->fetch();
    $this->id = $result['user_id'] ?? '';
    $this->loadPermissions();
  }

  private function loadPermissions(): void {
    $statement = $this->database->prepare("SELECT permission from permissions WHERE user_id = ?");
    $statement->execute([$this->id]);
    $result = $statement->fetch();
    if ($result) {
      foreach ($result as $permission) {
        $this->permissions[] = $permission;
      }
    }
  }

}
