<?php

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

// Carica le variabili di ambiente
require_once dirname(__DIR__, 2) . '/vendor/autoload.php'; // Assicurati che PHPMailer e Dotenv siano installati con Composer

$dotenv = Dotenv::createImmutable(dirname(__DIR__, 2)); // Se la cartella `class` è a 2 livelli sopra la root
$dotenv->load();

function sendEmail($to, $subject, $body, $attachments = [], $cc = [], $bcc = [])
{
    // Configurazione SMTP
    $mail = new PHPMailer(true);
    try {
        // Configurazione server SMTP con dati da .env
        $mail->isSMTP();
        $mail->Host       = $_ENV['MAIL_HOST'] ?? 'smtp.example.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = $_ENV['MAIL_USERNAME'] ?? 'email@example.com';
        $mail->Password   = $_ENV['MAIL_PASSWORD'] ?? 'password';
        $mail->SMTPSecure = $_ENV['MAIL_ENCRYPTION'] ?? PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = $_ENV['MAIL_PORT'] ?? 587;

        // Mittente
        $mail->setFrom($_ENV['MAIL_FROM_ADDRESS'] ?? 'default@example.com', $_ENV['MAIL_FROM_NAME'] ?? 'Default Name');

        // Destinatari principali
        foreach ((array)$to as $recipient) {
            $mail->addAddress($recipient);
        }

        // Destinatari CC
        foreach ((array)$cc as $recipient) {
            $mail->addCC($recipient);
        }

        // Destinatari BCC
        foreach ((array)$bcc as $recipient) {
            $mail->addBCC($recipient);
        }

        // Allegati
        foreach ((array)$attachments as $file) {
            $mail->addAttachment($file);
        }

        // Contenuto dell'email
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $body;

        // Invia l'email
        $mail->send();
        return ['success' => true, 'message' => 'Email inviata con successo.'];
    } catch (Exception $e) {
        return ['success' => false, 'message' => "Errore nell'invio dell'email: {$mail->ErrorInfo}"];
    }
}
