<?php

require_once __DIR__ . '/PHPMailer/src/PHPMailer.php';
require_once __DIR__ . '/PHPMailer/src/SMTP.php';
require_once __DIR__ . '/PHPMailer/src/Exception.php';

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

function kirimEmail($to, $subject, $body, $attachments = null)
{
    $mail = new PHPMailer(true);

    try {

        $mail->isSMTP();
        $mail->Host       = 'mail.laporan.my.id';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'noreply@laporan.my.id';
        $mail->Password   = 'P455w0rd...'; 
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port       = 465;

        $mail->CharSet = 'UTF-8';

        $mail->setFrom('noreply@laporan.my.id', 'LuminaCare');
        $mail->addAddress($to);

        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $body;

        /* ==========================
           SUPPORT MULTIPLE ATTACHMENT
        ========================== */

        if (!empty($attachments)) {

            // Jika single file (string)
            if (is_string($attachments)) {
                if (file_exists($attachments)) {
                    $mail->addAttachment($attachments);
                }
            }

            // Jika multiple file (array)
            if (is_array($attachments)) {
                foreach ($attachments as $file) {
                    if (file_exists($file)) {
                        $mail->addAttachment($file);
                    }
                }
            }
        }

        $mail->send();
        return true;

    } catch (Exception $e) {
        error_log("Mail Error: " . $mail->ErrorInfo);
        return false;
    }
}