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

$error = null; $success = null;
$token = $_GET['token'] ?? '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $token = $_POST['token'] ?? '';
  $pass = $_POST['password'] ?? '';
  $pass2 = $_POST['password_confirm'] ?? '';
  if (!$token || !$pass || !$pass2) {
    $error = 'All fields are required';
  } elseif ($pass !== $pass2) {
    $error = 'Passwords do not match';
  } else {
    $stmt = db()->prepare("SELECT id, reset_expires_at FROM users WHERE reset_token = ?");
    $stmt->bind_param("s", $token);
    $stmt->execute();
    $res = $stmt->get_result();
    $user = $res->fetch_assoc();
    if (!$user) {
      $error = 'Invalid reset token';
    } elseif (strtotime($user['reset_expires_at']) < time()) {
      $error = 'Reset token has expired';
    } else {
      $hash = password_hash($pass, PASSWORD_DEFAULT);
      $stmt = db()->prepare("UPDATE users SET password_hash = ?, reset_token = NULL, reset_expires_at = NULL WHERE id = ?");
      $stmt->bind_param("si", $hash, $user['id']);
      $stmt->execute();
      $success = 'Password updated. You can now login.';
    }
  }
}
?>
<div class="container glass-card" style="padding:16px;margin-top:24px;max-width:520px;">
  <h2>Reset Password</h2>
  <?php if ($error): ?><div class="alert error"><?php echo htmlspecialchars($error); ?></div><?php endif; ?>
  <?php if ($success): ?><div class="alert success"><?php echo htmlspecialchars($success); ?></div><?php endif; ?>
  <form method="post">
    <input type="hidden" name="token" value="<?php echo htmlspecialchars($token); ?>">
    <label>New Password</label><input class="input" type="password" name="password" required>
    <label>Confirm Password</label><input class="input" type="password" name="password_confirm" required>
    <button class="btn" type="submit" style="margin-top:10px;">Update Password</button>
  </form>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>