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

apply_cors();
$admin = require_super_admin();

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

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

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

$html = '<div style="font-family:sans-serif;padding:24px;">'
    . '<h2>SMTP test successful</h2>'
    . '<p>This is a test email from your AI Auto Reply Marketing admin panel. '
    . 'If you received this, your SMTP configuration is working correctly.</p>'
    . '<p style="color:#888;font-size:12px;">Sent at ' . date('Y-m-d H:i:s') . ' IST</p>'
    . '</div>';

[$success, $message] = send_mail_via_settings($targetEmail, '', 'SMTP Test - AI Auto Reply Marketing', $html);

log_admin_action($admin['email'], 'TEST_SMTP_EMAIL', $targetEmail, $success ? 'success' : $message);

if (!$success) {
    send_error($message, 500);
}

send_success(null, 'Test email sent to ' . $targetEmail . '.');
