<?php
require_once 'includes/config.php';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    require_once 'includes/mailer.php';
    $email = filter_var(trim($_POST['email'] ?? ''), FILTER_SANITIZE_EMAIL);
    if (!filter_var($email, FILTER_VALIDATE_EMAIL))
        jsonResponse(['success'=>false,'message'=>'Please enter a valid email address.']);
    $stmt = $pdo->prepare("SELECT * FROM users WHERE email=? AND is_verified=1");
    $stmt->execute([$email]); $user = $stmt->fetch();
    if ($user) {
        $token   = bin2hex(random_bytes(32));
        $expires = date('Y-m-d H:i:s', time() + (RESET_EXPIRY_HOURS * 3600));
        $pdo->prepare("UPDATE users SET reset_token=?, reset_expires=? WHERE id=?")->execute([$token,$expires,$user['id']]);
        $resetUrl = SITE_URL . '/reset-password.php?token=' . urlencode($token);
        sendPasswordReset($email, $user['name'], $resetUrl);
    }
    jsonResponse(['success'=>true,'message'=>'If an account exists with that email, a reset link has been sent.']);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Forgot Password — <?= SITE_NAME ?></title>
<link rel="icon" type="image/png" href="https://studytrack.edurx.icu/studytrack/images/studytrack.png">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Sora:wght@400;600;700;800;900&family=DM+Sans:ital,wght@0,400;0,500;0,600;1,400&display=swap" rel="stylesheet">
<link rel="stylesheet" href="<?= SITE_URL ?>/assets/auth-shared.css">
<style>
/* ── Scroll fix: left fixed, right scrolls ── */
html, body { height: 100%; overflow: hidden; }
body { height: 100vh; overflow: hidden; }
.auth-layout { height: 100vh; overflow: hidden; }
.auth-left { position: sticky; top: 0; height: 100vh; overflow: hidden; }
.auth-right {
  height: 100vh; overflow-y: auto; overflow-x: hidden;
  display: flex; align-items: flex-start; justify-content: center;
  padding: 40px 40px;
  scrollbar-width: thin; scrollbar-color: rgba(99,102,241,.3) transparent;
}
.auth-right::-webkit-scrollbar { width: 5px; }
.auth-right::-webkit-scrollbar-thumb { background: rgba(99,102,241,.3); border-radius: 99px; }
.auth-form-wrap { width: 100%; max-width: 420px; margin: auto 0; }

/* ── Mobile: allow normal page scroll ── */
@media (max-width: 900px) {
  html, body { height: auto; overflow: auto; }
  body { height: auto; overflow-x: hidden; }
  .auth-layout { height: auto; overflow: visible; display: block; }
  .auth-left { display: none; }
  .auth-right {
    height: auto; min-height: 100vh;
    overflow: visible;
    padding: 32px 20px 40px;
  }
  .auth-form-wrap { margin: 0 auto; }
}

