<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/config.php';   // has BASE_URL + url()
require_once __DIR__ . '/../includes/helpers.php';
require_once __DIR__ . '/../includes/mailer.php';   // <- PHPMailer wrapper

$msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = strtolower(trim($_POST['email'] ?? ''));

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $msg = 'Enter a valid email.';
    } else {
        // Look up user (don’t reveal existence)
        $st = $pdo->prepare("SELECT id FROM users WHERE LOWER(email)=? LIMIT 1");
        $st->execute([$email]);
        $u = $st->fetch();

        if ($u) {
            // Create token + expiry
            $rawToken = random_bytes(32);
            $hashBin  = hash('sha256', $rawToken, true); // store binary hash
            $expires  = (new DateTime('+30 minutes', new DateTimeZone('Africa/Lagos')))->format('Y-m-d H:i:s');

            $upd = $pdo->prepare("UPDATE users SET reset_token_hash=?, reset_expires=? WHERE id=?");
            $upd->execute([$hashBin, $expires, $u['id']]);

            // Build link (hex encode token)
            $tokenHex = bin2hex($rawToken);
            $link = url('reset.php') . '?e=' . urlencode($email) . '&t=' . $tokenHex;

            // Send the email
            $subject  = 'Reset your Whiteman Money password';
            $htmlBody = '
              <p>Hello,</p>
              <p>We received a request to reset your password. Click the button below:</p>
              <p><a href="'.$link.'" style="background:#4f8cff;color:#fff;padding:10px 16px;border-radius:8px;text-decoration:none;display:inline-block">Reset Password</a></p>
              <p>If the button doesn’t work, paste this in your browser:<br><code>'.$link.'</code></p>
              <p>This link expires in 30 minutes.</p>
              <p>— Whiteman Money</p>
            ';
            $textBody = "Reset your password:\n$link\n\nThis link expires in 30 minutes.";

            $sent = send_mail($email, $subject, $htmlBody, $textBody);

            // User-facing message (don’t leak whether email exists)
            $msg = $sent
                ? 'If that email exists, a reset link has been sent.'
                : 'We could not send the email right now. Here is your reset link (copy it manually):<br><a href="'.sanitize($link).'">'.sanitize($link).'</a>';
        } else {
            // Generic either way
            $msg = 'If that email exists, a reset link has been sent.';
        }
    }
}

?>
<link rel="stylesheet" href="/public/assets/landing.css">
<div class="container">
  <div class=>
    <div class="brand"><div class="logo"></div><h1>Forgot password</h1></div>
    <div class="actions">
      <a class="btn ghost" href="<?= url('login.php') ?>">Back to Login</a>
    </div>
  </div>

  <div class="card" style="max-width:560px;margin:0 auto">
    <?php if (!empty($msg)): ?>
      <div class="info mb-2"><?= $msg ?></div>
    <?php endif; ?>

    <form method="post" class="stack">
      <div>
        <label>Email</label>
        <input type="email" name="email" required>
      </div>
      <button class="btn">Send reset link</button>
    </form>
  </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
