<?php
require_once '../includes/config.php';
$token = $_GET['token'] ?? '';
$success = $error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $password = password_hash($_POST['password'], PASSWORD_DEFAULT);

  $stmt = $pdo->prepare("SELECT email FROM password_resets WHERE token = ? AND expires_at >= NOW()");
  $stmt->execute([$token]);
  $reset = $stmt->fetch();

  if ($reset) {
    $pdo->prepare("UPDATE employees SET password = ? WHERE email = ?")->execute([$password, $reset['email']]);
    $pdo->prepare("DELETE FROM password_resets WHERE email = ?")->execute([$reset['email']]);
    $success = "Password reset successful! You may now login.";
  } else {
    $error = "Invalid or expired token.";
  }
}
?>

<!DOCTYPE html>
<html>
<head><title>Reset 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>🔑 Reset 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; ?>

  <?php if (!$success): ?>
    <form method="post">
      <label>New Password</label>
      <input type="password" name="password" class="form-control mb-3" required>
      <button class="btn btn-success w-100">Update Password</button>
    </form>
  <?php endif; ?>
</div>
</body>
</html>
