<?php
/**
 * POST /api/auth/forgot
 *
 * Body: email
 *
 * Always returns generic success (no email enumeration).
 * If email exists → sends reset link via SMTP_FORGET_URL.
 */

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

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

if ((int)env('OTP_FORGET_ENABLED', 1) !== 1) {
    jsonError('Self-serve password reset is currently disabled. Please contact support.', 403);
}

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

$email = strtolower(Validator::clean((string)($_POST['email'] ?? ''), 190));
if (!Validator::email($email)) {
    jsonError('Please enter a valid email address.');
}

RateLimit::hit('forgot:email:' . $email, 3, 3600,
    'Too many reset requests for this email. Try in 1 hour.');

$pdo = db();
$stmt = $pdo->prepare("SELECT id, status FROM publisher_user WHERE email = ? LIMIT 1");
$stmt->execute([$email]);
$user = $stmt->fetch();

// Don't reveal whether email exists — log silently if not
if ($user && (int)$user['status'] === 1) {
    $token = bin2hex(random_bytes(32));
    $tokenHash = hash('sha256', $token);
    $expiry = date('Y-m-d H:i:s', time() + (int)env('RESET_TOKEN_EXPIRY_MINUTES', 30) * 60);

    // Invalidate older unused tokens for this user
    $pdo->prepare("UPDATE publisher_password_reset SET used = 1 WHERE publisher_id = ? AND used = 0")
        ->execute([(int)$user['id']]);

    $pdo->prepare("
        INSERT INTO publisher_password_reset (publisher_id, token_hash, expires_at, ip_address)
        VALUES (?, ?, ?, ?)
    ")->execute([(int)$user['id'], $tokenHash, $expiry, $ip]);

    // The mailer should construct: APP_URL/reset-password?token=$token
    Mail::sendResetLink($email, $token);
    Logger::audit((int)$user['id'], 'password_reset_requested');
} else {
    Logger::warning('Forgot password for unknown/blocked email', ['email' => $email]);
}

jsonSuccess('If that email is registered with us, a reset link has been sent.');
