<?php

/**
 * Create a token for a user. Returns the token on success, or false on failure.
 */
function token_create($userId)
{
	$token = token();
	$result = db_query(db_auth(), "INSERT INTO tokens (token, user_id) VALUES (:t, :u)", [
		':t' => $token,
		':u' => $userId
	]);
	if (!$result) return false;
	return $token;
}

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

/**
 * Delete a token by token.
 */
function token_delete($token)
{
	return db_query(db_auth(), "DELETE FROM tokens WHERE token = :t", [':t' => $token]);
}

/**
 * Validate a token by token and created date. Tokens are invalid if older than 7 days.
 */
function token_validate($token)
{
	$token = token_find($token);
	if (!$token) return false;
	if (strtotime('+7 days') < time()) {
		token_delete($token['token']);
		return false;
	}
	return true;
}

