<?php
// Prevent any output before JSON
ob_start();

require_once '../../includes/config.php';
require_once '../../includes/mailer.php';

header('Content-Type: application/json');

// Clear any accidental output
ob_clean();

if (!isAdmin()) {
    echo json_encode(['success'=>false,'message'=>'Not authorized']); exit;
}

$to = trim($_POST['to'] ?? '');
if (!$to || !filter_var($to, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(['success'=>false,'message'=>'Invalid email address']); exit;
}

// Check settings configured
$host = getSetting('mail_host') ?: '';
$user = getSetting('mail_username') ?: '';
$pass = getSetting('mail_password') ?: '';

if (!$host || !$user || !$pass) {
    echo json_encode(['success'=>false,'message'=>'SMTP not configured. Fill Host, Username, Password and Save first.']); exit;
}

$result = sendMail(
    $to,
    '['.SITE_NAME.'] Test Email',
    '<h2 style="color:#1a3c8f">✅ Email server is working!</h2><p>This is a test email from <b>'.htmlspecialchars(SITE_NAME).'</b>.</p>',
    'Test email from '.SITE_NAME
);

echo json_encode([
    'success' => $result['ok'],
    'message' => $result['message']
]);
