<?php

declare(strict_types=1);

namespace App\Helpers;

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

class MailHelper
{
    /**
     * Cria instância configurada do PHPMailer
     */
    public static function create(): PHPMailer
    {
        $mail = new PHPMailer(true);

        try {
            // Configurações do servidor
            $mail->isSMTP();
            $mail->Host       = $_ENV['MAIL_HOST'] ?? 'smtp.gmail.com';
            $mail->SMTPAuth   = true;
            $mail->Username   = $_ENV['MAIL_USERNAME'] ?? '';
            $mail->Password   = $_ENV['MAIL_PASSWORD'] ?? '';

            // Configurar encryption baseado na porta
            $port = (int) ($_ENV['MAIL_PORT'] ?? 587);
            $encryption = $_ENV['MAIL_ENCRYPTION'] ?? 'tls';

            if ($port == 465) {
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; // SSL
            } elseif ($encryption == 'ssl') {
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            } else {
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // TLS
            }

            $mail->Port       = $port;
            $mail->CharSet    = 'UTF-8';

            // Timeouts
            $mail->Timeout = 30; // Timeout de conexão (30 segundos)
            $mail->SMTPKeepAlive = false; // Não manter conexão aberta

            // Remetente padrão
            $mail->setFrom(
                $_ENV['MAIL_FROM_ADDRESS'] ?? 'noreply@sistema.com.br',
                $_ENV['MAIL_FROM_NAME'] ?? 'Sistema ERP'
            );

            // Debug (desabilitado por padrão)
            $mail->SMTPDebug = 0;

            // Opções adicionais para compatibilidade
            $mail->SMTPOptions = array(
                'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true
                )
            );

        } catch (Exception $e) {
            error_log("Erro ao configurar PHPMailer: " . $e->getMessage());
        }

        return $mail;
    }

    /**
     * Envia e-mail com anexo
     * @return array ['success' => bool, 'message' => string]
     */
    public static function sendWithAttachment(
        string $to,
        string $subject,
        string $body,
        string $attachmentPath,
        string $attachmentName
    ): array {
        $mail = self::create();

        try {
            // Destinatário
            $mail->addAddress($to);

            // Conteúdo
            $mail->isHTML(true);
            $mail->Subject = $subject;
            $mail->Body    = $body;
            $mail->AltBody = strip_tags($body);

            // Anexo
            if (file_exists($attachmentPath)) {
                $mail->addAttachment($attachmentPath, $attachmentName);
            } else {
                return ['success' => false, 'message' => 'Arquivo de anexo não encontrado'];
            }

            // Enviar
            $result = $mail->send();

            if ($result) {
                return ['success' => true, 'message' => 'E-mail enviado com sucesso'];
            }

            return ['success' => false, 'message' => 'Falha ao enviar e-mail'];

        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => $mail->ErrorInfo ?: $e->getMessage()
            ];
        }
    }

    /**
     * Envia e-mail simples (sem anexo)
     */
    public static function send(string $to, string $subject, string $body): bool
    {
        try {
            $mail = self::create();

            // Destinatário
            $mail->addAddress($to);

            // Conteúdo
            $mail->isHTML(true);
            $mail->Subject = $subject;
            $mail->Body    = $body;
            $mail->AltBody = strip_tags($body);

            // Enviar
            return $mail->send();

        } catch (Exception $e) {
            error_log("Erro ao enviar e-mail: " . $mail->ErrorInfo);
            error_log("Exception: " . $e->getMessage());
            return false;
        }
    }
}

