<?php

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

require __DIR__ . '/../../../vendor/autoload.php';

class CorreoElectronico
{
    public $plantilla;

    function __construct($urlPlantilla, $parametros = [])
    {
        $plantillaHTML = file_get_contents($urlPlantilla);
        $this->plantilla = $plantillaHTML;

        $variablesNecesarias = [];
        preg_match_all('/\{\{(.*)\}\}/U', $this->plantilla, $variablesNecesarias);
        $variablesNecesarias = $variablesNecesarias[1];

        foreach ($variablesNecesarias as $variable) {
            if (!isset($parametros[$variable])) {
                echo json_encode((object)[
                    'message' => 'Error: variable ' . $variable . ' no encontrada',
                    'status' => 400,
                ]);
                exit();
            }
        }

        foreach ($parametros as $key => $value) {
            $this->plantilla = str_replace('{{' . $key . '}}', $value, $this->plantilla);
        }
    }

    public function enviar($destinatario, $nombre, $asunto, $adjuntos, $correoEmisor = 'comunicacionInterna@seguridadactivaelsalvador.com', $nombreEmisor = 'SEAC S.A. de C.V'): object
    {
        $correo = new PHPMailer(true);

        try {
            $correo->isSMTP();
            $correo->Host = 'smtp.constru-services.com';
            $correo->SMTPAuth = true;
            $correo->Username = 'comunicacionInterna.seac@constru-services.com';
            $correo->Password = 'cse13cse13!';

            $correo->SMTPAutoTLS = false;
            $correo->SMTPSecure = false;
            $correo->Port = 25;

            $correo->setFrom($correoEmisor, $nombreEmisor);

            foreach ($adjuntos as $adjunto) {
                $correo->addAttachment($adjunto);
            }

            $correo->addAddress($destinatario, utf8_decode($nombre));
            $correo->isHTML(true);
            $correo->Subject = utf8_decode($asunto);

            $correo->Body = utf8_decode($this->plantilla);

            $correo->send();

            return (object)[
                'message' => 'success',
                'status' => 200,
            ];
        } catch (Exception $e) {
            return (object)[
                'message' => 'Error: ' . $correo->ErrorInfo,
                'status' => 500,
            ];
        }
    }
}
