<?php
/**
 * Forgot password — emails a reset link (no account enumeration).
 *
 * @package AutoOrderAccount
 */

require __DIR__ . '/_app.php';

$done = false;
if ( 'POST' === ( $_SERVER['REQUEST_METHOD'] ?? '' ) ) {
	csrf_check();
	$email = strtolower( trim( $_POST['email'] ?? '' ) );
	$acc   = $email ? account_get( $email ) : null;
	if ( $acc ) {
		$token = bin2hex( random_bytes( 24 ) );
		$st    = aobd_db()->prepare( 'UPDATE aobd_accounts SET reset_token = ?, reset_expires = ? WHERE email = ?' );
		$st->execute( array( $token, time() + 3600, $acc['email'] ) );

		$link = 'https://api.demfilz.com/account/reset?token=' . $token;
		$body = "We received a request to reset your Demfilz account password.\n\n"
			. "Reset it here (link expires in 1 hour):\n$link\n\n"
			. "If you didn't request this, you can safely ignore this email.";
		// phpcs:ignore
		@mail( $acc['email'], 'Reset your Demfilz account password', $body, 'From: Demfilz <licensing@demfilz.com>' );
	}
	$done = true;
}

head( 'Forgot password' );
?>
<div class="card narrow">
	<h1>Forgot password</h1>
	<?php if ( $done ) : ?>
		<p class="sub">If an account exists for that email, a password-reset link is on its way. Check your inbox (and spam).</p>
		<p class="links"><a href="/account/login">Back to log in</a></p>
	<?php else : ?>
		<p class="sub">Enter your account email and we’ll send you a link to reset your password.</p>
		<form method="post" novalidate>
			<?php echo csrf_field(); ?>
			<label>Email<input type="email" name="email" required autocomplete="email"></label>
			<button class="btn" type="submit">Send reset link</button>
		</form>
		<p class="links"><a href="/account/login">Back to log in</a></p>
	<?php endif; ?>
</div>
<?php
foot();
