<?php
// verify-code.php - Match user-entered email verification code
session_start();

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || empty($_POST['code'])) {
  http_response_code(400);
  echo json_encode(['success' => false, 'error' => 'Missing verification code.']);
  exit();
}

$inputCode = trim($_POST['code']);
$stored = $_SESSION['email_verification'] ?? null;

if (!$stored || !isset($stored['code'], $stored['timestamp'])) {
  http_response_code(400);
  echo json_encode(['success' => false, 'error' => 'No code was sent.']);
  exit();
}

if (time() - $stored['timestamp'] > 900) { // 15 minutes expiry
  unset($_SESSION['email_verification']);
  echo json_encode(['success' => false, 'error' => 'Code expired.']);
  exit();
}

if ($inputCode == $stored['code']) {
  $_SESSION['email_verified'] = true;
  echo json_encode(['success' => true]);
} else {
  echo json_encode(['success' => false, 'error' => 'Invalid code.']);
}
