<?php
// reset-password-verify.php — Step 2 of the password-reset flow.
//
// The user enters the 6-digit OTP they received. We POST it (via AJAX) to
// verify-otp.php (purpose=password_reset). On success, verify-otp.php stores
// $_SESSION['reset_email'] and $_SESSION['reset_email_verified'], then this
// page redirects to reset-password.php to choose a new password.

session_start();

// Already logged in → no need to reset.
if (isset($_SESSION['user_id']) && ($_SESSION['role'] ?? '') === 'customer') {
    header('Location: dashboard.php');
    exit;
}

// Already verified in this session → skip straight to the new-password step.
if (!empty($_SESSION['reset_email_verified'])) {
    header('Location: reset-password.php');
    exit;
}

$email = trim($_GET['email'] ?? '');
if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    header('Location: forgot-password.php');
    exit;
}
$emailSafe = htmlspecialchars($email, ENT_QUOTES, 'UTF-8');

const OTP_RESEND_COOLDOWN = 60; // seconds, must match send-otp.php
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>Verify Code — Dabil</title>
<style>
  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

  :root {
    --primary:      #2563EB;
    --primary-dark: #1D4ED8;
    --primary-bg:   #EFF6FF;
    --text:         #0F172A;
    --text-muted:   #64748B;
    --text-light:   #94A3B8;
    --bg:           #F4F6FB;
    --card-border:  #E2E8F0;
    --field-bg:     #FFFFFF;
    --radius:       16px;
  }

  html, body {
    height: 100%;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', sans-serif;
    background: var(--bg);
    overflow-x: hidden;
    color: var(--text);
  }

  .page {
    display: flex;
    flex-direction: column;
    min-height: 100%;
    max-width: 430px;
    margin: 0 auto;
    background: var(--bg);
  }

  /* ── Top bar ── */
  .topbar {
    display: flex;
    align-items: center;
    gap: 14px;
    padding: calc(env(safe-area-inset-top, 0px) + 18px) 20px 16px;
    background: #fff;
    border-bottom: 1px solid var(--card-border);
  }
  .back-btn {
    display: flex; align-items: center; justify-content: center;
    width: 36px; height: 36px;
    border-radius: 50%;
    color: var(--primary); text-decoration: none; flex-shrink: 0;
    -webkit-tap-highlight-color: transparent;
    transition: background .15s;
  }
  .back-btn:active { background: var(--primary-bg); }
  .topbar h1 { font-size: 1.05rem; font-weight: 700; color: var(--text); }

  /* ── Content ── */
  .content {
    flex: 1; display: flex; flex-direction: column;
    padding: 32px 20px;
  }

  /* ── Icon pill ── */
  .icon-pill {
    width: 64px; height: 64px; border-radius: 20px;
    background: var(--primary-bg);
    display: flex; align-items: center; justify-content: center;
    margin-bottom: 20px; color: var(--primary);
  }

  /* ── Headline ── */
  .headline { margin-bottom: 32px; }
  .headline h2 {
    font-size: 1.55rem; font-weight: 800; letter-spacing: -.02em;
    line-height: 1.2; color: var(--primary); margin-bottom: 8px;
  }
  .headline p { font-size: .9rem; color: var(--text-muted); line-height: 1.6; }
  .headline p strong { color: var(--text); font-weight: 600; }

  /* ── OTP boxes ── */
  .otp-row {
    display: flex; gap: 10px; justify-content: center;
    margin-bottom: 24px;
  }
  .otp-digit {
    width: 48px; height: 58px;
    border: 1.5px solid var(--card-border);
    border-radius: 14px;
    background: var(--field-bg);
    font-size: 1.5rem; font-weight: 700;
    text-align: center; color: var(--text);
    outline: none; caret-color: transparent;
    transition: border-color .15s, box-shadow .15s;
    font-family: inherit;
    -webkit-appearance: none;
  }
  .otp-digit:focus {
    border-color: var(--primary);
    box-shadow: 0 0 0 3px rgba(37,99,235,.14);
  }
  .otp-digit.filled { border-color: var(--primary); }

  /* ── Feedback ── */
  .msg {
    font-size: .85rem; border-radius: 12px;
    padding: 12px 14px; margin-bottom: 18px;
    text-align: center; display: none;
  }
  .msg.error { background: #FEF2F2; border: 1px solid #FECACA; color: #B91C1C; }
  .msg.success { background: #F0FDF4; border: 1px solid #BBF7D0; color: #15803D; }

  /* ── Submit button ── */
  .btn-submit {
    display: flex; align-items: center; justify-content: center; gap: 8px;
    width: 100%; padding: 17px;
    background: var(--primary); color: #fff;
    font-size: 1rem; font-weight: 700;
    border: none; border-radius: 999px; cursor: pointer;
    box-shadow: 0 4px 20px rgba(37,99,235,.32);
    transition: background .15s, transform .12s, opacity .15s;
    -webkit-tap-highlight-color: transparent;
  }
  .btn-submit:active { background: var(--primary-dark); transform: scale(.98); }
  .btn-submit:disabled { opacity: .6; cursor: not-allowed; transform: none; }

  .spinner {
    width: 18px; height: 18px;
    border: 2.5px solid rgba(255,255,255,.4);
    border-top-color: #fff;
    border-radius: 50%;
    animation: spin .7s linear infinite;
    display: none;
  }
  @keyframes spin { to { transform: rotate(360deg); } }

  /* ── Resend ── */
  .resend-row {
    text-align: center; margin-top: 20px;
    font-size: .875rem; color: var(--text-muted);
  }
  #resendBtn {
    background: none; border: none; padding: 0;
    color: var(--primary); font-weight: 600; font-size: .875rem;
    cursor: pointer; font-family: inherit;
    -webkit-tap-highlight-color: transparent;
  }
  #resendBtn:disabled { color: var(--text-light); cursor: default; }

  /* ── Animations ── */
  .anim-up { animation: slideUp .5s cubic-bezier(.22,1,.36,1) both; }
  .anim-up.d1 { animation-delay: .05s; }
  .anim-up.d2 { animation-delay: .12s; }
  .anim-up.d3 { animation-delay: .19s; }
  .anim-up.d4 { animation-delay: .26s; }

  @keyframes slideUp {
    from { opacity: 0; transform: translateY(20px); }
    to   { opacity: 1; transform: translateY(0); }
  }
  @media (prefers-reduced-motion: reduce) {
    *, .anim-up { animation: none !important; }
  }
</style>
</head>
<body>

<div class="page">

  <!-- Top bar -->
  <div class="topbar">
    <a href="forgot-password.php" class="back-btn" aria-label="Back">
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round">
        <polyline points="15 18 9 12 15 6"/>
      </svg>
    </a>
    <h1>Verify Code</h1>
  </div>

  <!-- Content -->
  <div class="content">

    <!-- Icon -->
    <div class="icon-pill anim-up d1">
      <svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="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>
    </div>

    <!-- Headline -->
    <div class="headline anim-up d2">
      <h2>Check Your Email</h2>
      <p>We sent a 6-digit code to<br><strong><?= $emailSafe ?></strong>.<br>Enter it below to continue.</p>
    </div>

    <!-- Messages -->
    <div class="msg error"   id="msgError"   role="alert"></div>
    <div class="msg success" id="msgSuccess" role="status"></div>

    <!-- OTP boxes -->
    <div class="otp-row anim-up d3" id="otpRow">
      <input class="otp-digit" type="text" inputmode="numeric" maxlength="1" aria-label="Digit 1">
      <input class="otp-digit" type="text" inputmode="numeric" maxlength="1" aria-label="Digit 2">
      <input class="otp-digit" type="text" inputmode="numeric" maxlength="1" aria-label="Digit 3">
      <input class="otp-digit" type="text" inputmode="numeric" maxlength="1" aria-label="Digit 4">
      <input class="otp-digit" type="text" inputmode="numeric" maxlength="1" aria-label="Digit 5">
      <input class="otp-digit" type="text" inputmode="numeric" maxlength="1" aria-label="Digit 6">
    </div>

    <!-- Submit -->
    <button type="button" class="btn-submit anim-up d4" id="verifyBtn" onclick="verifyOtp()">
      <div class="spinner" id="spinner"></div>
      <span id="btnLabel">Verify Code</span>
    </button>

    <!-- Resend -->
    <div class="resend-row anim-up d4">
      Didn't get it?
      <button type="button" id="resendBtn" onclick="resendOtp()" disabled>
        Resend in <span id="countdown"><?= OTP_RESEND_COOLDOWN ?></span>s
      </button>
    </div>

  </div><!-- /.content -->

</div><!-- /.page -->

<script>
  const EMAIL    = <?= json_encode($email) ?>;
  const COOLDOWN = <?= OTP_RESEND_COOLDOWN ?>;

  const digits    = Array.from(document.querySelectorAll('.otp-digit'));
  const verifyBtn = document.getElementById('verifyBtn');
  const spinner   = document.getElementById('spinner');
  const btnLabel  = document.getElementById('btnLabel');
  const msgError  = document.getElementById('msgError');
  const msgSuccess= document.getElementById('msgSuccess');
  const resendBtn = document.getElementById('resendBtn');
  const countdown = document.getElementById('countdown');

  // ── Auto-focus first box ──
  digits[0].focus();

  // ── Input handling: auto-advance, backspace, paste ──
  digits.forEach((el, i) => {
    el.addEventListener('input', () => {
      el.value = el.value.replace(/\D/g, '').slice(-1);
      el.classList.toggle('filled', el.value !== '');
      if (el.value && i < digits.length - 1) digits[i + 1].focus();
      if (getOtp().length === 6) verifyOtp();
    });

    el.addEventListener('keydown', e => {
      if (e.key === 'Backspace' && !el.value && i > 0) {
        digits[i - 1].value = '';
        digits[i - 1].classList.remove('filled');
        digits[i - 1].focus();
      }
    });

    el.addEventListener('paste', e => {
      e.preventDefault();
      const text = (e.clipboardData || window.clipboardData)
                      .getData('text').replace(/\D/g, '').slice(0, 6);
      text.split('').forEach((ch, j) => {
        if (digits[j]) {
          digits[j].value = ch;
          digits[j].classList.add('filled');
        }
      });
      const next = Math.min(text.length, digits.length - 1);
      digits[next].focus();
      if (text.length === 6) verifyOtp();
    });
  });

  function getOtp() { return digits.map(d => d.value).join(''); }

  function setLoading(on) {
    verifyBtn.disabled    = on;
    spinner.style.display = on ? 'block' : 'none';
    btnLabel.textContent  = on ? 'Verifying…' : 'Verify Code';
  }

  function showError(msg) {
    msgError.textContent   = msg;
    msgError.style.display = 'block';
    msgSuccess.style.display = 'none';
    // Shake the OTP row
    const row = document.getElementById('otpRow');
    row.style.animation = 'none';
    void row.offsetWidth;
    row.style.animation = 'shake .4s ease';
  }

  function showSuccess(msg) {
    msgSuccess.textContent   = msg;
    msgSuccess.style.display = 'block';
    msgError.style.display   = 'none';
  }

  async function verifyOtp() {
    const otp = getOtp();
    if (otp.length < 6) { showError('Please enter all 6 digits.'); return; }

    msgError.style.display   = 'none';
    msgSuccess.style.display = 'none';
    setLoading(true);

    try {
      const fd = new FormData();
      fd.append('email',    EMAIL);
      fd.append('otp_code', otp);
      fd.append('purpose',  'password_reset');

      const res  = await fetch('verify-otp.php', { method: 'POST', body: fd });
      const data = await res.json();

      if (res.ok) {
        showSuccess('Code verified! Redirecting…');
        setTimeout(() => { window.location.href = 'reset-password.php'; }, 600);
        return;
      }

      showError(data.message || 'Incorrect code. Please try again.');
      digits.forEach(d => { d.value = ''; d.classList.remove('filled'); });
      digits[0].focus();

    } catch (e) {
      showError('Network error. Please try again.');
    } finally {
      setLoading(false);
    }
  }

  // ── Resend cooldown timer ──
  let timer = COOLDOWN;
  const tick = setInterval(() => {
    timer--;
    if (timer <= 0) {
      clearInterval(tick);
      resendBtn.disabled = false;
      resendBtn.textContent = 'Resend code';
    } else {
      countdown.textContent = timer;
    }
  }, 1000);

  async function resendOtp() {
    resendBtn.disabled    = true;
    resendBtn.textContent = 'Sending…';
    msgError.style.display   = 'none';
    msgSuccess.style.display = 'none';

    try {
      const fd = new FormData();
      fd.append('email',   EMAIL);
      fd.append('purpose', 'password_reset');

      const res  = await fetch('send-otp.php', { method: 'POST', body: fd });
      const data = await res.json();

      if (res.ok) {
        showSuccess('A new code has been sent to ' + EMAIL);
        // Restart countdown
        timer = COOLDOWN;
        countdown.textContent = timer;
        resendBtn.innerHTML = 'Resend in <span id="countdown">' + timer + '</span>s';
        const newCountdown = resendBtn.querySelector('span');
        const newTick = setInterval(() => {
          timer--;
          if (timer <= 0) {
            clearInterval(newTick);
            resendBtn.disabled = false;
            resendBtn.textContent = 'Resend code';
          } else {
            newCountdown.textContent = timer;
          }
        }, 1000);
      } else {
        msgError.textContent   = data.message || 'Could not resend code. Please try again.';
        msgError.style.display = 'block';
        resendBtn.disabled = false;
        resendBtn.textContent = 'Resend code';
      }
    } catch (e) {
      msgError.textContent   = 'Network error. Please try again.';
      msgError.style.display = 'block';
      resendBtn.disabled = false;
      resendBtn.textContent = 'Resend code';
    }
  }

  // Shake keyframe (inline so no external CSS file needed)
  const style = document.createElement('style');
  style.textContent = `@keyframes shake {
    0%,100%{transform:translateX(0)}
    20%{transform:translateX(-6px)}
    40%{transform:translateX(6px)}
    60%{transform:translateX(-4px)}
    80%{transform:translateX(4px)}
  }`;
  document.head.appendChild(style);
</script>

</body>
</html>
