<?php
declare(strict_types=1);

require_once __DIR__ . '/includes/bootstrap.php';
require_once __DIR__ . '/includes/views.php';

$config = require __DIR__ . '/includes/config.php';
if (!is_file($config['installed_flag'])) {
    header('Location: install.php', true, 302);
    exit;
}

if (current_user()) {
    header('Location: dashboard.php', true, 302);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    $email = trim((string) ($_POST['email'] ?? ''));
    $token = null;
    if ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $token = create_password_reset_token($email);
    }
    if ($token !== null) {
        $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
        $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
        $path = portal_url('reset.php');
        $link = $scheme . '://' . $host . $path . '?token=' . rawurlencode($token);
        $subject = 'Reset your Galleys portal password';
        $body = "Reset your password (link expires in one hour):\r\n\r\n" . $link . "\r\n";
        $from = $config['mail_from'] ?? 'contact@galleys.pub';
        @mail($email, $subject, $body, 'From: ' . $from . "\r\nContent-Type: text/plain; charset=UTF-8");
    }
    flash_set('info', 'If an account exists for that email, we sent reset instructions.');
    header('Location: login.php', true, 302);
    exit;
}

portal_header('Forgot password', null);
?>
<div class="portal-auth-card">
  <h1 class="portal-h1">Reset password</h1>
  <p class="portal-lead">We will email you a link if that address has an account.</p>
  <form method="post" class="portal-form">
    <?= csrf_field() ?>
    <label class="portal-label">Email
      <input class="portal-input" type="email" name="email" required autocomplete="email">
    </label>
    <button type="submit" class="portal-btn portal-btn-primary portal-btn-block">Send reset link</button>
  </form>
  <p class="portal-auth-meta"><a href="login.php">Back to sign in</a></p>
</div>
<?php
portal_footer();
