<?php
if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/oauth.php';
include __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/mailer.php';

$info = null; $error = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $email = trim($_POST['email'] ?? '');
  if (!$email) {
    $error = 'Email is required';
  } else {
    $stmt = db()->prepare("SELECT id FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $res = $stmt->get_result();
    $user = $res->fetch_assoc();
    if (!$user) {
      $error = 'No account found for that email';
    } else {
      $token = bin2hex(random_bytes(32));
      $expires = date('Y-m-d H:i:s', time() + 3600);
      $stmt = db()->prepare("UPDATE users SET reset_token = ?, reset_expires_at = ? WHERE id = ?");
      $stmt->bind_param("ssi", $token, $expires, $user['id']);
      $stmt->execute();

      $link = BASE_URL . '/pages/reset_password.php?token=' . urlencode($token);
      $subject = 'Reset your WATCHING password';
      $message = "Hello,\n\nWe received a password reset request.\n\nReset link: $link\n\nIf you did not request this, ignore this email.";
      $headers = "From: " . MAIL_FROM_NAME . " <" . MAIL_FROM . ">\r\n";
      // Send email via PHPMailer if available, else fallback to mail()
      send_mail($email, $subject, $message);

      $info = 'If an account exists for that email, a reset link was sent.';
    }
  }
}
?>
<div class="container glass-card" style="padding:16px;margin-top:24px;max-width:520px;">
  <h2>Forgot Password</h2>
  <?php if ($error): ?><div class="alert error"><?php echo htmlspecialchars($error); ?></div><?php endif; ?>
  <?php if ($info): ?><div class="alert success"><?php echo htmlspecialchars($info); ?></div><?php endif; ?>
  <form method="post">
    <label>Email</label><input class="input" type="email" name="email" required>
    <button class="btn" type="submit" style="margin-top:10px;">Send Reset Link</button>
  </form>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>