<?php

/**
 * Create a session for a user with a token and expiration date. Returns the token on success, or false on failure.
 */
function session_create($userId, $expires)
{
	$token = token();
	$result = db_query(db_auth(), "INSERT INTO sessions (token, user_id, expires) VALUES (:t, :u, :e)", [
		':t' => $token,
		':u' => $userId,
		':e' => $expires
	]);
	if (!$result) return false;
	return $token;
}

/**
 * Find a session by token.
 */
function session_find($token)
{
	$result = db_query(db_auth(), "SELECT * FROM sessions WHERE token = :t", [':t' => $token]);
	$session = $result->fetchArray(SQLITE3_ASSOC);
	if (!$session) return false;
	$result->finalize();
	return $session;
}

/**
 * Delete sessions by user id.
 */
function session_delete($userId)
{
	return db_query(db_auth(), "DELETE FROM sessions WHERE user_id = :u", [':u' => $userId]);
}

/**
 * Validate a session by token and expiration date. If expired, the session is deleted and false is returned.
 */
function session_validate($token)
{
	$session = session_find($token);
	if (!$session) return false;
	if ($session['expires'] < time()) {
		session_delete($session['user_id']);
		return false;
	}
	return true;
}
