<?php
/**
 * POST /api/auth/resend_verification.php
 * Body (JSON): { email }
 * Always returns a generic success message regardless of whether the email
 * exists or is already verified, same privacy pattern as forgot_password.php.
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';
require_once __DIR__ . '/../includes/mailer.php';

only_post_allowed();

$input = get_json_input();
$email = trim($input['email'] ?? '');
if ($email === '') {
    send_error('Email is required.', 422);
}

$pdo = Database::connect();
$stmt = $pdo->prepare('SELECT id, email_verified_at FROM users WHERE email = ? LIMIT 1');
$stmt->execute([$email]);
$user = $stmt->fetch();

if ($user && !$user['email_verified_at']) {
    $rawToken = bin2hex(random_bytes(32));
    $tokenHash = hash('sha256', $rawToken);
    $expiresAt = date('Y-m-d H:i:s', strtotime('+48 hours'));

    // Clear any previous tokens for this user before issuing a new one.
    $pdo->prepare('DELETE FROM email_verifications WHERE user_id = ?')->execute([$user['id']]);
    $pdo->prepare('INSERT INTO email_verifications (user_id, token_hash, expires_at) VALUES (?, ?, ?)')
        ->execute([$user['id'], $tokenHash, $expiresAt]);

    // See register.php - APP_URL already points to the public/ web root.
    $verifyLink = APP_URL . '/verify-email.html?token=' . $rawToken;
    send_email($email, 'Verify your Ragreen account', "Verify your email address:\n$verifyLink\n\nThis link expires in 48 hours.");
}

$response = ['message' => 'If that email exists and needs verification, a new link has been sent.'];
if (APP_ENV === 'local' && $user && !$user['email_verified_at']) {
    $response['dev_verify_link'] = $verifyLink;
}

send_json(true, $response['message'], array_diff_key($response, ['message' => '']));
