<?php
/**
 * ZLO Platform - Mailer
 * Email sending system with PHPMailer
 */

declare(strict_types=1);

// Include PHPMailer (you need to install it via Composer or download manually)
// require_once __DIR__ . '/../../vendor/autoload.php';
// use PHPMailer\PHPMailer\PHPMailer;
// use PHPMailer\PHPMailer\Exception;

class Mailer
{
    private array $config;
    private string $fromEmail;
    private string $fromName;
    
    public function __construct()
    {
        $this->config = require __DIR__ . '/../config/config.php';
        $this->fromEmail = $this->config['mail']['from']['address'];
        $this->fromName = $this->config['mail']['from']['name'];
    }
    
    /**
     * Send email using PHP mail() or SMTP
     */
    public function send(string $to, string $subject, string $body, array $options = []): bool
    {
        $headers = $this->buildHeaders($options);
        
        // Use SMTP if configured
        if ($this->config['mail']['driver'] === 'smtp') {
            return $this->sendSMTP($to, $subject, $body, $options);
        }
        
        // Fallback to PHP mail()
        return mail($to, $subject, $body, $headers);
    }
    
    /**
     * Send email using SMTP (PHPMailer)
     */
    private function sendSMTP(string $to, string $subject, string $body, array $options = []): bool
    {
        // This requires PHPMailer to be installed
        // Uncomment when PHPMailer is available
        
        /*
        try {
            $mail = new PHPMailer(true);
            
            // Server settings
            $mail->isSMTP();
            $mail->Host = $this->config['mail']['host'];
            $mail->SMTPAuth = true;
            $mail->Username = $this->config['mail']['username'];
            $mail->Password = $this->config['mail']['password'];
            $mail->SMTPSecure = $this->config['mail']['encryption'];
            $mail->Port = $this->config['mail']['port'];
            
            // Recipients
            $mail->setFrom($this->fromEmail, $this->fromName);
            $mail->addAddress($to);
            
            // Content
            $mail->isHTML(true);
            $mail->Subject = $subject;
            $mail->Body = $body;
            
            // CC and BCC
            if (!empty($options['cc'])) {
                foreach ((array) $options['cc'] as $cc) {
                    $mail->addCC($cc);
                }
            }
            
            if (!empty($options['bcc'])) {
                foreach ((array) $options['bcc'] as $bcc) {
                    $mail->addBCC($bcc);
                }
            }
            
            // Attachments
            if (!empty($options['attachments'])) {
                foreach ((array) $options['attachments'] as $attachment) {
                    $mail->addAttachment($attachment);
                }
            }
            
            $mail->send();
            return true;
        } catch (Exception $e) {
            error_log("Mailer Error: " . $e->getMessage());
            return false;
        }
        */
        
        // Fallback to mail() for now
        return $this->sendMail($to, $subject, $body, $options);
    }
    
    /**
     * Send email using PHP mail()
     */
    private function sendMail(string $to, string $subject, string $body, array $options = []): bool
    {
        $headers = "MIME-Version: 1.0\r\n";
        $headers .= "Content-type: text/html; charset=UTF-8\r\n";
        $headers .= "From: {$this->fromName} <{$this->fromEmail}>\r\n";
        
        if (!empty($options['reply_to'])) {
            $headers .= "Reply-To: {$options['reply_to']}\r\n";
        }
        
        return mail($to, $subject, $body, $headers);
    }
    
    /**
     * Build email headers
     */
    private function buildHeaders(array $options): string
    {
        $headers = "MIME-Version: 1.0\r\n";
        $headers .= "Content-type: text/html; charset=UTF-8\r\n";
        $headers .= "From: {$this->fromName} <{$this->fromEmail}>\r\n";
        
        if (!empty($options['reply_to'])) {
            $headers .= "Reply-To: {$options['reply_to']}\r\n";
        }
        
        return $headers;
    }
    
    /**
     * Send lead notification to admin
     */
    public function sendLeadNotification(array $leadData): bool
    {
        $subject = "Nouveau lead: {$leadData['first_name']} {$leadData['last_name']}";
        
        $body = $this->getEmailTemplate('lead_notification', [
            'name' => $leadData['first_name'] . ' ' . $leadData['last_name'],
            'email' => $leadData['email'],
            'phone' => $leadData['phone'] ?? 'Non renseigné',
            'company' => $leadData['company'] ?? 'Non renseigné',
            'message' => $leadData['message'] ?? 'Aucun message',
            'date' => date('d/m/Y H:i')
        ]);
        
        return $this->send($this->config['mail']['from']['address'], $subject, $body);
    }
    