/* ── Toast ── */
#auth-toast-wrap {
  position: fixed; top: 20px; left: 50%; transform: translateX(-50%);
  z-index: 99999; display: flex; flex-direction: column; align-items: center;
  gap: 10px; pointer-events: none; width: 100%; max-width: 460px; padding: 0 16px;
}
.auth-toast {
  width: 100%; display: flex; align-items: flex-start; gap: 12px;
  padding: 14px 16px; border-radius: 14px; font-size: 13px; font-weight: 500;
  line-height: 1.5; pointer-events: auto;
  box-shadow: 0 8px 32px rgba(0,0,0,.45); backdrop-filter: blur(12px);
  animation: toastIn .35s cubic-bezier(.34,1.56,.64,1) both;
  cursor: pointer; border: 1px solid; position: relative; overflow: hidden;
}
.auth-toast::before { content:''; position:absolute; top:0; left:0; right:0; height:2px; border-radius:14px 14px 0 0; }
.auth-toast.hiding { animation: toastOut .3s ease forwards; }
.auth-toast.err { background: rgba(15,5,5,.95); border-color: rgba(239,68,68,.35); color: #fca5a5; }
.auth-toast.err::before { background: linear-gradient(90deg,#ef4444,#f87171); }
.auth-toast.ok  { background: rgba(2,12,10,.95);  border-color: rgba(16,185,129,.35); color: #6ee7b7; }
.auth-toast.ok::before  { background: linear-gradient(90deg,#10b981,#34d399); }
.auth-toast-icon { flex-shrink:0; margin-top:1px; }
.auth-toast-body { flex:1; }
.auth-toast-close { flex-shrink:0; opacity:.5; font-size:13px; cursor:pointer; padding:2px; transition:opacity .15s; }
.auth-toast-close:hover { opacity:1; }
.auth-toast-progress { position:absolute; bottom:0; left:0; height:2px; border-radius:0 0 14px 14px; animation:toastProgress linear forwards; }
.auth-toast.err .auth-toast-progress { background:rgba(239,68,68,.5); }
.auth-toast.ok  .auth-toast-progress { background:rgba(16,185,129,.5); }
@keyframes toastIn { from{opacity:0;transform:translateY(-16px) scale(.94)} to{opacity:1;transform:translateY(0) scale(1)} }
@keyframes toastOut { from{opacity:1;transform:translateY(0) scale(1);max-height:100px} to{opacity:0;transform:translateY(-10px) scale(.94);max-height:0} }
@keyframes toastProgress { from{width:100%} to{width:0%} }
.auth-alert { display: none !important; }
</style>
</head>
<body>

<!-- Toast container -->
<div id="auth-toast-wrap"></div>

<div class="auth-layout">

  <!-- ── LEFT PANEL ───────────────────────── -->
  <div class="auth-left">
    <div class="auth-left-grid"></div>
    <div class="auth-left-content">

      <div class="auth-logo">
        <img class="auth-logo-img" src="https://studytrack.edurx.icu/studytrack/images/studytrack.png" alt="StudyTrack">
        <div>
          <div class="auth-logo-name">StudyTrack</div>
          <div class="auth-logo-tag">by EduRX</div>
        </div>
      </div>

      <div class="auth-hero">
        <div class="auth-hero-label">Account Recovery</div>
        <h1 class="auth-hero-title">
          Forgot your<br>
          <span>password?</span>
        </h1>
        <p class="auth-hero-sub">
          No worries — it happens to the best of us. Enter your email and we'll send you a secure link to reset your password instantly.
        </p>

        <div class="auth-features">
          <div class="auth-feature">
            <div class="auth-feature-icon" style="background:rgba(99,102,241,.14)">📧</div>
            <span>Secure reset link sent to your email</span>
          </div>
          <div class="auth-feature">
            <div class="auth-feature-icon" style="background:rgba(6,182,212,.14)">⏱️</div>
            <span>Link expires in <?= defined('RESET_EXPIRY_HOURS') ? RESET_EXPIRY_HOURS : 1 ?> hour for security</span>
          </div>
          <div class="auth-feature">
            <div class="auth-feature-icon" style="background:rgba(16,185,129,.14)">🔐</div>
            <span>Your data is always safe with us</span>
          </div>
        </div>
      </div>



    </div>
  </div>

  <!-- ── RIGHT PANEL ──────────────────────── -->
  <div class="auth-right">
    <div class="auth-form-wrap">

      <div class="auth-mobile-logo">
        <img src="https://studytrack.edurx.icu/studytrack/images/studytrack.png" alt="StudyTrack" style="width:34px;height:34px;border-radius:10px">
        <span style="font-family:'Sora',sans-serif;font-size:18px;font-weight:800;background:linear-gradient(135deg,#e0e7ff,#a5b4fc);-webkit-background-clip:text;-webkit-text-fill-color:transparent">StudyTrack</span>
      </div>

      <a href="<?= SITE_URL ?>/login" class="auth-back">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><polyline points="15 18 9 12 15 6"/></svg>
        Back to Sign In
      </a>

      <!-- Icon -->
      <div style="width:60px;height:60px;border-radius:18px;background:rgba(99,102,241,.12);border:1px solid rgba(99,102,241,.25);display:flex;align-items:center;justify-content:center;font-size:28px;margin-bottom:22px">🔑</div>

      <h2 class="auth-form-title">Reset your password</h2>
      <p class="auth-form-sub">Enter your registered email address and we'll send you a reset link.</p>

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

      <div id="formSection">
        <form id="forgotForm" novalidate>
          <div class="f-group" style="margin-bottom:22px">
            <label class="f-label">Email Address</label>
            <div class="f-input-wrap">
              <span class="f-icon">✉️</span>
              <input type="email" name="email" class="f-input" placeholder="you@email.com" required autofocus>
            </div>
          </div>
          <button type="submit" id="forgotBtn" class="btn-auth">Send Reset Link →</button>
        </form>
      </div>

      <!-- Success state (shown after submit) -->
      <div id="successSection" style="display:none;text-align:center;padding:20px 0">
        <div style="font-size:52px;margin-bottom:16px;animation:authFadeUp .4s ease both">📬</div>
        <div style="font-size:18px;font-weight:700;color:var(--ink);margin-bottom:8px;font-family:'Sora',sans-serif">Check your inbox!</div>
        <div style="font-size:14px;color:var(--ink3);line-height:1.7;margin-bottom:24px">
          We've sent a password reset link to your email address. Please check your spam folder too.
        </div>
        <a href="<?= SITE_URL ?>/login" class="btn-auth" style="display:inline-flex;align-items:center;justify-content:center;gap:8px;text-decoration:none">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><polyline points="15 18 9 12 15 6"/></svg>
          Back to Sign In
        </a>
      </div>

      <div class="auth-foot" id="footLink">
        Remember your password? <a href="<?= SITE_URL ?>/login">Sign In</a>
      </div>

    </div>
  </div>
</div>

<script>
(function(){
  const form = document.getElementById('forgotForm');
  const msgBox = document.getElementById('msgBox');
  const btn = document.getElementById('forgotBtn');
  function showMsg(msg, type) {
    authToast(msg, type === 'error' ? 'err' : 'ok');
  }
  form.addEventListener('submit', async function(e) {
    e.preventDefault();
    btn.disabled = true; btn.innerHTML = '<span class="spinner"></span> Sending…';
    msgBox.style.display = 'none';
    try {
      const res = await fetch(location.href, { method:'POST', body:new FormData(form), headers:{'X-Requested-With':'XMLHttpRequest'} });
      const data = await res.json();
      if (data.success) {
        document.getElementById('formSection').style.display = 'none';
        document.getElementById('footLink').style.display = 'none';
        document.getElementById('successSection').style.display = 'block';
      } else {
        showMsg(data.message||'Something went wrong. Please try again.','error');
        btn.disabled = false; btn.innerHTML = 'Send Reset Link →';
      }
    } catch(err) {
      showMsg('Connection error. Please try again.','error');
      btn.disabled = false; btn.innerHTML = 'Send Reset Link →';
    }
  });
})();
</script>
<script>
/* ── Toast System ─────────────────────────────────────────── */
(function() {
  var wrap = document.getElementById('auth-toast-wrap');
  var DURATION = 4500;

  window.authToast = function(msg, type) {
    type = type || 'err';
    var toast = document.createElement('div');
    toast.className = 'auth-toast ' + type;

    var icon = type === 'ok'
      ? '<svg class="auth-toast-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#34d399" stroke-width="2.5" stroke-linecap="round"><polyline points="20 6 9 17 4 12"/></svg>'
      : '<svg class="auth-toast-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#f87171" stroke-width="2.5" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>';

    toast.innerHTML = icon
      + '<div class="auth-toast-body">' + msg + '</div>'
      + '<div class="auth-toast-close" onclick="this.parentElement._dismiss()">&#10005;</div>'
      + '<div class="auth-toast-progress" style="animation-duration:' + DURATION + 'ms"></div>';

    toast._dismiss = function() {
      if (toast._dismissed) return;
      toast._dismissed = true;
      clearTimeout(toast._timer);
      toast.classList.add('hiding');
      setTimeout(function() { if (toast.parentNode) toast.parentNode.removeChild(toast); }, 320);
    };

    wrap.appendChild(toast);
    toast._timer = setTimeout(function() { toast._dismiss(); }, DURATION);
    toast.addEventListener('click', function(e) {
      if (!e.target.classList.contains('auth-toast-close')) toast._dismiss();
    });
  };
})();
</script>
</body>
</html>