����JFIF��`�`�����<CREATOR: gd-jpeg v1.0 (using IJG JPEG v80), quality = 100
���C����C����d�d"��������������
����JFIF��`�`�����<CREATOR: gd-jpeg v1.0 (using IJG JPEG v80), quality = 100
���C����C����d�d"��������������
����JFIF��`�`�����<CREATOR: gd-jpeg v1.0 (using IJG JPEG v80), quality = 100
���C����C����d�d"��������������
����JFIF��`�`�����<CREATOR: gd-jpeg v1.0 (using IJG JPEG v80), quality = 100
���C����C����d�d"��������������
<?php
// backend/api/public/send_community_otp.php
require_once '../db.php';
require_once '../utils/mailer.php';

// Rely on send_json() (from db_core.php) for CORS and headers
$data = get_json();

if (empty($data['email']) || empty($data['name'])) {
    send_json(['success' => false, 'message' => 'Name and email are required to join the community.'], 400);
}

$email = trim($data['email']);
$name = trim($data['name']);

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    send_json(['success' => false, 'message' => 'Invalid email format.'], 400);
}

// 1. Check if user is already in the community
$stmt = $conn->prepare("SELECT id FROM community_members WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
if ($stmt->get_result()->num_rows > 0) {
    $stmt->close();
    send_json(['success' => false, 'message' => 'This email is already part of the community.'], 400);
}
$stmt->close();

// 2. Limit generation rate (max 1 per 60 seconds)
$fourteen_mins_from_now = date('Y-m-d H:i:s', strtotime('+14 minutes'));
$stmt = $conn->prepare("SELECT id FROM registration_otps WHERE email = ? AND expiry > ?");
$stmt->bind_param("ss", $email, $fourteen_mins_from_now);
$stmt->execute();
if ($stmt->get_result()->num_rows > 0) {
    $stmt->close();
    send_json(['success' => false, 'message' => 'Please wait 60 seconds before requesting a new OTP.'], 429);
}
$stmt->close();

// 3. Clear old OTPs for this email to prevent clutter
$stmt = $conn->prepare("DELETE FROM registration_otps WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->close();

// 4. Generate new cryptographically secure OTP
$otp = str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);
$expiry = date('Y-m-d H:i:s', strtotime('+15 minutes'));

// 5. Store OTP in registration_otps (with default attempts = 0)
$stmt = $conn->prepare("INSERT INTO registration_otps (email, otp, expiry) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $email, $otp, $expiry);

if (!$stmt->execute()) {
    $stmt->close();
    send_json(['success' => false, 'message' => 'Failed to generate OTP.'], 500);
}
$stmt->close();

// 5. Send OTP Email using info@throtllr.com
$result = send_otp_email($email, $name, $otp, 'verification');
if ($result === true) {
    send_json(['success' => true, 'message' => "OTP sent successfully to $email."]);
} else {
    // We clean up the OTP if email fails to send due to SMTP errors
    $stmt = $conn->prepare("DELETE FROM registration_otps WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $stmt->close();
    
    $error_msg = is_string($result) ? $result : "Unknown Error";
    if (strpos($error_msg, 'Connection FAILED') !== false || strpos($error_msg, 'Auth FAILED') !== false || strpos($error_msg, 'All ports failed') !== false) {
        send_json(['success' => false, 'message' => 'SMTP Rate Limit reached. Please try again later.'], 500);
    } else {
        send_json(['success' => false, 'message' => 'Failed to send OTP email. ' . $error_msg], 500);
    }
}
?>
