<?php
// Autoloader do PHPMailer
if (file_exists(BASE_PATH . '/vendor/autoload.php')) {
    require_once BASE_PATH . '/vendor/autoload.php';
    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\SMTP;
    use PHPMailer\PHPMailer\Exception;
} else {
    // Fallback se PHPMailer não estiver disponível
    logError("PHPMailer não encontrado. Emails não serão enviados.");
}

class EmailSender {
    private $mailer;
    
    public function __construct() {
        if (class_exists('PHPMailer\PHPMailer\PHPMailer')) {
            $this->mailer = new PHPMailer(true);
            $this->configureMailer();
        }
    }
    
    private function configureMailer() {
        try {
            $this->mailer->isSMTP();
            $this->mailer->Host = SMTP_HOST;
            $this->mailer->SMTPAuth = true;
            $this->mailer->Username = SMTP_USERNAME;
            $this->mailer->Password = SMTP_PASSWORD;
            $this->mailer->SMTPSecure = SMTP_ENCRYPTION;
            $this->mailer->Port = SMTP_PORT;
            $this->mailer->CharSet = 'UTF-8';
            
            // Configurar remetente
            $this->mailer->setFrom(FROM_EMAIL, FROM_NAME);
        } catch (Exception $e) {
            logError("Erro ao configurar PHPMailer: " . $e->getMessage());
        }
    }
    
    public function sendWelcomeEmail($email, $name, $unsubscribeToken) {
        if (!$this->mailer) {
            return $this->sendWelcomeEmailFallback($email, $name, $unsubscribeToken);
        }
        
        try {
            $this->mailer->clearAddresses();
            $this->mailer->addAddress($email, $name);
            
            $this->mailer->isHTML(true);
            $this->mailer->Subject = '¡Bienvenido a ' . SITE_NAME . '!';
            
            $unsubscribeUrl = SITE_URL . "/newsletter/unsubscribe.php?token=" . $unsubscribeToken;
            
            $htmlContent = $this->getWelcomeEmailTemplate($name, $unsubscribeUrl);
            $this->mailer->Body = $htmlContent;
            
            $this->mailer->send();
            return true;
        } catch (Exception $e) {
            logError("Erro ao enviar email de boas-vindas: " . $e->getMessage());
            return false;
        }
    }
    
    private function sendWelcomeEmailFallback($email, $name, $unsubscribeToken) {
        $subject = '¡Bienvenido a ' . SITE_NAME . '!';
        $unsubscribeUrl = SITE_URL . "/newsletter/unsubscribe.php?token=" . $unsubscribeToken;
        $htmlContent = $this->getWelcomeEmailTemplate($name, $unsubscribeUrl);
        
        $headers = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
        $headers .= "From: " . FROM_NAME . " <" . FROM_EMAIL . ">" . "\r\n";
        
        return mail($email, $subject, $htmlContent, $headers);
    }
    
    private function getWelcomeEmailTemplate($name, $unsubscribeUrl) {
        $displayName = $name ?: 'Amigo';
        
        return "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='UTF-8'>
            <meta name='viewport' content='width=device-width, initial-scale=1.0'>
            <title>¡Bienvenido!</title>
            <style>
                body { 
                    font-family: Arial, sans-serif; 
                    line-height: 1.6; 
                    color: #333; 
                    margin: 0; 
                    padding: 0; 
                    background-color: #f5f7fa;
                }
                .container { 
                    max-width: 600px; 
                    margin: 0 auto; 
                    padding: 20px; 
                }
                .header { 
                    background: linear-gradient(135deg, #4F46E5, #7C3AED); 
                    color: white; 
                    padding: 30px; 
                    text-align: center; 
                    border-radius: 10px 10px 0 0; 
                }
                .content { 
                    background: white; 
                    padding: 30px; 
                    border-radius: 0 0 10px 10px;
                    box-shadow: 0 5px 15px rgba(0,0,0,0.1);
                }
                .footer { 
                    background: #333; 
                    color: white; 
                    padding: 20px; 
                    text-align: center; 
                    border-radius: 10px;
                    font-size: 12px; 
                    margin-top: 20px;
                }
                .footer a { 
                    color: #ccc; 
                    text-decoration: none;
                }
                .footer a:hover {
                    color: white;
                }
                .btn { 
                    display: inline-block; 
                    padding: 12px 25px; 
                    background: #4F46E5; 
                    color: white; 
                    text-decoration: none; 
                    border-radius: 5px; 
                    margin: 15px 0; 
                    font-weight: bold;
                }
                .btn:hover {
                    background: #3730A3;
                }
                .highlight {
                    background: #F3F4F6;
                    padding: 15px;
                    border-radius: 8px;
                    margin: 20px 0;
                    border-left: 4px solid #4F46E5;
                }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h1>¡Bienvenido a " . SITE_NAME . "!</h1>
                    <p>Tu suscripción ha sido confirmada</p>
                </div>
                <div class='content'>
                    <h2>¡Hola, {$displayName}!</h2>
                    
                    <p>¡Gracias por suscribirte a nuestro boletín! Estamos emocionados de tenerte en nuestra comunidad de aprendizaje.</p>
                    
                    <div class='highlight'>
                        <h3>🎯 ¿Qué puedes esperar?</h3>
                        <ul>
                            <li><strong>Cursos gratuitos exclusivos</strong> - Acceso prioritario a nuevos cursos</li>
                            <li><strong>Contenido de valor</strong> - Tips y estrategias prácticas</li>
                            <li><strong>Ofertas especiales</strong> - Descuentos y promociones exclusivas</li>
                            <li><strong>Comunidad activa</strong> - Conecta con otros estudiantes</li>
                        </ul>
                    </div>
                    
                    <p>Nos aseguraremos de que recibas solo contenido de alta calidad que te ayude a alcanzar tus objetivos de aprendizaje.</p>
                    
                    <div style='text-align: center;'>
                        <a href='" . SITE_URL . "' class='btn'>Explorar Cursos Gratuitos</a>
                    </div>
                    
                    <p><strong>¿Tienes alguna pregunta?</strong> No dudes en responder a este email o contactarnos.</p>
                    
                    <p>¡Feliz aprendizaje!<br>
                    El equipo de " . SITE_NAME . "</p>
                </div>
                <div class='footer'>
                    <p>Si no quieres recibir más emails, puedes <a href='{$unsubscribeUrl}'>darte de baja aquí</a></p>
                    <p>&copy; " . date('Y') . " " . SITE_NAME . ". Todos los derechos reservados.</p>
                </div>
            </div>
        </body>
        </html>";
    }
}
?>