<?php

/**
 * Check for a user session. If $_SESSION['user'] already exists, return early. If not, check for a remember me
 * cookie. If a remember me cookie exists, validate the session and set $_SESSION['user'].
 */
function auth_check()
{
	if (isset($_SESSION['user'])) return true;

	if (isset($_COOKIE['remember_me'])) {
		$session = session_validate($_COOKIE['remember_me']);
		if ($session === true) {
			$user = User::find($session['user_id']);
			$_SESSION['user'] = serialize($user);
			return true;
		}
	}

	return false;
}

/**
 * Ensure a user is logged in, or redirect to the login page. This will also check for a remember me cookie and
 * populate the $_SESSION['user'] array.
 */
function auth_only()
{
	if (!auth_check()) redirect('/auth/login');
}

/**
 * If there is a user logged in, redirect to the home page. Used for when we have a guest-only page.
 */
function guest_only()
{
	if (auth_check()) redirect('/');
}

/**
 * Ensure the user has a character selected. If they have no character, redirect to the character creation page. Otherwise,
 * select the first character attached to the user.
 */
function must_have_character()
{
	// If there is a character selected, make sure the session is up to date.
	if (user()->char_id !== 0) {
		char();
		return;
	}

	// if no characters, redirect to create first
	if (user()->char_count() === 0) redirect('/character/create-first');

	// if no character selected, select the first one
	if (user()->char_id === 0) {
		$char = db_query(
			db_live(),
			'SELECT * FROM characters WHERE user_id = :u ORDER BY id ASC LIMIT 1',
			[':u' => user()->id]
		)->fetchArray(SQLITE3_ASSOC);
		change_user_character($char['id']);
	}
}

/**
 * The user must be authenticated and have a character.
 */
function auth_only_and_must_have_character()
{
	auth_only();
	must_have_character();
}
