<?php
require_once __DIR__ . '/../includes/auth.php';

$token   = trim($_GET['token'] ?? '');
$error   = '';
$success = false;
$pending = null;

// Look up the reset token (username='__reset__' distinguishes from email-verification rows)
if ($token) {
    $stmt = db()->prepare(
        "SELECT * FROM pending_registrations WHERE token=? AND username='__reset__' AND expires_at > NOW()"
    );
    $stmt->execute([$token]);
    $pending = $stmt->fetch();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token    = trim($_POST['token'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirm  = $_POST['confirm']  ?? '';

    // Re-fetch pending row inside POST to prevent token reuse after expiry
    $stmt = db()->prepare(
        "SELECT * FROM pending_registrations WHERE token=? AND username='__reset__' AND expires_at > NOW()"
    );
    $stmt->execute([$token]);
    $pending = $stmt->fetch();

    if (!$pending) {
        $error = 'This reset link has expired or already been used. Please request a new one.';
    } elseif (strlen($password) < 6) {
        $error = 'Password must be at least 6 characters.';
    } elseif ($password !== $confirm) {
        $error = 'Passwords do not match.';
    } else {
        $hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 8]);
        $updated = db()->prepare("UPDATE users SET password=? WHERE email=?")
                       ->execute([$hash, $pending['email']]);
        db()->prepare("DELETE FROM pending_registrations WHERE token=?")->execute([$token]);
        $success = true;
        $pending = null;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= SITE_NAME ?> — Reset Password</title>
<link href="https://fonts.googleapis.com/css2?family=Exo+2:wght@400;700;900&family=Rajdhani:wght@400;500;600&display=swap" rel="stylesheet">
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{background:#0a0a12;color:#e8e8f0;font-family:'Rajdhani',sans-serif;min-height:100dvh;display:flex;align-items:center;justify-content:center;padding:24px}
body::before{content:'';position:fixed;inset:0;background-image:linear-gradient(rgba(0,229,255,0.03) 1px,transparent 1px),linear-gradient(90deg,rgba(0,229,255,0.03) 1px,transparent 1px);background-size:40px 40px;pointer-events:none}
.card{background:#1a1a2e;border:1px solid rgba(255,255,255,0.08);border-radius:20px;padding:40px 32px;max-width:420px;width:100%;text-align:center;position:relative;z-index:1}
.icon{font-size:64px;margin-bottom:20px;display:block}
.title{font-family:'Exo 2',sans-serif;font-weight:900;font-size:26px;margin-bottom:10px}
.title.success{background:linear-gradient(135deg,#f0c040,#00e5ff);-webkit-background-clip:text;-webkit-text-fill-color:transparent}
.title.error{color:#ff4444}
.msg{font-size:15px;color:#aaaacc;line-height:1.7;margin-bottom:28px}
.logo{font-family:'Exo 2',sans-serif;font-weight:900;font-size:20px;background:linear-gradient(135deg,#f0c040,#00e5ff);-webkit-background-clip:text;-webkit-text-fill-color:transparent;margin-bottom:28px;letter-spacing:1px}
.btn{display:block;width:100%;padding:15px;border:none;border-radius:10px;font-family:'Exo 2',sans-serif;font-weight:700;font-size:15px;letter-spacing:1px;cursor:pointer;text-decoration:none;text-align:center;transition:all .2s}
.btn-gold{background:linear-gradient(135deg,#f0c040,#d4a017);color:#000;box-shadow:0 4px 20px rgba(240,192,64,.4)}
.btn-outline{background:transparent;border:1.5px solid rgba(255,255,255,.2);color:#aaaacc;margin-top:10px}
.form-group{text-align:left;margin-bottom:18px}
.form-group label{display:block;font-size:13px;color:#8888aa;margin-bottom:6px;letter-spacing:.5px}
.form-group input{width:100%;background:#111122;border:1.5px solid rgba(255,255,255,.12);border-radius:10px;padding:13px 16px;color:#e8e8f0;font-family:'Rajdhani',sans-serif;font-size:15px;outline:none;transition:border-color .2s}
.form-group input:focus{border-color:#f0c040}
.alert-err{background:rgba(255,68,68,.1);border:1px solid rgba(255,68,68,.3);color:#ff9999;padding:12px 16px;border-radius:10px;font-size:14px;margin-bottom:20px;text-align:left}
</style>
</head>
<body>
<div class="card">
  <div class="logo">🎮 <?= SITE_NAME ?></div>

<?php if ($success): ?>
  <span class="icon">✅</span>
  <div class="title success">Password Updated!</div>
  <p class="msg">Your password has been reset successfully. You can now log in with your new password.</p>
  <a href="/" class="btn btn-gold">BACK TO LOGIN</a>

<?php elseif (!$token || (!$pending && !$error)): ?>
  <span class="icon">❌</span>
  <div class="title error">Invalid Link</div>
  <p class="msg">This password reset link is invalid or has expired.<br>Please request a new one from the app.</p>
  <a href="/" class="btn btn-gold">BACK TO HOME</a>

<?php else: ?>
  <div class="title" style="color:#f0c040;margin-bottom:8px;">Reset Password</div>
  <p class="msg" style="margin-bottom:24px;">Enter a new password for your account.</p>

  <?php if ($error): ?>
  <div class="alert-err"><?= htmlspecialchars($error) ?></div>
  <?php endif; ?>

  <form method="POST">
    <input type="hidden" name="token" value="<?= htmlspecialchars($token) ?>">
    <div class="form-group">
      <label>NEW PASSWORD</label>
      <input type="password" name="password" placeholder="At least 6 characters" required minlength="6" autofocus>
    </div>
    <div class="form-group">
      <label>CONFIRM PASSWORD</label>
      <input type="password" name="confirm" placeholder="Repeat new password" required minlength="6">
    </div>
    <button type="submit" class="btn btn-gold">SET NEW PASSWORD</button>
  </form>
<?php endif; ?>
</div>
</body>
</html>