    /**
     * Send contact form notification
     */
    public function sendContactNotification(array $contactData): bool
    {
        $subject = "Nouveau message de contact: {$contactData['name']}";
        
        $body = $this->getEmailTemplate('contact_notification', [
            'name' => $contactData['name'],
            'email' => $contactData['email'],
            'subject' => $contactData['subject'] ?? 'Sans sujet',
            'message' => nl2br($contactData['message']),
            'date' => date('d/m/Y H:i')
        ]);
        
        return $this->send($this->config['mail']['from']['address'], $subject, $body, [
            'reply_to' => $contactData['email']
        ]);
    }
    
    /**
     * Send demo request confirmation
     */
    public function sendDemoConfirmation(array $demoData): bool
    {
        $subject = "Confirmation de votre demande de démo - ZLO Technologies";
        
        $body = $this->getEmailTemplate('demo_confirmation', [
            'name' => $demoData['first_name'],
            'solution' => $demoData['solution'] ?? 'Non spécifié',
            'date' => date('d/m/Y H:i')
        ]);
        
        return $this->send($demoData['email'], $subject, $body);
    }
    
    /**
     * Send welcome email to new user
     */
    public function sendWelcomeEmail(array $userData): bool
    {
        $subject = "Bienvenue sur ZLO Technologies";
        
        $body = $this->getEmailTemplate('welcome', [
            'name' => $userData['name'],
            'login_url' => $this->config['app']['url'] . '/admin/',
            'email' => $userData['email']
        ]);
        
        return $this->send($userData['email'], $subject, $body);
    }
    
    /**
     * Send password reset email
     */
    public function sendPasswordReset(string $email, string $token): bool
    {
        $subject = "Réinitialisation de votre mot de passe";
        
        $resetUrl = $this->config['app']['url'] . '/admin/reset-password?token=' . $token;
        
        $body = $this->getEmailTemplate('password_reset', [
            'reset_url' => $resetUrl,
            'expiry' => '24 heures'
        ]);
        
        return $this->send($email, $subject, $body);
    }
    
    /**
     * Send newsletter subscription confirmation
     */
    public function sendNewsletterConfirmation(string $email): bool
    {
        $subject = "Confirmation d'inscription à la newsletter";
        
        $body = $this->getEmailTemplate('newsletter_confirmation', [
            'unsubscribe_url' => $this->config['app']['url'] . '/newsletter/unsubscribe?email=' . urlencode($email)
        ]);
        
        return $this->send($email, $subject, $body);
    }
    
    /**
     * Get email template
     */
    private function getEmailTemplate(string $template, array $data): string
    {
        $templates = [
            'lead_notification' => $this->getLeadNotificationTemplate(),
            'contact_notification' => $this->getContactNotificationTemplate(),
            'demo_confirmation' => $this->getDemoConfirmationTemplate(),
            'welcome' => $this->getWelcomeTemplate(),
            'password_reset' => $this->getPasswordResetTemplate(),
            'newsletter_confirmation' => $this->getNewsletterConfirmationTemplate()
        ];
        
        $template = $templates[$template] ?? '';
        
        // Replace placeholders
        foreach ($data as $key => $value) {
            $template = str_replace('{{' . $key . '}}', $value, $template);
        }
        
        return $this->wrapInLayout($template);
    }
    
