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

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

// Carregamento das classes PHPMailer [cite: 259, 267]
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;

/**
 * Configura o servidor SMTP para envios pagos
 */
function configurarMailerParaAnuncioPago() {
    $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';

        // Segurança: Limpeza de aspas no remetente [cite: 167, 179]
        $fromName = str_replace(['"', "'"], '', ($_ENV['SMTP_FROM_NAME'] ?? 'Selflix Vagas'));
        $mail->setFrom($_ENV['SMTP_FROM_EMAIL'] ?? '', $fromName);

        $mail->SMTPDebug = 0; 

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

/**
 * MOTOR DINÂMICO: Busca o template no banco e substitui as {{tags}}
 */
function enviarEmailVagaPagoDinamico($pdo, $email_destinatario, $slug_template, $dados) {
    // 1. Busca template no banco de dados [cite: 508]
    $stmt = $pdo->prepare("SELECT assunto, corpo FROM EmailTemplates WHERE slug = :slug");
    $stmt->execute([':slug' => $slug_template]);
    $template = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$template) {
        error_log("Template Pago não encontrado: " . $slug_template);
        return false;
    }

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

    // 2. Substitui as {{tags}} pelos valores reais enviados pelo processamento [cite: 519]
    foreach ($dados as $chave => $valor) {
        $placeholder = "{{" . $chave . "}}";
        $assunto = str_replace($placeholder, $valor, $assunto);
        $corpo   = str_replace($placeholder, $valor, $corpo);
    }

    // 3. Envio via PHPMailer
    $mail = configurarMailerParaAnuncioPago();
    if (!$mail) return false;

    try {
        $mail->addAddress($email_destinatario);
        $mail->isHTML(true);
        $mail->Subject = $assunto;
        $mail->Body    = $corpo;
        $mail->AltBody = strip_tags($corpo);

        return $mail->send();
    } catch (Exception $e) {
        error_log("Erro no envio dinâmico Pago ($slug_template): " . $mail->ErrorInfo);
        return false;
    }
}