<?php
/**
 * POST /api/auth/resend-otp
 *
 * Body: email, purpose (signup | login | forget)
 *
 * Re-sends an OTP if cooldown has passed.
 */

declare(strict_types=1);
require_once dirname(__DIR__, 2) . '/config/bootstrap.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonError('Method not allowed', 405);
}

$ip = Logger::clientIp();
RateLimit::hit('otp:resend:ip:' . $ip, 10, 3600);

$email   = strtolower(Validator::clean((string)($_POST['email'] ?? ''), 190));
$purpose = strtolower(Validator::clean((string)($_POST['purpose'] ?? 'signup'), 20));

if (!Validator::email($email)) jsonError('Invalid email.');
if (!in_array($purpose, ['signup', 'login', 'forget'], true)) {
    jsonError('Invalid purpose.');
}

RateLimit::hit("otp:resend:{$purpose}:{$email}", 5, 3600,
    'Too many resend requests for this email.');

$pdo = db();
$stmt = $pdo->prepare("
    SELECT id, otp_hash, payload, created_at, verified
    FROM publisher_otp
    WHERE identifier = ? AND purpose = ?
    ORDER BY id DESC LIMIT 1
");
$stmt->execute([$email, $purpose]);
$row = $stmt->fetch();

if (!$row) {
    jsonError('No active OTP context found. Please start over.', 404);
}
if ((int)$row['verified'] === 1) {
    jsonError('This OTP was already verified.', 400);
}

$cooldown = (int)env('OTP_RESEND_COOLDOWN_SECONDS', 60);
$age = time() - (int)$row['created_at'];
if ($age < $cooldown) {
    $wait = $cooldown - $age;
    jsonError("Please wait {$wait} seconds before resending.", 429);
}

// Generate fresh OTP, replace existing row
$otpLen = (int)env('OTP_LENGTH', 6);
$max = (int)str_repeat('9', $otpLen);
$otp = str_pad((string)random_int(0, $max), $otpLen, '0', STR_PAD_LEFT);
$otpHash = password_hash($otp, PASSWORD_BCRYPT);
$expiry = time() + ((int)env('OTP_EXPIRY_MINUTES', 10) * 60);

$pdo->prepare("
    UPDATE publisher_otp
    SET otp_hash = ?, attempts = 0, expires_at = ?, created_at = ?
    WHERE id = ?
")->execute([$otpHash, $expiry, time(), (int)$row['id']]);

Mail::sendOtp($email, $otp, $purpose);
Logger::audit(null, 'otp_resent', 'email', null, ['email' => $email, 'purpose' => $purpose]);

jsonSuccess('OTP re-sent. Please check your inbox.', [
    'expires_in' => (int)env('OTP_EXPIRY_MINUTES', 10) * 60,
]);
