<?php
// /user/user_verify_reset.php
require_once __DIR__ . '/_bootstrap.php'; // starts session + $conn

// ---- config ----
$RESET_WINDOW_MIN = 10;   // reset page usable for 10 minutes after verify
$RATE_MAX_ATTEMPTS = 5;   // max attempts
$RATE_WINDOW_SEC   = 600; // 10 minutes

// init rate limiter
if (!isset($_SESSION['vr_attempts'])) $_SESSION['vr_attempts'] = [];
// clear old attempts
$_SESSION['vr_attempts'] = array_filter($_SESSION['vr_attempts'], function($t) use($RATE_WINDOW_SEC){
  return $t > time() - $RATE_WINDOW_SEC;
});
$locked = (count($_SESSION['vr_attempts']) >= $RATE_MAX_ATTEMPTS);

// CSRF
if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(16));
$csrf = $_SESSION['csrf'];

$err = $ok = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$locked) {
  if (!hash_equals($_SESSION['csrf'] ?? '', $_POST['csrf'] ?? '')) {
    $err = 'Invalid request. Please refresh and try again.';
  } else {
    // inputs
    $email = trim($_POST['email'] ?? '');
    $cnic  = trim($_POST['cnic'] ?? '');
    $dob   = trim($_POST['dob'] ?? ''); // YYYY-MM-DD
    $regno = trim($_POST['reg_no'] ?? ''); // optional

    // basic validation
    if ($email === '' || $cnic === '' || $dob === '') {
      $err = 'Please provide Email, CNIC and Date of Birth.';
    } elseif (!preg_match('/^[0-9]{5}-[0-9]{7}-[0-9]$/', $cnic)) {
      $err = 'CNIC format invalid. Use 12345-1234567-1';
    } else {
      // 1) find student by email
      $st = mysqli_prepare($conn, "SELECT id, email, cnic, dob FROM students WHERE email=? LIMIT 1");
      mysqli_stmt_bind_param($st, "s", $email);
      mysqli_stmt_execute($st);
      $res = mysqli_stmt_get_result($st);
      $stu = mysqli_fetch_assoc($res);
      mysqli_stmt_close($st);

      if (!$stu) {
        $err = 'No student found for this Email.';
      } else {
        $sid = (int)$stu['id'];
        $cnic_ok = (strcmp($cnic, (string)$stu['cnic']) === 0);
        $dob_ok  = (strcmp($dob, (string)$stu['dob']) === 0);

        // optional: if reg_no provided, verify against any registration
        $reg_ok = true;
        if ($regno !== '') {
          $st2 = mysqli_prepare($conn, "SELECT id FROM registrations WHERE student_id=? AND reg_no=? LIMIT 1");
          mysqli_stmt_bind_param($st2, "is", $sid, $regno);
          mysqli_stmt_execute($st2);
          $r2 = mysqli_stmt_get_result($st2);
          $reg_ok = (bool)mysqli_fetch_assoc($r2);
          mysqli_stmt_close($st2);
        }

        if ($cnic_ok && $dob_ok && $reg_ok) {
          // success → make short-lived reset session
          $_SESSION['reset_student_id'] = $sid;
          $_SESSION['reset_until']      = time() + ($RESET_WINDOW_MIN * 60);
          // single-use CSRF for reset
          $_SESSION['reset_csrf']       = bin2hex(random_bytes(16));
          header('Location: user_set_new_password.php?ok=1');
          exit;
        } else {
          $err = 'Provided details did not match our records.';
        }
      }
    }
  }

  // log attempt (fail or success handled above; log on any POST)
  $_SESSION['vr_attempts'][] = time();
}

// simple clean UI
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Verify Identity · Zetechup Portal</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
  body{font-family:system-ui,Segoe UI,Roboto,Arial;background:#f8fafc;margin:0}
  .wrap{max-width:520px;margin:40px auto;padding:16px}
  .card{background:#fff;border:1px solid #e5e7eb;border-radius:12px;padding:16px;box-shadow:0 1px 2px rgba(0,0,0,.04),0 6px 18px rgba(0,0,0,.06)}
  h2{margin:0 0 10px;color:#0f172a}
  label{display:block;font-size:12px;color:#475569;margin:8px 0 4px}
  input{width:100%;height:38px;border:1px solid #e5e7eb;border-radius:10px;padding:8px 10px}
  .btn{background:#2563eb;color:#fff;border:1px solid #2563eb;border-radius:10px;padding:10px 14px;cursor:pointer}
  .muted{color:#64748b;font-size:13px}
  .alert{border-radius:10px;padding:10px;margin:10px 0}
  .err{background:#fee2e2;border:1px solid #fecaca;color:#991b1b}
  .ok{background:#eff6ff;border:1px solid #bfdbfe;color:#1e40af}
  .row{display:grid;grid-template-columns:1fr 1fr;gap:10px}
  @media(max-width:620px){.row{grid-template-columns:1fr}}
</style>
</head>
<body>
<div class="wrap">
  <h2>Verify Your Identity</h2>
  <div class="card">
    <?php if($locked): ?>
      <div class="alert err">Too many attempts. Please try again after a few minutes.</div>
    <?php endif; ?>
    <?php if(!empty($err)): ?>
      <div class="alert err"><?=htmlspecialchars($err)?></div>
    <?php endif; ?>
    <form method="post" autocomplete="off">
      <input type="hidden" name="csrf" value="<?=htmlspecialchars($csrf)?>">
      <label>Email</label>
      <input name="email" type="email" placeholder="you@example.com" required>

      <div class="row">
        <div>
          <label>CNIC</label>
          <input name="cnic" placeholder="12345-1234567-1" pattern="[0-9]{5}-[0-9]{7}-[0-9]" required>
        </div>
        <div>
          <label>Date of Birth</label>
          <input name="dob" type="date" required>
        </div>
      </div>

      <label>Registration No. (optional)</label>
      <input name="reg_no" placeholder="ZE-2025-0001">

      <div style="display:flex;gap:8px;align-items:center;margin-top:12px">
        <button class="btn" <?= $locked?'disabled':''; ?>>Continue</button>
        <a href="user_login.php" class="muted">Back to Login</a>
      </div>
      <div class="muted" style="margin-top:8px">We’ll allow password reset only if details match exactly.</div>
    </form>
  </div>
</div>
</body>
</html>
