<?php
require '../vendor/autoload.php'; // Asegúrate de ajustar la ruta si es necesario

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

header('Content-Type: application/json'); // Set response header to JSON

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $to = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
    $subject = htmlspecialchars($_POST['subject'], ENT_QUOTES, 'UTF-8');
    $message = nl2br(htmlspecialchars($_POST['message'], ENT_QUOTES, 'UTF-8')); // Convert new lines to <br>
    $pdfFilePath = filter_var($_POST['pdfFilePath'], FILTER_SANITIZE_STRING);

    $result = sendEmail($to, $subject, $message, $pdfFilePath);

    if ($result === true) {
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'error' => $result]);
    }
}

function sendEmail($to, $subject, $body, $attachment = null)
{
    $mail = new PHPMailer(true);

    try {
        // Configuración del servidor
        $mail->isSMTP();
        $mail->Host       = 'mail.compranet.com.co'; // Configura tu servidor SMTP
        $mail->SMTPAuth   = true;
        $mail->Username   = 'ventas@compranet.com.co'; // Tu dirección de correo SMTP
        $mail->Password   = 'Proyecto2025*'; // Tu contraseña SMTP
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Encriptación TLS
        $mail->Port       = 587; // Puerto SMTP sin SSL
        // Opciones SMTP
        $mail->SMTPOptions = array(
            'ssl' => array(
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            )
        );

        // Remitente y destinatario
        $mail->setFrom('ventas@compranet.com.co', 'Compranet Comercio Electronico SAS');
        $mail->addAddress($to);

        // Añadir copia oculta (BCC)
        $mail->addBCC('ventas@compranet.com.co');

        // Contenido del correo
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $body;
        $mail->CharSet = 'UTF-8'; // Set the charset to UTF-8

        // Adjuntar archivo si existe
        if ($attachment) {
            $mail->addAttachment($attachment);
        }

        $mail->send();
        return true;
    } catch (Exception $e) {
        return "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
    }
}
