<?php
require_once dirname(__DIR__) . '/auth_check.php';
require_once dirname(__DIR__) . '/config.php';

$to = isset($_POST['to']) ? trim($_POST['to']) : '';
if (!filter_var($to, FILTER_VALIDATE_EMAIL)) {
    echo "error: Invalid email address"; die();
}

$settings = getSmtpSettings($koneksi);

// Load PHPMailer
$mailerPath = dirname(__DIR__,2) . '/api/Email/PHPMailer/';
if (!file_exists($mailerPath . 'PHPMailer.php')) {
    echo "error: PHPMailer not found at $mailerPath"; die();
}

require_once $mailerPath . 'PHPMailer.php';
require_once $mailerPath . 'SMTP.php';
require_once $mailerPath . 'Exception.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

try {
    $mail = new PHPMailer(true);
    $mail->isSMTP();
    $mail->Host       = $settings['smtp_host'] ?? 'smtp.gmail.com';
    $mail->SMTPAuth   = true;
    $mail->Username   = $settings['smtp_username'] ?? '';
    $mail->Password   = $settings['smtp_password'] ?? '';
    $enc = $settings['smtp_encryption'] ?? 'tls';
    $mail->SMTPSecure = $enc === 'ssl' ? PHPMailer::ENCRYPTION_SMTPS : ($enc === 'tls' ? PHPMailer::ENCRYPTION_STARTTLS : '');
    $mail->Port       = (int)($settings['smtp_port'] ?? 587);
    $mail->setFrom($settings['smtp_from_email'] ?? $settings['smtp_username'], $settings['smtp_from_name'] ?? 'Admin');
    $mail->addAddress($to);
    $mail->isHTML(true);
    $mail->Subject = 'Test Email from ' . ($settings['site_name'] ?? 'Admin Panel');
    $mail->Body    = '<h2>Test Email</h2><p>This is a test email from your admin panel. SMTP is configured correctly!</p>';
    $mail->send();
    echo "success: Test email sent to $to";
} catch (Exception $e) {
    echo "error: " . $mail->ErrorInfo;
}
