<?php
require_once __DIR__ . "/../includes/config.php";
require_once __DIR__ . "/../includes/functions.php";

$msg = '';
$err = '';

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

  $stmt = $pdo->prepare("SELECT id,email FROM users WHERE email=? LIMIT 1");
  $stmt->execute([$email]);
  $user = $stmt->fetch();

  if (!$user) {
    $err = "If this email exists, you will receive a reset link.";
  } else {
    $token = bin2hex(random_bytes(32));
    $tokenHash = password_hash($token, PASSWORD_DEFAULT);
    $expires = date('Y-m-d H:i:s', time() + 3600);

    $pdo->prepare("INSERT INTO password_resets (user_id, token_hash, expires_at) VALUES (?,?,?)")
        ->execute([(int)$user['id'], $tokenHash, $expires]);

    $resetLink = "https://YOURDOMAIN.co.uk/auth/forgot.php?reset=1&email=" . urlencode($email) . "&token=$token";

    // TODO: Send via SMTP (PHPMailer). For now show link (development only).
    $msg = "Reset link (dev): <a href='".e($resetLink)."'>Click here</a>";
  }
}

$doReset = ($_GET['reset'] ?? '') == '1';
if ($doReset && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['new_password'])) {
  // handle reset submission
}

include __DIR__ . "/../includes/header.php";
?>
<div class="row justify-content-center">
  <div class="col-md-7">
    <div class="card shadow-sm">
      <div class="card-body p-4">
        <h3 class="mb-3">Forgot Password</h3>

        <?php if ($err): ?><div class="alert alert-warning"><?= e($err) ?></div><?php endif; ?>
        <?php if ($msg): ?><div class="alert alert-success"><?= $msg ?></div><?php endif; ?>

        <?php if (!$doReset): ?>
          <form method="post">
            <div class="mb-3">
              <label class="form-label">Enter your email</label>
              <input class="form-control" name="email" type="email" required>
            </div>
            <button class="btn btn-dark">Send Reset Link</button>
          </form>
        <?php else: ?>
          <?php
            $email = strtolower(trim($_GET['email'] ?? ''));
            $token = $_GET['token'] ?? '';
            $newErr=''; $newMsg='';

            if ($_SERVER['REQUEST_METHOD'] === 'POST') {
              $newPass = $_POST['new_password'] ?? '';
              if (strlen($newPass) < 6) {
                $newErr = "Password must be 6+ characters.";
              } else {
                $stmt = $pdo->prepare("SELECT u.id, pr.token_hash, pr.expires_at
                                       FROM users u
                                       JOIN password_resets pr ON pr.user_id=u.id
                                       WHERE u.email=? ORDER BY pr.id DESC LIMIT 1");
                $stmt->execute([$email]);
                $row = $stmt->fetch();

                if (!$row || strtotime($row['expires_at']) < time() || !password_verify($token, $row['token_hash'])) {
                  $newErr = "Invalid/expired token.";
                } else {
                  $hash = password_hash($newPass, PASSWORD_DEFAULT);
                  $pdo->prepare("UPDATE users SET password_hash=? WHERE id=?")->execute([$hash, (int)$row['id']]);
                  $pdo->prepare("DELETE FROM password_resets WHERE user_id=?")->execute([(int)$row['id']]);
                  $newMsg = "Password updated. You can login now.";
                }
              }
            }
          ?>

          <?php if ($newErr): ?><div class="alert alert-danger"><?= e($newErr) ?></div><?php endif; ?>
          <?php if ($newMsg): ?><div class="alert alert-success"><?= e($newMsg) ?> <a href="/auth/login.php">Login</a></div><?php endif; ?>

          <form method="post">
            <div class="mb-3">
              <label class="form-label">New Password</label>
              <input class="form-control" name="new_password" type="password" minlength="6" required>
            </div>
            <button class="btn btn-dark">Update Password</button>
          </form>
        <?php endif; ?>

      </div>
    </div>
  </div>
</div>
<?php include __DIR__ . "/../includes/footer.php"; ?>
