<?php
require_once 'includes/config.php';

// Decode token safely (email clients sometimes encode = signs in URLs)
$token = trim(urldecode($_GET['token'] ?? ''));
$valid = false;
$user  = null;

if ($token !== '') {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE reset_token = ?");
    $stmt->execute([$token]);
    $row = $stmt->fetch();

    if ($row) {
        // Both stored with date() (Asia/Colombo) and checked with time() — consistent
        if (strtotime($row['reset_expires']) >= time()) {
            $user  = $row;
            $valid = true;
        } else {
            // Expired — clear token so it can't be reused
            $pdo->prepare("UPDATE users SET reset_token=NULL, reset_expires=NULL WHERE id=?")
                ->execute([$row['id']]);
        }
    }
}

// AJAX POST — change password
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    if (!$valid)
        jsonResponse(['success'=>false,'message'=>'This reset link is invalid or has expired. Please request a new one.']);

    $password = $_POST['password'] ?? '';
    $confirm  = $_POST['confirm_password'] ?? '';

    if (strlen($password) < 8)
        jsonResponse(['success'=>false,'message'=>'Password must be at least 8 characters.']);
    if ($password !== $confirm)
        jsonResponse(['success'=>false,'message'=>'Passwords do not match.']);

    $hash = password_hash($password, PASSWORD_BCRYPT, ['cost'=>12]);
    $pdo->prepare("UPDATE users SET password=?, reset_token=NULL, reset_expires=NULL WHERE id=?")
        ->execute([$hash, $user['id']]);

    jsonResponse(['success'=>true,'message'=>'Password updated successfully!','redirect'=> SITE_URL.'/login.php']);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Reset Password — <?= SITE_NAME ?></title>
<link rel="stylesheet" href="<?= SITE_URL ?>/assets/css/style.css">
</head>
<body>
<div class="auth-wrapper">
<div class="auth-card animate-in">
  <div class="auth-logo">
    <div class="logo-icon">🔐</div>
    <h1>Set New Password</h1>
    <p>Choose a strong new password</p>
  </div>

  <div id="msgBox" style="display:none" class="alert"></div>

  <?php if (!$valid): ?>
  <div class="alert alert-error" style="margin-bottom:20px">
    ⚠️ This password reset link is <strong>invalid or has expired</strong>.<br>
    Reset links are valid for <?= RESET_EXPIRY_HOURS ?> hour(s) only.
  </div>
  <a href="<?= SITE_URL ?>/forgot-password" class="btn btn-primary btn-full">
    Request a New Reset Link →
  </a>

  <?php else: ?>
  <form id="resetForm" novalidate>
    <div class="form-group">
      <label class="form-label">New Password</label>
      <div class="input-icon">
        <span class="icon">🔒</span>
        <input type="password" name="password" class="form-control" placeholder="Min. 8 characters" required autofocus>
        <button type="button" class="toggle-password">👁️</button>
      </div>
    </div>
    <div class="form-group">
      <label class="form-label">Confirm New Password</label>
      <div class="input-icon">
        <span class="icon">🔑</span>
        <input type="password" name="confirm_password" class="form-control" placeholder="Repeat password" required>
        <button type="button" class="toggle-password">👁️</button>
      </div>
    </div>
    <button type="submit" id="resetBtn" class="btn btn-primary btn-full">Update Password</button>
  </form>
  <?php endif; ?>

  <p style="text-align:center;margin-top:20px;font-size:14px">
    <a href="<?= SITE_URL ?>/login" style="color:var(--accent)">← Back to Login</a>
  </p>
</div>
</div>
<script src="<?= SITE_URL ?>/assets/js/app.js"></script>
<?php if ($valid): ?>
<script>
(function(){
  var form   = document.getElementById('resetForm');
  var msgBox = document.getElementById('msgBox');
  var btn    = document.getElementById('resetBtn');

  function showMsg(msg, type) {
    msgBox.className = 'alert alert-' + type;
    msgBox.innerHTML = (type === 'error' ? '⚠️ ' : '✅ ') + msg;
    msgBox.style.display = 'flex';
  }

  // Password visibility toggles
  document.querySelectorAll('.toggle-password').forEach(function(b) {
    b.addEventListener('click', function() {
      var inp = b.previousElementSibling;
      inp.type = inp.type === 'password' ? 'text' : 'password';
      b.innerHTML = inp.type === 'password' ? '👁️' : '🙈';
    });
  });

  form.addEventListener('submit', async function(e) {
    e.preventDefault();
    var pass = form.password.value;
    var conf = form.confirm_password.value;
    if (pass.length < 8) { showMsg('Password must be at least 8 characters.', 'error'); return; }
    if (pass !== conf)   { showMsg('Passwords do not match.', 'error'); return; }

    btn.disabled = true;
    btn.innerHTML = '<span class="spinner"></span>&nbsp; Updating...';
    msgBox.style.display = 'none';

    try {
      var res  = await fetch(window.location.href, {
        method: 'POST', body: new FormData(form),
        headers: {'X-Requested-With': 'XMLHttpRequest'}
      });
      var text = await res.text();
      var data;
      try { data = JSON.parse(text); }
      catch(e) { throw new Error('Server error: ' + text.substring(0, 200)); }

      if (data.success) {
        showMsg(data.message + ' Redirecting to login...', 'success');
        btn.innerHTML = '✓ Done!';
        setTimeout(function() { window.location.href = data.redirect; }, 2000);
      } else {
        showMsg(data.message, 'error');
        btn.disabled = false;
        btn.innerHTML = 'Update Password';
      }
    } catch(err) {
      console.error(err);
      showMsg('Connection error. Please try again.', 'error');
      btn.disabled = false;
      btn.innerHTML = 'Update Password';
    }
  });
})();
</script>
<?php endif; ?>
</body>
</html>
