<?php
// includes/send_email.php

require_once __DIR__ . '/PHPMailer-master/src/Exception.php';
require_once __DIR__ . '/PHPMailer-master/src/PHPMailer.php';
require_once __DIR__ . '/PHPMailer-master/src/SMTP.php';
require_once __DIR__ . '/config.php';

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

function sendEmail($to, $subject, $body, $isHTML = true, $attachments = [], $senderName = '') {
    $mail = new PHPMailer(true);

    try {
        // Configuración del servidor SMTP empresarial
        $mail->isSMTP();
        $mail->Host       = SMTP_HOST;
        $mail->SMTPAuth   = true;
        $mail->Username   = SMTP_USER;
        $mail->Password   = SMTP_PASS;
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // TLS
        $mail->Port       = SMTP_PORT;

        // Remitente (cuenta empresarial)
        $mail->setFrom(SMTP_FROM, SMTP_FROM_NAME);
        
        // Si se especifica un remitente personalizado
        if (!empty($senderName)) {
            $mail->addReplyTo(SMTP_FROM, $senderName);
        }

        // Destinatario(s)
        if (is_array($to)) {
            foreach ($to as $email => $name) {
                $mail->addAddress($email, $name);
            }
        } else {
            $mail->addAddress($to);
        }

        // Adjuntos
        if (!empty($attachments)) {
            foreach ($attachments as $attachment) {
                $mail->addAttachment($attachment['tmp_name'], $attachment['name']);
            }
        }

        // Contenido
        $mail->isHTML($isHTML);
        $mail->Subject = $subject;
        $mail->Body    = $body;
        
        if (!$isHTML) {
            $mail->AltBody = strip_tags($body);
        }

        $mail->send();
        return true;
    } catch (Exception $e) {
        error_log("[" . date('Y-m-d H:i:s') . "] Error al enviar correo: " . $mail->ErrorInfo);
        return false;
    }
}