<?php /* Copyright (c) 2024 Freya Murphy */
class MainModel {

	// loaded route infomation
	public $info;
	public $db;
	public $user_id;

	private $users;

	function __construct() {
		$this->info = NULL;
		$this->db = new DatabaseHelper();
		$this->users = array();
		$_SESSION['jwt'] = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoicmVzdF91c2VyIiwidXNlcl9pZCI6MSwiZXhwIjoxNzExODUxMDUzfQ.FUcFO44SWV--YtVOy7NftTF8OeeOYGZDaDHigygQxsY';
		if (array_key_exists('jwt', $_SESSION)) {
			$this->get_session($_SESSION['jwt']);
		} else {
			$this->user_id = NULL;
		};
	}

	private function get_session($jwt) {
		$query = $this->db
			->select("_api.verify_jwt('" . $jwt . "') AS user_id;");
		$result = $query->row();
		$user_id = $result['user_id'];
		if ($user_id) {
			$this->user_id = $user_id;
		}
	}

	public function link_css($path) {
		return '<link rel="stylesheet" href="/public/' . $path . '">';
	}

	public function link_js($path) {
		return '<script src="/public/'. $path . '"></script>';
	}

	public function user() {
		if ($this->user_id) {
			return $this->db
				->select('*')
				->from('api.user')
				->where('id')
				->eq($this->user_id)
				->row();
		} else {
			return NULL;
		}
	}

	public function get_num($key, $default = NULL) {
		if (!array_key_exists($key, $_GET)) {
			if ($default !== NULL) {
				return $default;
			} else {
				error_page(400, lang('error_400'));
			}
		} else {
			$val = $_GET[$key];
			$val = intval($val);
			if ($val < 0) {
				return 0;
			} else {
				return $val;
			}
		}
	}

	public function get_users($objs) {
		$ids = array();
		foreach ($objs as $obj) {
			$id = $obj['user_id'];
			if (!array_key_exists($id, $this->users)) {
				array_push($ids, intval($id));
			}
		}
		if (!empty($ids)) {
			$result = $this->db
				->select('*')
				->from('api.user')
				->where_in('id', $ids)
				->rows();
			foreach ($result as $user) {
				$id = $user['id'];
				$this->users[$id] = $user;
			}
		}
		return $this->users;
	}

	public function display_name($user) {
		$name = '';
		if ($user['first_name']) {
			$name .= $user['first_name'];
		}
		if ($user['middle_name']) {
			if ($name != '') {
				$name .= ' ';
			}
			$name .= $user['middle_name'];
		}
		if ($user['last_name']) {
			if ($name != '') {
				$name .= ' ';
			}
			$name .= $user['last_name'];
		}
		if ($name == '') {
			$name = '@' . $user['username'];
		}
		return $name;
	}

	public function display_date($date) {
		return $date;
	}

}

?>