<?php

namespace Actions;

use Models\Session;
use Models\User;
use Models\Wallet;

class Auth
{
	/*
		============================================================
		Registration
		============================================================
	*/
	public static function register_get(): void
	{
		echo render('layouts/basic', ['view' => 'pages/auth/register']);
	}

	public static function register_post(): void
	{
		$errors = [];

		$u = trim($_POST['u'] ?? '');
		$e = trim($_POST['e'] ?? '');
		$p = $_POST['p'] ?? '';

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

		/*
			An email is required.
			An email must be at most 255 characters long.
			An email must be a valid email address.
		*/
		if (empty($e) || strlen($e) > 255 || !filter_var($e, FILTER_VALIDATE_EMAIL)) {
			$errors['e'][] = 'Email is required must be a valid email address.';
		}

		/*
			A password is required.
			A password must be at least 6 characters long.
		*/
		if (empty($p) || strlen($p) < 6) {
			$errors['p'][] = 'Password is required and must be at least 6 characters long.';
		}

		/*
			A username must be unique.
		*/
		if (User::username_exists($u)) {
			$errors['u'][] = 'Username is already taken.';
		}

		/*
			An email must be unique.
		*/
		if (User::email_exists($e)) {
			$errors['e'][] = 'Email is already taken.';
		}

		// If there are errors at this point, send them to the page with errors flashed.
		if (!empty($errors)) {
			$GLOBALS['form-errors'] = $errors;
			echo render('layouts/basic', ['view' => 'pages/auth/register']);
			exit;
		}

		if (User::create($u, $e, $p) === false) error_response(400);

		$_SESSION['user'] = serialize(User::find($u));
		Wallet::create(user()->id);
		redirect('/character/create-first');
	}

	/*
		============================================================
		Login
		============================================================
	*/
	public static function login_get(): void
	{
		echo render('layouts/basic', ['view' => 'pages/auth/login']);
	}

	public static function login_post(): void
	{
		$errors = [];

		$u = trim($_POST['u'] ?? '');
		$p = $_POST['p'] ?? '';

		if (empty($u)) $errors['u'][] = 'Username is required.';
		if (empty($p)) $errors['p'][] = 'Password is required.';

		// If there are errors at this point, send them to the page with errors flashed.
		if (!empty($errors)) {
			$GLOBALS['form-errors'] = $errors;
			echo render('layouts/basic', ['view' => 'pages/auth/login']);
			exit;
		}

		$user = User::find($u);
		if ($user === false || !$user->check_password($p)) {
			$errors['x'][] = 'Invalid username or password.';
			$GLOBALS['form-errors'] = $errors;
			echo render('layouts/basic', ['view' => 'pages/auth/login']);
			exit;
		}

		$_SESSION['user'] = serialize($user);

		if ($_POST['remember'] ?? false) {
			$session = Session::create($user->id, strtotime('+30 days'));
			if ($session === false) error_response(400);
			set_cookie('remember_me', $session->token, $session->expires);
		}

		if ($user->char_count() === 0) {
			redirect('/character/create-first');
		} elseif (!change_user_character($user->char_id)) {
			echo "failed to change user character (aclp)";
			error_response(999);
		}

		redirect('/');
	}

	/*
		============================================================
		Logout
		============================================================
	*/
	public static function logout(): void
	{
		Session::delete(user()->id);
		unset($_SESSION['user']);
		set_cookie('remember_me', '', 1);
		redirect('/');
	}
}
