<?php
require_once '../includes/config.php';
$success = $error = '';

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

  $stmt = $pdo->prepare("SELECT * FROM employees WHERE email = ?");
  $stmt->execute([$email]);
  $user = $stmt->fetch();

  if ($user) {
    $token = bin2hex(random_bytes(32));
    $expires = date("Y-m-d H:i:s", strtotime("+1 hour"));

    $pdo->prepare("INSERT INTO password_resets (email, token, expires_at) VALUES (?, ?, ?)")
        ->execute([$email, $token, $expires]);

    // Simulate sending email
    $resetLink = "http:/cpforce.com.sg/auth/reset_password.php?token=$token";
    // mail($email, "Reset your password", "Reset link: $resetLink");
    $success = "Reset link sent! (Simulated: $resetLink)";
  } else {
    $error = "No account found with that email.";
  }
}
?>

<!DOCTYPE html>
<html>
<head><title>Forgot Password</title>
<link rel="stylesheet" href="../assets/css/bootstrap.min.css">
</head>
<body class="bg-light">
<div class="container mt-5" style="max-width:500px;">
  <h4>🔐 Forgot Password</h4>
  <?php if ($success): ?><div class="alert alert-success"><?= $success ?></div><?php endif; ?>
  <?php if ($error): ?><div class="alert alert-danger"><?= $error ?></div><?php endif; ?>

  <form method="post">
    <label>Email</label>
    <input type="email" name="email" class="form-control mb-3" required>
    <button class="btn btn-primary w-100">Send Reset Link</button>
  </form>
</div>
</body>
</html>
