<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

/**
 * Fungsi untuk mengirim email menggunakan PHPMailer
 *
 * @param string $subject Judul email
 * @param string $body Isi email (dapat berupa HTML)
 * @param string $recipient Email penerima
 * @return bool|string True jika berhasil, atau pesan error jika gagal
 */
function sendEmailSystemBroker(string $subject, string $body, string $recipient)
{
    $mail = new PHPMailer(true);

    try {
        // Konfigurasi server SMTP
        $mail->isSMTP();
        $mail->Host = 'mail.wiselie.co.id'; // Ganti dengan host SMTP Anda
        $mail->SMTPAuth = true;
        $mail->Username = 'system@wiselie.co.id'; // Email pengirim
        $mail->Password = 'HiWiselie9898_'; // Password atau App Password
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port = 465;

        // Informasi pengirim
        $mail->setFrom('system@wiselie.co.id', 'System Broker');
        $mail->addAddress($recipient); // Tambahkan penerima

        // Konten email
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $body;
        $mail->AltBody = strip_tags($body); // Versi teks biasa

        // Kirim email
        $mail->send();
        return true; // Email berhasil dikirim
    } catch (Exception $e) {
        return "Gagal mengirim email: {$mail->ErrorInfo}";
    }
}


$input = json_decode(file_get_contents('php://input'), true);

// Validasi data input
if (!isset($input['body'])) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Data tidak lengkap. Pastikan subject, body, dan recipient tersedia.']);
    exit;
}

// Contoh penggunaan fungsi
$result = sendEmailSystemBroker(
    'Peringatan: Terjadi Error di Log File', $input['body'], "arifnurabdullah03@gmail.com"
);

if ($result === true) {
    echo json_encode(['status' => 'success', 'message' => 'Email berhasil dikirim.']);
} else {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => $result]);
}
?>
