<?php
/**
 * Create an account. Verified by email + licence key (proves ownership of a
 * real subscription without a separate email-verification step).
 *
 * @package AutoOrderAccount
 */

require __DIR__ . '/_app.php';

if ( current_user() ) {
	go( '/account/' );
}

$err   = '';
$email = '';
$key   = '';

if ( 'POST' === ( $_SERVER['REQUEST_METHOD'] ?? '' ) ) {
	csrf_check();
	$email = strtolower( trim( $_POST['email'] ?? '' ) );
	$key   = strtoupper( trim( $_POST['license_key'] ?? '' ) );
	$pw    = (string) ( $_POST['password'] ?? '' );
	$pw2   = (string) ( $_POST['password2'] ?? '' );

	if ( ! filter_var( $email, FILTER_VALIDATE_EMAIL ) ) {
		$err = 'Please enter a valid email address.';
	} elseif ( strlen( $pw ) < 8 ) {
		$err = 'Password must be at least 8 characters.';
	} elseif ( $pw !== $pw2 ) {
		$err = 'The two passwords do not match.';
	} elseif ( account_get( $email ) ) {
		$err = 'An account with that email already exists — try logging in.';
	} else {
		$lic = aobd_get_license( $key );
		if ( ! $lic || strtolower( trim( $lic['email'] ) ) !== $email ) {
			$err = 'That email and licence key don’t match our records. Use the email you subscribed with and the licence key from your confirmation email.';
		} else {
			account_create( $email, $pw );
			login_user( $email );
			flash_set( 'Account created — welcome.' );
			go( '/account/' );
		}
	}
}

head( 'Create account' );
?>
<div class="card narrow">
	<h1>Create an account</h1>
	<p class="sub">Already subscribed? Create an account with the email you used and your licence key to manage your subscription.</p>
	<?php if ( $err ) : ?><div class="err"><?php echo e( $err ); ?></div><?php endif; ?>
	<form method="post" novalidate>
		<?php echo csrf_field(); ?>
		<label>Email<input type="email" name="email" required autocomplete="email" value="<?php echo e( $email ); ?>"></label>
		<label>Licence key<input type="text" name="license_key" required placeholder="AOBD-XXXXX-XXXXX-XXXXX-XXXXX" value="<?php echo e( $key ); ?>"></label>
		<label>Password (min 8 characters)<input type="password" name="password" required autocomplete="new-password"></label>
		<label>Confirm password<input type="password" name="password2" required autocomplete="new-password"></label>
		<button class="btn" type="submit">Create account</button>
	</form>
	<p class="links">Already have one? <a href="/account/login">Log in</a></p>
</div>
<?php
foot();
