<?php
require_once __DIR__ . '/../app/helpers/functions.php';
require_once __DIR__ . '/../app/helpers/otp.php';

session_boot();
$conn = require __DIR__ . '/../app/config/database.php';

$userId = (int)($_SESSION['otp_user'] ?? 0);
if (!$userId) {
  http_response_code(403);
  exit('Unauthorized');
}

/* ⏱️ COOLDOWN CHECK (60s) */
$st = $conn->prepare("
  SELECT created_at
  FROM otps
  WHERE user_id=? AND purpose='login'
  ORDER BY id DESC
  LIMIT 1
");
$st->bind_param("i", $userId);
$st->execute();
$last = $st->get_result()->fetch_assoc();

if ($last) {
  $lastTime = strtotime($last['created_at']);
  if (time() - $lastTime < 60) {
    http_response_code(429);
    echo json_encode([
      'error' => 'Please wait before requesting another OTP.'
    ]);
    exit;
  }
}

/* 🔥 Invalidate previous OTPs */
$inv = $conn->prepare("
  UPDATE otps
  SET used_at = NOW()
  WHERE user_id=? AND purpose='login' AND used_at IS NULL
");
$inv->bind_param("i", $userId);
$inv->execute();

/* ✅ CREATE NEW OTP */
otp_create($conn, $userId, 'login', 'email');

echo json_encode([
  'success' => true,
  'message' => 'New OTP sent'
]);
