<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/mailer.php';

apply_cors();

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

$input = get_json_input();
require_fields($input, ['email']);

$email = strtolower(clean_str($input['email']));
if (!is_valid_email($email)) {
    send_error('Invalid email address.', 422);
}

$pdo = getDbConnection();

// Already-registered check
$existing = $pdo->prepare('SELECT id FROM users WHERE email = :email');
$existing->execute([':email' => $email]);
if ($existing->fetch()) {
    send_error('An account with this email already exists. Try logging in instead.', 409);
}

// Rate limit: max 5 OTP sends per email per 15 minutes
$rateCheck = $pdo->prepare(
    'SELECT COUNT(*) FROM email_otps WHERE email = :email AND created_at > (NOW() - INTERVAL 15 MINUTE)'
);
$rateCheck->execute([':email' => $email]);
if ((int) $rateCheck->fetchColumn() >= 5) {
    send_error('Too many OTP requests. Please wait a few minutes and try again.', 429);
}

$otp = generate_otp(6);
$expiresAt = date('Y-m-d H:i:s', time() + 600); // 10 minutes

$stmt = $pdo->prepare(
    'INSERT INTO email_otps (email, otp, expires_at) VALUES (:email, :otp, :expires_at)'
);
$stmt->execute([':email' => $email, ':otp' => $otp, ':expires_at' => $expiresAt]);

$html = '<div style="font-family:sans-serif;padding:24px;">'
    . '<h2>Verify your email</h2>'
    . '<p>Your verification code is:</p>'
    . '<div style="font-size:28px;font-weight:700;letter-spacing:6px;margin:16px 0;">' . $otp . '</div>'
    . '<p style="color:#888;font-size:13px;">This code expires in 10 minutes. If you did not request this, ignore this email.</p>'
    . '</div>';

[$sent, $mailMessage] = send_mail_via_settings($email, '', 'Your verification code', $html);

if (!$sent) {
    // Don't fail registration flow just because SMTP isn't configured yet —
    // log server-side so an admin notices, but let the client proceed
    // (useful during initial setup/testing before SMTP is live).
    error_log('OTP email failed for ' . $email . ': ' . $mailMessage);
}

send_success(null, 'Verification code sent to your email.');
