<?php
// verify-email.php — Dabil "Enter Verification Code" screen
// Step 2 of the email signup flow: user enters the 6-digit code sent by
// send-otp.php. On success, verify-otp.php stores $_SESSION['signup_email']
// and this page redirects to profile-setup.php.

session_start();

// If already signed in, skip straight to the dashboard.
if (isset($_SESSION['user_id']) && ($_SESSION['role'] ?? '') === 'customer') {
    header('Location: dashboard.php');
    exit;
}

// If this step's email has already been verified, continue the flow.
if (!empty($_SESSION['signup_email_verified']) && !empty($_SESSION['signup_email'])) {
    header('Location: profile-setup.php');
    exit;
}

$email = trim($_GET['email'] ?? '');
if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    header('Location: signup-email.php');
    exit;
}

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 Email — 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;
    --radius-field: 14px;
  }

  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);
    position: relative;
  }

  /* ── 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: 28px 20px;
  }

  /* ── Headline ── */
  .headline { padding: 4px 0 26px; }

  .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.55;
  }

  .headline p strong { color: var(--text); font-weight: 700; }

  /* ── OTP input boxes ── */
  .otp-row {
    display: flex;
    gap: 10px;
    margin-bottom: 22px;
  }

  .otp-row input {
    flex: 1;
    width: 100%;
    aspect-ratio: 1 / 1;
    text-align: center;
    font-size: 1.4rem;
    font-weight: 700;
    font-family: inherit;
    color: var(--text);
    border: 1px solid var(--card-border);
    background: var(--field-bg);
    border-radius: var(--radius-field);
    outline: none;
    transition: border-color .15s, box-shadow .15s;
    box-shadow: 0 1px 4px rgba(15,23,42,.03);
  }

  .otp-row input:focus {
    border-color: var(--primary);
    box-shadow: 0 0 0 3px rgba(37,99,235,.12);
  }

  /* ── Messages ── */
  .form-error, .form-info, .form-success {
    font-size: .85rem;
    border-radius: 12px;
    padding: 12px 14px;
    margin-bottom: 18px;
    text-align: center;
  }

  .form-error {
    background: #FEF2F2;
    border: 1px solid #FECACA;
    color: #B91C1C;
  }

  .form-success {
    background: #F0FDF4;
    border: 1px solid #BBF7D0;
    color: #15803D;
  }

  /* ── Resend row ── */
  .resend-row {
    text-align: center;
    font-size: .85rem;
    color: var(--text-muted);
    margin-bottom: 26px;
  }

  .resend-row button {
    background: none;
    border: none;
    color: var(--primary);
    font-weight: 700;
    font-size: .85rem;
    font-family: inherit;
    cursor: pointer;
    padding: 0;
    -webkit-tap-highlight-color: transparent;
  }

  .resend-row button:disabled {
    color: var(--text-light);
    cursor: default;
  }

  /* ── Submit button ── */
  .btn-submit {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    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: .65; cursor: default; transform: none; }

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

  /* ── Legal / footer ── */
  .legal {
    margin-top: auto;
    text-align: center;
    font-size: .8rem;
    color: var(--text-muted);
    line-height: 1.6;
    padding: 32px 8px calc(env(safe-area-inset-bottom, 0px) + 28px);
  }

  .legal a { color: var(--primary); text-decoration: none; font-weight: 600; }

  /* ── 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; }

  @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="signup-email.php" class="back-btn" aria-label="Go 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 Email</h1>
  </div>

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

    <!-- Headline -->
    <div class="headline anim-up d1">
      <h2>Check your inbox</h2>
      <p>We've sent a 6-digit code to <strong><?php echo htmlspecialchars($email, ENT_QUOTES, 'UTF-8'); ?></strong>. Enter it below to verify your email.</p>
    </div>

    <div id="formMessage"></div>

    <!-- Form -->
    <form id="otpForm" autocomplete="off">
      <div class="otp-row anim-up d2">
        <input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="otp-digit" required>
        <input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="otp-digit" required>
        <input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="otp-digit" required>
        <input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="otp-digit" required>
        <input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="otp-digit" required>
        <input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="otp-digit" required>
      </div>

      <div class="resend-row anim-up d2">
        <span id="resendText">Resend code in <span id="cooldown">60</span>s</span>
        <button type="button" id="resendBtn" style="display:none;">Resend code</button>
      </div>

      <button type="submit" class="btn-submit anim-up d3" id="submitBtn">
        <span id="btnTxt">Verify Email</span>
        <div class="spin" id="spinner"></div>
      </button>
    </form>

    <!-- Sign in -->
    <p class="legal anim-up d3">
      Wrong email? <a href="signup-email.php">Use a different address</a>
    </p>

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

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

<script>
const EMAIL = <?php echo json_encode($email); ?>;
const RESEND_COOLDOWN = <?php echo (int) OTP_RESEND_COOLDOWN; ?>;

const otpForm   = document.getElementById('otpForm');
const digits    = Array.from(document.querySelectorAll('.otp-digit'));
const submitBtn = document.getElementById('submitBtn');
const btnTxt    = document.getElementById('btnTxt');
const spinner   = document.getElementById('spinner');
const msgBox    = document.getElementById('formMessage');
const resendBtn  = document.getElementById('resendBtn');
const resendText = document.getElementById('resendText');
const cooldownEl = document.getElementById('cooldown');

function showMessage(html, type) {
  msgBox.innerHTML = '<div class="form-' + type + ' anim-up">' + html + '</div>';
}
function clearMessage() { msgBox.innerHTML = ''; }

function setLoading(isLoading) {
  submitBtn.disabled = isLoading;
  btnTxt.style.display  = isLoading ? 'none' : 'inline';
  spinner.style.display = isLoading ? 'block' : 'none';
}

// --- OTP box behaviour: auto-advance, backspace, paste ---
digits.forEach((input, idx) => {
  input.addEventListener('input', () => {
    input.value = input.value.replace(/[^0-9]/g, '').slice(0, 1);
    if (input.value && idx < digits.length - 1) {
      digits[idx + 1].focus();
    }
  });
  input.addEventListener('keydown', (e) => {
    if (e.key === 'Backspace' && !input.value && idx > 0) {
      digits[idx - 1].focus();
    }
  });
  input.addEventListener('paste', (e) => {
    e.preventDefault();
    const text = (e.clipboardData.getData('text') || '').replace(/[^0-9]/g, '').slice(0, digits.length);
    text.split('').forEach((ch, i) => { if (digits[i]) digits[i].value = ch; });
    const next = Math.min(text.length, digits.length - 1);
    digits[next].focus();
  });
});
digits[0].focus();

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

// --- Resend cooldown timer ---
let cooldownRemaining = RESEND_COOLDOWN;
let cooldownTimer = null;

function startCooldown() {
  cooldownRemaining = RESEND_COOLDOWN;
  resendBtn.style.display  = 'none';
  resendText.style.display = 'inline';
  cooldownEl.textContent = cooldownRemaining;

  if (cooldownTimer) clearInterval(cooldownTimer);
  cooldownTimer = setInterval(() => {
    cooldownRemaining--;
    if (cooldownRemaining <= 0) {
      clearInterval(cooldownTimer);
      resendText.style.display = 'none';
      resendBtn.style.display  = 'inline';
    } else {
      cooldownEl.textContent = cooldownRemaining;
    }
  }, 1000);
}
startCooldown();

resendBtn.addEventListener('click', async () => {
  clearMessage();
  resendBtn.disabled = true;
  try {
    const res = await fetch('send-otp.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: new URLSearchParams({ email: EMAIL, purpose: 'signup' })
    });
    const data = await res.json();
    if (res.ok && data.success) {
      showMessage('A new code has been sent to your email.', 'success');
      startCooldown();
    } else {
      showMessage(data.message || 'Could not resend code. Please try again.', 'error');
    }
  } catch (err) {
    showMessage('Network error. Please check your connection and try again.', 'error');
  } finally {
    resendBtn.disabled = false;
  }
});

// --- Submit / verify ---
otpForm.addEventListener('submit', async function (e) {
  e.preventDefault();
  clearMessage();

  const otp = getOtpValue();
  if (otp.length !== 6) {
    showMessage('Enter the 6-digit code sent to your email.', 'error');
    return;
  }

  setLoading(true);

  try {
    const res = await fetch('verify-otp.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: new URLSearchParams({ email: EMAIL, otp_code: otp, purpose: 'signup' })
    });

    const data = await res.json();

    if (res.ok && data.success) {
      showMessage('Email verified! Redirecting…', 'success');
      window.location.href = 'profile-setup.php';
      return;
    }

    showMessage(data.message || 'Incorrect code. Please try again.', 'error');
    digits.forEach(d => d.value = '');
    digits[0].focus();
  } catch (err) {
    showMessage('Network error. Please check your connection and try again.', 'error');
  } finally {
    setLoading(false);
  }
});
</script>

</body>
</html>
