<?php
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
require_once __DIR__ . '/config/db.php';
startSession();

if (isLoggedIn()) { header('Location: dashboard.php'); exit; }

$token    = trim($_GET['token'] ?? '');
$msg      = ''; $msgType = '';
$success  = false;
$tokenValid = false;
$user     = null;

// ── Validate token first ────────────────────────────────────
if ($token) {
    try {
        // Auto-add columns if missing
        try {
            db()->exec("ALTER TABLE users
                ADD COLUMN IF NOT EXISTS password_reset_token VARCHAR(100) NULL,
                ADD COLUMN IF NOT EXISTS password_reset_expires DATETIME NULL");
        } catch(PDOException $e) {}

        $q = db()->prepare(
            "SELECT user_id, first_name, email, password_reset_expires
             FROM users
             WHERE password_reset_token = ? AND is_active = 1 LIMIT 1"
        );
        $q->execute([$token]);
        $user = $q->fetch();

        if (!$user) {
            $msg = 'This reset link is invalid or has already been used.'; $msgType = 'e';
        } elseif (strtotime($user['password_reset_expires']) < time()) {
            $msg = 'This reset link has <strong>expired</strong> (valid for 1 hour). <a href="forgot_password.php" style="color:inherit;font-weight:700">Request a new one →</a>';
            $msgType = 'e';
        } else {
            $tokenValid = true;
        }
    } catch(PDOException $e) {
        $msg = 'Server error. Please try again.'; $msgType = 'e';
    }
} else {
    $msg = 'No reset token provided.'; $msgType = 'e';
}

// ── Handle form submission ──────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $tokenValid) {
    $password  = $_POST['password']  ?? '';
    $password2 = $_POST['password2'] ?? '';

    $errs = [];
    if (strlen($password) < 8)               $errs[] = 'Password must be at least 8 characters.';
    if (!preg_match('/[A-Z]/', $password))   $errs[] = 'Must contain at least one uppercase letter.';
    if (!preg_match('/[0-9]/', $password))   $errs[] = 'Must contain at least one number.';
    if ($password !== $password2)             $errs[] = 'Passwords do not match.';

    if ($errs) {
        $msg = implode('<br>', $errs); $msgType = 'e';
    } else {
        try {
            $hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
            db()->prepare(
                "UPDATE users
                 SET password_hash=?, password_reset_token=NULL, password_reset_expires=NULL, updated_at=NOW()
                 WHERE user_id=?"
            )->execute([$hash, $user['user_id']]);

            // Kill all remember-me tokens for security
            try {
                db()->prepare("DELETE FROM remember_tokens WHERE user_id=?")->execute([$user['user_id']]);
            } catch(PDOException $e) {}

            $success = true;
        } catch(PDOException $e) {
            $msg = 'Server error. Please try again.'; $msgType = 'e';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Reset Password — communeglobal</title>
<link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;600;700&display=swap" rel="stylesheet">
<style>
:root{--primary:#E05A2B;--blue:#1B3F6E;--teal:#1A7F8E;--teal-dk:#136070;--text:#222;--muted:#666;--border:#D1D5DB;--bg:#F0F4F8;--white:#fff;--error:#DC2626;--font:'Open Sans',sans-serif;}
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
body{font-family:var(--font);background:var(--bg);min-height:100vh;display:flex;flex-direction:column}
a{color:var(--teal);text-decoration:none}a:hover{text-decoration:underline}
.nav{background:var(--white);border-bottom:1px solid var(--border);padding:0 32px;height:54px;display:flex;align-items:center;justify-content:space-between;flex-shrink:0;box-shadow:0 1px 4px rgba(0,0,0,.06)}
.logo{font-size:22px;font-weight:700;color:var(--primary)}
.page{flex:1;display:flex;align-items:center;justify-content:center;padding:32px 16px}
.card{background:var(--white);border-radius:12px;box-shadow:0 4px 32px rgba(0,0,0,.1);width:100%;max-width:420px;overflow:hidden}
.card-hdr{background:linear-gradient(135deg,var(--blue),#1A5276);padding:26px 32px}
.card-hdr-title{font-size:21px;font-weight:700;color:#fff;margin-bottom:4px}
.card-hdr-sub{font-size:13.5px;color:rgba(255,255,255,.75)}
.card-body{padding:28px 32px 36px}
.fg{margin-bottom:18px}
.fl{display:block;font-size:13px;font-weight:600;color:var(--text);margin-bottom:5px}
.req{color:var(--error)}
.fi{width:100%;padding:10px 14px;border:1.5px solid var(--border);border-radius:6px;font-family:var(--font);font-size:14px;color:var(--text);outline:none;transition:border-color .15s;background:var(--white)}
.fi:focus{border-color:var(--teal);box-shadow:0 0 0 3px rgba(26,127,142,.12)}
.fi::placeholder{color:#9CA3AF}
.pw-wrap{position:relative}
.pw-wrap .fi{padding-right:44px}
.pw-eye{position:absolute;right:12px;top:50%;transform:translateY(-50%);background:none;border:none;cursor:pointer;color:var(--muted);font-size:16px;padding:4px;line-height:1}
/* Strength bar */
.pw-str{height:4px;background:#E5E7EB;border-radius:2px;margin-top:7px;overflow:hidden}
.pw-str-bar{height:100%;width:0;border-radius:2px;transition:all .3s}
.pw-hint{font-size:11.5px;color:var(--muted);margin-top:4px}
/* Match hint */
.match-hint{font-size:11.5px;margin-top:5px}
/* Requirements checklist */
.req-list{background:#F8FAFC;border:1px solid #E5E7EB;border-radius:6px;padding:12px 14px;margin-bottom:18px;font-size:12.5px}
.req-list div{display:flex;align-items:center;gap:7px;padding:3px 0;color:var(--muted);transition:color .2s}
.req-list div.ok{color:#16A34A}
.req-list div.ok .dot{background:#16A34A}
.dot{width:7px;height:7px;border-radius:50%;background:#CBD5E1;flex-shrink:0;transition:background .2s}
.btn{width:100%;padding:13px;background:var(--teal);color:#fff;border:none;border-radius:6px;font-family:var(--font);font-size:15px;font-weight:700;cursor:pointer;transition:background .15s;display:flex;align-items:center;justify-content:center;gap:8px}
.btn:hover{background:var(--teal-dk)}
.btn:disabled{opacity:.5;cursor:not-allowed}
.alert{padding:13px 16px;border-radius:7px;font-size:13.5px;line-height:1.6;margin-bottom:20px}
.alert-e{background:#FEF2F2;border:1px solid #FECACA;color:#991B1B}
.alert-s{background:#F0FDF4;border:1px solid #BBF7D0;color:#166534}
.spin{width:16px;height:16px;border:2.5px solid rgba(255,255,255,.35);border-top-color:#fff;border-radius:50%;animation:sp .6s linear infinite;flex-shrink:0}
@keyframes sp{to{transform:rotate(360deg)}}
.back-link{display:block;text-align:center;margin-top:18px;font-size:13.5px;color:var(--muted)}
.footer{text-align:center;padding:14px;font-size:12px;color:var(--muted)}
.success-box{text-align:center;padding:8px 0}
.success-icon{font-size:56px;margin-bottom:14px}
.success-title{font-size:20px;font-weight:700;color:var(--text);margin-bottom:8px}
.success-desc{font-size:13.5px;color:var(--muted);line-height:1.7;margin-bottom:24px}
</style>
</head>
<body>

<?php include __DIR__ . '/../include/header.php'; ?>

<div class="page">
  <div class="card">
    <div class="card-hdr">
      <div class="card-hdr-title">🔒 Reset Password</div>
      <div class="card-hdr-sub">
        <?php if ($tokenValid && !$success): ?>
          Hi <?= htmlspecialchars($user['first_name']) ?>, set your new password below
        <?php else: ?>
          communeglobal account security
        <?php endif; ?>
      </div>
    </div>
    <div class="card-body">

      <?php if ($msg): ?>
      <div class="alert alert-<?= $msgType ?>"><?= $msg ?></div>
      <?php endif; ?>

      <?php if ($success): ?>
      <!-- ── SUCCESS ── -->
      <div class="success-box">
        <div class="success-icon">✅</div>
        <div class="success-title">Password updated!</div>
        <div class="success-desc">
          Your password has been reset successfully.<br>
          Ab naye password se login karo.
        </div>
        <a href="login.php" class="btn" style="text-decoration:none;display:inline-flex;width:auto;padding:11px 32px">
          Sign in now →
        </a>
      </div>

      <?php elseif ($tokenValid): ?>
      <!-- ── RESET FORM ── -->
      <form method="POST" id="resetForm" novalidate>
        <input type="hidden" name="token" value="<?= htmlspecialchars($token) ?>">

        <!-- Requirements checklist -->
        <div class="req-list" id="reqList">
          <div id="req-len"><span class="dot"></span> At least 8 characters</div>
          <div id="req-up"><span class="dot"></span> One uppercase letter (A–Z)</div>
          <div id="req-num"><span class="dot"></span> One number (0–9)</div>
          <div id="req-match"><span class="dot"></span> Passwords match</div>
        </div>

        <div class="fg">
          <label class="fl" for="password">New password <span class="req">*</span></label>
          <div class="pw-wrap">
            <input class="fi" type="password" id="password" name="password"
                   placeholder="Min 8 characters"
                   autocomplete="new-password"
                   oninput="checkAll()" required>
            <button type="button" class="pw-eye" onclick="togglePw('password',this)">👁️</button>
          </div>
          <div class="pw-str"><div class="pw-str-bar" id="strBar"></div></div>
          <div class="pw-hint" id="strHint">Enter a strong password</div>
        </div>

        <div class="fg">
          <label class="fl" for="password2">Confirm new password <span class="req">*</span></label>
          <div class="pw-wrap">
            <input class="fi" type="password" id="password2" name="password2"
                   placeholder="Repeat password"
                   autocomplete="new-password"
                   oninput="checkAll()" required>
            <button type="button" class="pw-eye" onclick="togglePw('password2',this)">👁️</button>
          </div>
          <div class="match-hint" id="matchHint"></div>
        </div>

        <button type="submit" class="btn" id="resetBtn">Set new password</button>
      </form>

      <?php else: ?>
      <!-- ── INVALID TOKEN ── -->
      <div style="text-align:center;padding:16px 0">
        <div style="font-size:48px;margin-bottom:14px">⛔</div>
        <div style="font-size:15px;font-weight:700;color:var(--text);margin-bottom:10px">Link Invalid or Expired</div>
        <div style="font-size:13.5px;color:var(--muted);margin-bottom:20px;line-height:1.6">
          Reset links expire after 1 hour.<br>Please request a new one.
        </div>
        <a href="forgot_password.php" class="btn" style="text-decoration:none;display:inline-flex;width:auto;padding:11px 28px">
          Request new link →
        </a>
      </div>
      <?php endif; ?>

      <a href="login.php" class="back-link">← Back to Sign in</a>
    </div>
  </div>
</div>


<script>
function togglePw(id, btn) {
  const f = document.getElementById(id);
  f.type = (f.type === 'password') ? 'text' : 'password';
  btn.textContent = (f.type === 'password') ? '👁️' : '🙈';
}

const colors = ['','#EF4444','#F97316','#EAB308','#22C55E','#16A34A'];
const labels = ['','Weak','Fair','Good','Strong','Very strong'];

function checkAll() {
  const p1 = document.getElementById('password')?.value  || '';
  const p2 = document.getElementById('password2')?.value || '';

  // Strength
  let s = 0;
  if (p1.length >= 8)           s++;
  if (/[A-Z]/.test(p1))        s++;
  if (/[0-9]/.test(p1))        s++;
  if (/[^A-Za-z0-9]/.test(p1)) s++;
  if (p1.length >= 12)          s++;

  const bar  = document.getElementById('strBar');
  const hint = document.getElementById('strHint');
  if (bar)  bar.style.cssText = `width:${s * 20}%;background:${colors[s] || '#E5E7EB'}`;
  if (hint) { hint.textContent = labels[s] || 'Enter a strong password'; hint.style.color = colors[s] || 'var(--muted)'; }

  // Requirements
  const setReq = (id, ok) => {
    const el = document.getElementById(id);
    if (!el) return;
    el.classList.toggle('ok', ok);
    el.querySelector('.dot').style.background = ok ? '#16A34A' : '#CBD5E1';
  };
  setReq('req-len',   p1.length >= 8);
  setReq('req-up',    /[A-Z]/.test(p1));
  setReq('req-num',   /[0-9]/.test(p1));
  setReq('req-match', p1 && p2 && p1 === p2);

  // Match hint
  const mh = document.getElementById('matchHint');
  if (mh) {
    if (!p2)          { mh.textContent = ''; }
    else if (p1===p2) { mh.textContent = '✅ Passwords match'; mh.style.color = '#16A34A'; }
    else              { mh.textContent = '❌ Passwords do not match'; mh.style.color = '#EF4444'; }
  }
}

document.getElementById('resetForm')?.addEventListener('submit', function(e) {
  const p1 = document.getElementById('password').value;
  const p2 = document.getElementById('password2').value;
  if (p1 !== p2 || p1.length < 8) { e.preventDefault(); return; }
  const btn = document.getElementById('resetBtn');
  btn.disabled = true;
  btn.innerHTML = '<span class="spin"></span> Updating password...';
});
</script>
</body>
</html>

<?php include __DIR__ . '/../include/footer.php'; ?>
