<?php
/**
 * POST /api/admin/test_email.php
 * Body (JSON): { to }
 * Admin-only. Sends a test email and returns the actual delivery result
 * (method used, success/failure, and the raw error if it failed) - so mail
 * configuration can be diagnosed from the admin panel in one click instead
 * of repeating a full registration cycle to find out if it worked.
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/mailer.php';

only_post_allowed();
require_login();
require_role(['admin']);

$input = get_json_input();
$to = trim($input['to'] ?? '');
if (!filter_var($to, FILTER_VALIDATE_EMAIL)) {
    send_error('Please provide a valid email address to send the test to.', 422);
}

$result = send_email(
    $to,
    'Ragreen test email',
    "This is a test email from your Ragreen admin panel.\n\nIf you received this, outgoing mail is configured correctly."
);

if ($result['ok']) {
    send_json(true, "Test email sent via {$result['method']}. Check the inbox (and spam folder) for $to.", $result);
} else {
    send_error("Sending failed via {$result['method']}: {$result['error']}", 500, $result);
}
