<?php
require_once 'includes/config.php';
require_once 'includes/mailer.php';
if (!isset($_SESSION['pending_verify_id'])) {
    header('Location: '.SITE_URL.'/register.php'); exit;
}
$email = $_SESSION['pending_verify_email'] ?? '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    $action = $_POST['action'] ?? '';
    if ($action === 'verify') {
        $otp    = trim($_POST['otp_code'] ?? '');
        $userId = (int)($_SESSION['pending_verify_id'] ?? 0);
        if (!$userId) jsonResponse(['success'=>false,'message'=>'Session expired. Please register again.']);
        if (strlen($otp) !== 6 || !ctype_digit($otp)) jsonResponse(['success'=>false,'message'=>'Please enter the 6-digit OTP code.']);
        $stmt = $pdo->prepare("SELECT * FROM users WHERE id=? AND otp_code=? AND is_verified=0");
        $stmt->execute([$userId, $otp]); $user = $stmt->fetch();
        if (!$user) jsonResponse(['success'=>false,'message'=>'Incorrect OTP. Please check and try again.']);
        if (strtotime($user['otp_expires']) < time()) jsonResponse(['success'=>false,'message'=>'OTP has expired. Please request a new one.','expired'=>true]);
        $pdo->prepare("UPDATE users SET is_verified=1, otp_code=NULL, otp_expires=NULL WHERE id=?")->execute([$userId]);
        unset($_SESSION['pending_verify_id'], $_SESSION['pending_verify_email']);
        $_SESSION['user_id']    = $user['id'];
        $_SESSION['user_name']  = $user['name'];
        $_SESSION['user_email'] = $user['email'];
        createDbSession($user['id']);
        sendManualSignupWelcome($user['email'], $user['name']);
        jsonResponse(['success'=>true,'redirect'=> SITE_URL.'/welcome.php']);
    }
    if ($action === 'resend') {
        $userId = (int)($_SESSION['pending_verify_id'] ?? 0);
        if (!$userId) jsonResponse(['success'=>false,'message'=>'Session expired. Please register again.']);
        $stmt = $pdo->prepare("SELECT * FROM users WHERE id=?"); $stmt->execute([$userId]); $user = $stmt->fetch();
        if (!$user) jsonResponse(['success'=>false,'message'=>'User not found. Please register again.']);
        $otp = str_pad(rand(0,999999), 6, '0', STR_PAD_LEFT);
        $expires = date('Y-m-d H:i:s', strtotime('+'.OTP_EXPIRY_MINUTES.' minutes'));
        $pdo->prepare("UPDATE users SET otp_code=?, otp_expires=? WHERE id=?")->execute([$otp, $expires, $userId]);
        sendOTP($user['email'], $user['name'], $otp);
        jsonResponse(['success'=>true,'message'=>'A new OTP has been sent to your email.']);
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Verify Email — <?= 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">Almost There!</div>
        <h1 class="auth-hero-title">
          Verify your<br>
          <span>email address</span>
        </h1>
        <p class="auth-hero-sub">
          We sent a 6-digit verification code to your email. Enter it to confirm your account and start your study journey.
        </p>

        <div class="auth-features">
          <div class="auth-feature">
            <div class="auth-feature-icon" style="background:rgba(245,158,11,.14)">📧</div>
            <span>Check your inbox (and spam folder)</span>
          </div>
          <div class="auth-feature">
            <div class="auth-feature-icon" style="background:rgba(99,102,241,.14)">⏱️</div>
            <span>Code expires in <?= defined('OTP_EXPIRY_MINUTES') ? OTP_EXPIRY_MINUTES : 10 ?> minutes</span>
          </div>
          <div class="auth-feature">
            <div class="auth-feature-icon" style="background:rgba(16,185,129,.14)">🔄</div>
            <span>Didn't get it? You can resend the code</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>

      <!-- Icon -->
      <div style="width:64px;height:64px;border-radius:20px;background:rgba(99,102,241,.12);border:1px solid rgba(99,102,241,.25);display:flex;align-items:center;justify-content:center;font-size:30px;margin-bottom:22px;position:relative">
        📬
        <div style="position:absolute;top:-4px;right:-4px;width:18px;height:18px;border-radius:50%;background:var(--accent);border:2px solid var(--bg);display:flex;align-items:center;justify-content:center">
          <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="3" stroke-linecap="round"><polyline points="20 6 9 17 4 12"/></svg>
        </div>
      </div>

      <h2 class="auth-form-title">Check your email</h2>
      <p class="auth-form-sub" style="margin-bottom:16px">Enter the 6-digit code we sent to</p>

      <?php if ($email): ?>
      <div class="email-pill">
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
        <?= htmlspecialchars($email) ?>
      </div>
      <?php endif; ?>

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

      <form id="otpForm" novalidate>
        <div class="otp-inputs" id="otpInputs">
          <input class="otp-digit" type="text" maxlength="1" inputmode="numeric" pattern="[0-9]" autocomplete="one-time-code" autofocus>
          <input class="otp-digit" type="text" maxlength="1" inputmode="numeric" pattern="[0-9]">
          <input class="otp-digit" type="text" maxlength="1" inputmode="numeric" pattern="[0-9]">
          <input class="otp-digit" type="text" maxlength="1" inputmode="numeric" pattern="[0-9]">
          <input class="otp-digit" type="text" maxlength="1" inputmode="numeric" pattern="[0-9]">
          <input class="otp-digit" type="text" maxlength="1" inputmode="numeric" pattern="[0-9]">
        </div>

        <button type="submit" id="verifyBtn" class="btn-auth" disabled style="opacity:.5">Verify Email →</button>
      </form>

      <!-- Resend section -->
      <div style="text-align:center;margin-top:24px">
        <p style="font-size:13px;color:var(--ink3);margin-bottom:10px">Didn't receive the code?</p>
        <button id="resendBtn" onclick="resendOTP()" class="btn-bio" style="width:auto;padding:9px 20px;font-size:13px">
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-.07-8.2"/></svg>
          Resend Code
        </button>
        <p id="resendTimer" style="font-size:12px;color:var(--ink3);margin-top:8px;display:none"></p>
      </div>

      <div class="auth-foot" style="margin-top:20px">
        Wrong account? <a href="<?= SITE_URL ?>/register">Start over</a>
      </div>

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

<script>
(function(){
  const digits = document.querySelectorAll('.otp-digit');
  const form   = document.getElementById('otpForm');
  const btn    = document.getElementById('verifyBtn');
  const msgBox = document.getElementById('msgBox');

  function showMsg(msg, type) {
    authToast(msg, type === 'error' ? 'err' : 'ok');
  }
  function getOTP() {
    return Array.from(digits).map(d => d.value).join('');
  }
  function checkComplete() {
    const complete = getOTP().length === 6 && /^\d{6}$/.test(getOTP());
    btn.disabled = !complete;
    btn.style.opacity = complete ? '1' : '.5';
  }

  // OTP input behaviour
  digits.forEach((inp, i) => {
    inp.addEventListener('input', function(e) {
      const v = this.value.replace(/\D/g,'');
      this.value = v ? v[0] : '';
      if (this.value) { this.classList.add('filled'); if (i < 5) digits[i+1].focus(); }
      else this.classList.remove('filled');
      checkComplete();
    });
    inp.addEventListener('keydown', function(e) {
      if (e.key === 'Backspace' && !this.value && i > 0) { digits[i-1].focus(); digits[i-1].value = ''; digits[i-1].classList.remove('filled'); checkComplete(); }
    });
    inp.addEventListener('paste', function(e) {
      e.preventDefault();
      const pasted = (e.clipboardData || window.clipboardData).getData('text').replace(/\D/g,'').slice(0,6);
      pasted.split('').forEach((ch, j) => { if (digits[j]) { digits[j].value = ch; digits[j].classList.add('filled'); } });
      if (pasted.length < 6 && digits[pasted.length]) digits[pasted.length].focus();
      else if (digits[5]) digits[5].focus();
      checkComplete();
    });
  });

  form.addEventListener('submit', async function(e) {
    e.preventDefault();
    const otp = getOTP();
    if (otp.length !== 6) return;
    btn.disabled = true; btn.innerHTML = '<span class="spinner"></span> Verifying…';
    msgBox.style.display = 'none';
    const fd = new FormData(); fd.append('action','verify'); fd.append('otp_code', otp);
    try {
      const res = await fetch(location.href, { method:'POST', body:fd, headers:{'X-Requested-With':'XMLHttpRequest'} });
      const data = await res.json();
      if (data.success) {
        showMsg('Email verified! Redirecting to your dashboard…','success');
        btn.innerHTML = '✓ Verified!';
        digits.forEach(d => { d.style.borderColor = 'var(--success)'; d.style.color = '#6ee7b7'; });
        setTimeout(() => { window.location.href = data.redirect; }, 1000);
      } else {
        showMsg(data.message || 'Incorrect OTP. Please try again.','error');
        btn.disabled = false; btn.innerHTML = 'Verify Email →';
        digits.forEach(d => { d.style.borderColor = 'rgba(239,68,68,.6)'; d.style.animation = 'shake .3s ease'; });
        setTimeout(() => { digits.forEach(d => { d.style.borderColor=''; d.style.animation=''; d.value=''; d.classList.remove('filled'); }); digits[0].focus(); checkComplete(); }, 600);
        if (data.expired) startResendTimer(0);
      }
    } catch(err) {
      showMsg('Connection error. Please try again.','error');
      btn.disabled = false; btn.innerHTML = 'Verify Email →';
    }
  });

  let resendCooldown = 0;
  function startResendTimer(secs) {
    resendCooldown = secs;
    const resendBtn = document.getElementById('resendBtn');
    const timerEl  = document.getElementById('resendTimer');
    if (secs <= 0) { resendBtn.disabled = false; timerEl.style.display = 'none'; return; }
    resendBtn.disabled = true;
    timerEl.style.display = 'block';
    const iv = setInterval(() => {
      resendCooldown--;
      timerEl.textContent = 'Resend available in ' + resendCooldown + 's';
      if (resendCooldown <= 0) { clearInterval(iv); resendBtn.disabled = false; timerEl.style.display = 'none'; }
    }, 1000);
    timerEl.textContent = 'Resend available in ' + secs + 's';
  }

  window.resendOTP = async function() {
    const resendBtn = document.getElementById('resendBtn');
    resendBtn.disabled = true; resendBtn.innerHTML = '<span class="spinner"></span> Sending…';
    const fd = new FormData(); fd.append('action','resend');
    try {
      const res = await fetch(location.href, { method:'POST', body:fd, headers:{'X-Requested-With':'XMLHttpRequest'} });
      const data = await res.json();
      if (data.success) {
        showMsg(data.message,'success');
        resendBtn.innerHTML = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-.07-8.2"/></svg> Resend Code';
        startResendTimer(60);
      } else {
        showMsg(data.message||'Failed to resend. Try again.','error');
        resendBtn.disabled = false;
        resendBtn.innerHTML = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-.07-8.2"/></svg> Resend Code';
      }
    } catch(err) {
      showMsg('Connection error. Please try again.','error');
      resendBtn.disabled = false;
    }
  };
})();
</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>