<?php

function kpApiUserCreate($first, $last, $username, $email, $password, &$response) {
	try {
		// Check for duplicate username.
		$user = kirby()->users()->filterBy('name', $username);
		if ($user->first()) {
			$response['reason'] = 'User name already exists.';
		} else {
			// Save Kirby attributes.
			$user = kirby()->users()->create([
				'name'      => $username,
				'email'     => $email,
				'password'  => $password,
				'language'  => 'en',
				'role'      => 'user'
			]);
			// Send activation email.
			// This duplicates a lot of code from site/controllers/register.php
			$token = Str::random(16);
			$link  = kirby()->site()->url() . "/user/activate/" . $token;
			$email = kirby()->email([
			  'to'       => $email,
			  'from'     => option('user.email.activation.sender'),
			  'subject'  => option('user.email.activation.sender', 'Account Activation Link'),
			  'template' => 'account-activation',
			  'data'     => [
				 'link'   => $link,
			  ]
			]);
			// Save our extended attributes.
			$user->update([
				'firstname'             => $first,
				'lastname'              => $last,
				'emailActivation'       => false,
            'emailActivationToken'  => $token
			]);
			// Save SQL attributes.
			// ***TODO***
			// ***TODO*** Intercept password change and user enable/disable to update the DB.

			// Return result.
			$response['result'] = 'true';
			$response['reason'] = 'Check your E-mail for activation instructions.';
		}
	} catch(Exception $e) {
		if (strpos($e->getMessage(), "email")) {
			$response['reason'] = 'E-mail already exists.';
		} else {
			$response['reason'] = $e->getMessage();
		}
	}
}

?>