    /**
     * Wrap content in email layout
     */
    private function wrapInLayout(string $content): string
    {
        return <<<HTML
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ZLO Technologies</title>
    <style>
        body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif; line-height: 1.6; color: #333; margin: 0; padding: 0; background: #f5f5f5; }
        .container { max-width: 600px; margin: 0 auto; background: white; }
        .header { background: linear-gradient(135deg, #0066FF, #0052CC); padding: 30px; text-align: center; }
        .header h1 { color: white; margin: 0; font-size: 24px; }
        .content { padding: 30px; }
        .footer { background: #1A1A2E; color: white; padding: 20px 30px; text-align: center; font-size: 12px; }
        .footer a { color: #0066FF; }
        .btn { display: inline-block; background: #0066FF; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px; margin: 10px 0; }
        .info-box { background: #f8f9fa; border-left: 4px solid #0066FF; padding: 15px; margin: 15px 0; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1><span style="color: white;">ZLO</span>Technologies</h1>
        </div>
        <div class="content">
            {$content}
        </div>
        <div class="footer">
            <p>&copy; 2024 ZLO Technologies. Tous droits réservés.</p>
            <p>Digital Innovation for Africa</p>
        </div>
    </div>
</body>
</html>
HTML;
    }
    
    /**
     * Lead notification template
     */
    private function getLeadNotificationTemplate(): string
    {
        return <<<HTML
<h2>Nouveau lead reçu</h2>

<div class="info-box">
    <p><strong>Nom:</strong> {{name}}</p>
    <p><strong>Email:</strong> {{email}}</p>
    <p><strong>Téléphone:</strong> {{phone}}</p>
    <p><strong>Entreprise:</strong> {{company}}</p>
    <p><strong>Date:</strong> {{date}}</p>
</div>

<h3>Message:</h3>
<p>{{message}}</p>

<p><a href="{{admin_url}}" class="btn">Voir dans l'admin</a></p>
HTML;
    }
    
    /**
     * Contact notification template
     */
    private function getContactNotificationTemplate(): string
    {
        return <<<HTML
<h2>Nouveau message de contact</h2>

<div class="info-box">
    <p><strong>Nom:</strong> {{name}}</p>
    <p><strong>Email:</strong> {{email}}</p>
    <p><strong>Sujet:</strong> {{subject}}</p>
    <p><strong>Date:</strong> {{date}}</p>
</div>

<h3>Message:</h3>
<p>{{message}}</p>

<p><a href="{{admin_url}}" class="btn">Répondre</a></p>
HTML;
    }
    
    /**
     * Demo confirmation template
     */
    private function getDemoConfirmationTemplate(): string
    {
        return <<<HTML
<h2>Bonjour {{name}},</h2>

<p>Merci d'avoir demandé une démonstration de <strong>{{solution}}</strong>.</p>

<p>Notre équipe commerciale vous contactera sous 24 heures ouvrées pour planifier votre démonstration personnalisée.</p>

<div class="info-box">
    <p><strong>Prochaines étapes:</strong></p>
    <ul>
        <li>Un conseiller vous contactera par téléphone ou email</li>
        <li>Nous discuterons de vos besoins spécifiques</li>
        <li>Nous planifierons une démo adaptée à votre entreprise</li>
    </ul>
</div>

<p>En attendant, n'hésitez pas à consulter nos ressources:</p>
<p><a href="{{resources_url}}" class="btn">Voir nos ressources</a></p>

<p>Cordialement,<br>L'équipe ZLO Technologies</p>
HTML;
    }
    
    /**
     * Welcome template
     */
    private function getWelcomeTemplate(): string
    {
        return <<<HTML
<h2>Bienvenue {{name}} !</h2>

<p>Votre compte a été créé avec succès sur la plateforme ZLO Technologies.</p>

<div class="info-box">
    <p><strong>Email:</strong> {{email}}</p>
    <p><strong>URL de connexion:</strong> {{login_url}}</p>
</div>

<p><a href="{{login_url}}" class="btn">Se connecter</a></p>

<p>Si vous avez des questions, n'hésitez pas à contacter notre support.</p>

<p>Cordialement,<br>L'équipe ZLO Technologies</p>
HTML;
    }
    
    /**
     * Password reset template
     */
    private function getPasswordResetTemplate(): string
    {
        return <<<HTML
<h2>Réinitialisation de mot de passe</h2>

<p>Vous avez demandé la réinitialisation de votre mot de passe.</p>

<p>Cliquez sur le lien ci-dessous pour créer un nouveau mot de passe:</p>

<p><a href="{{reset_url}}" class="btn">Réinitialiser mon mot de passe</a></p>

<div class="info-box">
    <p><strong>Important:</strong> Ce lien expire dans {{expiry}}.</p>
    <p>Si vous n'avez pas demandé cette réinitialisation, ignorez cet email.</p>
</div>

<p>Cordialement,<br>L'équipe ZLO Technologies</p>
HTML;
    }
    
    /**
     * Newsletter confirmation template
     */
    private function getNewsletterConfirmationTemplate(): string
    {
        return <<<HTML
<h2>Merci pour votre inscription !</h2>

<p>Vous êtes maintenant abonné à la newsletter de ZLO Technologies.</p>

<p>Vous recevrez régulièrement:</p>
<ul>
    <li>Les dernières actualités sur la tech en Afrique</li>
    <li>Des études de cas et témoignages clients</li>
    <li>Des conseils pour optimiser votre entreprise</li>
    <li>Des invitations à nos événements</li>
</ul>

<div class="info-box">
    <p>Vous pouvez vous désabonner à tout moment en cliquant sur le lien dans nos emails.</p>
</div>

<p>Cordialement,<br>L'équipe ZLO Technologies</p>
HTML;
    }
}
