<?php

/**
 * Display a list of characters for the currently logged in user.
 */
function char_controller_list_get()
{
	auth_only_and_must_have_character();

	$GLOBALS['active_nav_tab'] = 'chars';
	echo page('chars/list', ['chars' => user()->char_list()]);
}

/**
 * Handle an action from the character list page.
 */
function char_controller_list_post()
{
	auth_only_and_must_have_character(); csrf_ensure();

	$GLOBALS['active_nav_tab'] = 'chars';

	$char_id = (int) ($_POST['char_id'] ?? 0);
	$action = $_POST['action'] ?? '';

	// If the character ID is not a number, or the action is not a string, return a 400.
	if (!is_numeric($char_id) || !is_string($action)) error_response(400);

	// If the character ID is 0, return to the list.
	if ($char_id === 0) {
		flash('alert_character_list_1', ['', 'No character selected.']);
		redirect('/characters');
	}

	// If the action is not one of the allowed actions, return a 400.
	if (!in_array($action, ['select', 'delete'])) error_response(400);

	// If the action is to select a character, change the user's selected character.
	if ($action === 'select') {
		// If the character ID is the current character, do nothing.
		if ($char_id === user()->char_id || $char_id === 0) {
			flash('alert_character_list_1', ['info', 'You are already using <b>' . char()->name . '</b>.']);
			redirect('/characters');
		}

		if (!Character::belongs_to($char_id, user()->id)) error_response(999);

		change_user_character($char_id);

		flash('alert_character_list_1', ['success', 'Switched to <b>' . char()->name . '</b>!']);
	}

	// If the action is to delete a character, move to the confirmation page.
	if ($action === 'delete') {
		if (!Character::belongs_to($char_id, user()->id)) error_response(999);

		echo page('chars/delete', ['char' => Character::find($char_id)]);
		exit;
	}

	redirect('/characters');
}

/**
 * Delete a character for the currently logged in user.
 */
function char_controller_delete_post()
{
	auth_only_and_must_have_character(); csrf_ensure();

	$char_id = (int) ($_POST['char_id'] ?? 0);

	// If the character ID is not a number, return a 400.
	if (!is_numeric($char_id)) error_response(400);

	// Ensure the character ID is valid and belongs to the user.
	if (!Character::belongs_to($char_id, user()->id)) error_response(999);

	$char = Character::find($char_id);

	// Confirm the name matches the name of the character. CASE SENSITIVE.
	if ($char['name'] !== trim($_POST['n'] ?? '')) {
		flash('alert_character_list_1', ['danger', 'Failed to delete <b>' . $char['name'] . '</b>. Name confirmation did not match.']);
		redirect('/characters');
	}

	// Delete the character
	Character::delete($char_id);

	// If the character being deleted is the currently selected character, select the first character.
	if (user()->char_id === $char_id) {
		$chars = user()->char_list();
		if (count($chars) > 0) change_user_character($chars[0]['id']);
	}

	flash('alert_character_list_1', ['danger', 'Character <b>' . $char['name'] . '</b> deleted.']);
	redirect('/characters');
}

/**
 * Form to create your first character.
 */
function char_controller_create_first_get()
{
	auth_only();

	$GLOBALS['active_nav_tab'] = 'chars';

	// If the user already has a character, redirect them to the main page.
	if (user()->char_count() > 0) redirect('/');

	echo page('chars/first');
}

/**
 * Create a character for the currently logged in user.
 */
function char_controller_create_post()
{
	auth_only(); csrf_ensure();

	$GLOBALS['active_nav_tab'] = 'chars';

	$errors = [];

	$name = trim($_POST['n'] ?? '');

	/*
		A name is required.
		A name must be between 3 and 18 characters.
		A name must contain only alphanumeric characters and spaces.
	*/
	if (empty($name) || strlen($name) < 3 || strlen($name) > 18 || !ctype_alnum(str_replace(' ', '', $name))) {
		$errors['n'][] = 'Name is required and must be between 3 and 18 characters long and contain only alphanumeric characters and spaces.';
	}

	/*
		A character's name must be unique.
	*/
	if (Character::name_exists($name)) $errors['n'][] = 'Name is already taken.';

	// If there are errors at this point, send them to the page with errors flashed.
	if (!empty($errors)) {
		$GLOBALS['form-errors-create-character'] = $errors;

		if (isset($_POST['first']) && $_POST['first'] === 'true') {
			// If this is the first character, return to the first character creation page.
			echo page('chars/first');
			exit;
		} else {
			// If this is not the first character, return to the character list page.
			echo page('chars/list', ['chars' => user()->char_list()]);
			exit;
		}
	}

	if (($char = Character::create(user()->id, $name)) === false) error_response(400);

	// Create the auxiliary tables
	$char->create_location();
	$char->create_gear();

	// Award the Adventurer title.
	$char->award_title(1);

	// Set the character as the user's selected character
	change_user_character($char->id);

	flash('alert_character_list_1', ['success', 'Character <b>' . $name . '</b> created!']);
	redirect('/characters');
}

