<?php
// include/emails-anuncios/gratuito.php

if (!defined('BASE_PATH')) {
    define('BASE_PATH', realpath(__DIR__ . '/../../')); 
}

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

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception as PHPMailerException;
use PHPMailer\PHPMailer\SMTP;

function configurarMailerParaAnuncioGratuito() {
    $mail = new PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host       = $_ENV['SMTP_HOST'] ?? '';
        $mail->SMTPAuth   = filter_var(($_ENV['SMTP_AUTH'] ?? true), FILTER_VALIDATE_BOOLEAN);
        $mail->Username   = $_ENV['SMTP_USERNAME'] ?? '';
        $mail->Password   = $_ENV['SMTP_PASSWORD'] ?? '';
        
        $smtp_secure_env = strtolower($_ENV['SMTP_SECURE'] ?? 'ssl');
        $mail->SMTPSecure = ($smtp_secure_env === 'tls') ? PHPMailer::ENCRYPTION_STARTTLS : PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port       = (int)($_ENV['SMTP_PORT'] ?? 465);
        $mail->CharSet    = 'UTF-8';

        $fromName = str_replace(['"', "'"], '', ($_ENV['SMTP_FROM_NAME'] ?? 'Selflix Vagas'));
        $mail->setFrom($_ENV['SMTP_FROM_EMAIL'] ?? '', $fromName);
        $mail->SMTPDebug = SMTP::DEBUG_OFF; 

        return $mail;
    } catch (PHPMailerException $e) {
        error_log("Erro ao configurar PHPMailer: " . $e->getMessage());
        return null;
    }
}

function processarTemplateEmail($pdo, $slug, $dados) {
    $stmt = $pdo->prepare("SELECT assunto, corpo FROM EmailTemplates WHERE slug = :slug");
    $stmt->execute([':slug' => $slug]);
    $template = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$template) return null;

    $assunto = $template['assunto'];
    $corpo = $template['corpo'];

    foreach ($dados as $chave => $valor) {
        $placeholder = "{{" . $chave . "}}";
        $assunto = str_replace($placeholder, $valor, $assunto);
        $corpo = str_replace($placeholder, $valor, $corpo);
    }

    return ['assunto' => $assunto, 'corpo' => $corpo];
}

function enviarEmailVagaGratuitaDinamico($pdo, $email_destinatario, $slug_template, $dados_vaga) {
    $mail = configurarMailerParaAnuncioGratuito();
    if (!$mail) return false;

    $conteudo = processarTemplateEmail($pdo, $slug_template, $dados_vaga);
    if (!$conteudo) return false;

    try {
        $mail->addAddress($email_destinatario);
        $mail->isHTML(true);
        $mail->Subject = $conteudo['assunto'];
        $mail->Body    = $conteudo['corpo'];
        $mail->AltBody = strip_tags($conteudo['corpo']);
        return $mail->send();
    } catch (PHPMailerException $e) {
        error_log("Erro no envio: " . $mail->ErrorInfo);
        return false;
    }
}