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

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

// Load .env
$env = parse_ini_file(__DIR__ . '/../.env');

function sendAlertEmail($to, $cc, $subject, $body)
{
    global $env;

    $mail = new PHPMailer(true);

    try {
        $mail->isSMTP();
        $mail->Host       = $env['SMTP_HOST'];
        $mail->SMTPAuth   = true;
        $mail->Username   = $env['SMTP_USER'];
        $mail->Password   = $env['SMTP_PASS'];
        $mail->Port       = (int)$env['SMTP_PORT'];
        $mail->SMTPSecure = $env['SMTP_SECURE'];

        $mail->setFrom($env['MAIL_FROM'], 'PC Monitoring');

        /* ========= TO ========= */
        if (filter_var($to, FILTER_VALIDATE_EMAIL)) {
            $mail->addAddress($to);
        }

        /* ========= CC ========= */
        if (is_array($cc)) {
            foreach ($cc as $email) {
                $email = trim($email);
                if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
                    $mail->addCC($email);
                }
            }
        }

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

        return $mail->send();

    } catch (Exception $e) {
        file_put_contents(
            __DIR__ . '/mail_error.log',
            date('Y-m-d H:i:s') . ' | ' . $mail->ErrorInfo . PHP_EOL,
            FILE_APPEND
        );
        return false;
    }
}
