<?php

namespace Models;

class Session
{
	public function __construct(
		public int $user_id,
		public string $token,
		public int $expires
	) {}

	public static function create(int $user_id, int $expires): Session|false
	{
		$token = token();
		$result = auth_db()->query("INSERT INTO sessions (token, user_id, expires) VALUES (:t, :u, :e)", [
			':t' => $token,
			':u' => $user_id,
			':e' => $expires
		]);
		if ($result === false) return false;
		return new Session($user_id, $token, $expires);
	}

	public static function find(string $token): Session|false
	{
		$result = auth_db()->query("SELECT * FROM sessions WHERE token = :t", [':t' => $token]);
		$session = db_fetch_array($result);
		if ($session === false) return false;
		$result->finalize();
		return new Session($session['user_id'], $session['token'], $session['expires']);
	}

	public static function delete(int $user_id): \SQLite3Result|false
	{
		return auth_db()->query("DELETE FROM sessions WHERE user_id = :u", [':u' => $user_id]);
	}

	public function validate(): bool
	{
		if (empty($this->user_id) || empty($this->token)) return false;
		if ($this->expires < time()) {
			self::delete($this->user_id);
			return false;
		}
		return true;
	}
}
