<?php

/**
 * Print the world page.
 */
function world_controller_get()
{
	auth_only_and_must_have_character();
	echo render('layouts/game');
}

/**
 * Handle a request to move a character.
 */
function world_controller_move_post()
{
	/*
		This endpoint is used to move the character around the world. The client sends a POST request with the direction
		they want to move the character. The server will update the character's position in the database and return the
		new position to the client.

		We should only be using this endpoint as an AJAX request from the world page. Since we don't need all the character's
		data to move them, we can just get and update their lcoation using the user's currently selected character ID.
	*/

	ajax_only(); auth_only(); csrf_ensure();

	define('directions', [
		[0, -1], // Up
		[0, 1],  // Down
		[-1, 0], // Left
		[1, 0]   // Right
	]);

	// direction must exist
	$d = (int) $_POST['direction'] ?? -1;

	// Update the character's position
	// 0 = up, 1 = down, 2 = left, 3 = right
	$x = location('x');
	$y = location('y');

	if (isset(directions[$d])) {
		$x += directions[$d][0];
		$y += directions[$d][1];
	} else {
		error_response(999);
	}

	$r = db_query(db_live(), 'UPDATE char_locations SET x = :x, y = :y WHERE char_id = :c', [
		':x' => $x,
		':y' => $y,
		':c' => user()->char_id
	]);

	if ($r === false) throw new Exception('Failed to move character. (wcmp)');

	json_response(['x' => $x, 'y' => $y]);
}
