<?php
require_once __DIR__ . '/../config/cors.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../utils/helpers.php';
require_once __DIR__ . '/../utils/mailer.php';
require_once __DIR__ . '/../utils/email-templates.php';

$token = getAuthToken();
$user = getUserFromToken($token);

if (!$user) {
    errorResponse('Unauthorized', 401);
}

$input = getJsonInput();
if (!isset($input['email']) || !filter_var($input['email'], FILTER_VALIDATE_EMAIL)) {
    errorResponse('Valid email address is required', 400);
}

$recipient = $input['email'];
$subject = "Test Email from FlashCORE";
$content = "
    <h2>Test Email Successful!</h2>
    <p>This is a confirmation that your email configuration is working correctly.</p>
    <p><strong>Sent to:</strong> $recipient</p>
    <p><strong>Sent by:</strong> " . $user['username'] . "</p>
    <hr>
    <p style='color: #666; font-size: 12px;'>If you received this, the SMTP settings are valid.</p>
";

$htmlBody = getBrandedTemplate($content, $subject);

$result = sendRobustEmail($recipient, $subject, $htmlBody);

if ($result['success']) {
    jsonResponse(['success' => true, 'message' => 'Test email sent successfully']);
} else {
    errorResponse($result['message'], 500);
}
?>
