<?php
require 'vendor/autoload.php';
require 'db2.php';

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

class EmailSender {
    private $db;
    private $mailer;
    
    public function __construct() {
        $this->db = Database::getInstance();
        $this->initMailer();
    }
    
    private function initMailer() {
        $this->mailer = new PHPMailer(true);
        $this->mailer->isSMTP();
        $this->mailer->Host = 'mail.imators.systems';
        $this->mailer->SMTPAuth = true;
        $this->mailer->Username = 'no-reply@imators.systems';
        $this->mailer->Password = 'imators.managements4455*#@';
        $this->mailer->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $this->mailer->Port = 465;
        $this->mailer->setFrom('no-reply@imators.systems', 'Imators');
        $this->mailer->isHTML(true);
        $this->mailer->CharSet = 'UTF-8';
        
        $this->mailer->XMailer = ' ';
        $this->mailer->addCustomHeader('List-Unsubscribe', '<mailto:unsubscribe@imators.com>');
        $this->mailer->addCustomHeader('Precedence', 'bulk');
    }
    
    public function sendEmails() {
        header('Content-Type: application/json');
        header('Cache-Control: no-cache');
        header('Connection: keep-alive');
        header('X-Accel-Buffering: no'); // Désactive le buffering Nginx si présent
        
        ob_implicit_flush(true);
        ob_end_flush();
        
        try {
            $users = $this->db->query("SELECT email FROM users WHERE email IS NOT NULL");
            $this->sendOutput("Démarrage de l'envoi des emails");
            
            foreach ($users as $user) {
                try {
                    $this->mailer->clearAddresses();
                    $this->mailer->addAddress($user['email']);
                    $this->mailer->Subject = "Votre sujet";
                    $this->mailer->Body = $this->getEmailTemplate();
                    $this->mailer->AltBody = "Version texte de votre email";
                    
                    $this->mailer->send();
                    $this->sendOutput("✓ Email envoyé à : {$user['email']}", 'success');
                    usleep(500000);
                    
                } catch (Exception $e) {
                    $this->sendOutput("⚠ Échec d'envoi à {$user['email']}: {$e->getMessage()}", 'error');
                }
            }
            
            $this->sendOutput("Processus terminé", 'info');
            return true;
            
        } catch (Exception $e) {
            $this->sendOutput("❌ Erreur critique: " . $e->getMessage(), 'error');
            return false;
        }
    }
    
    private function sendOutput($message, $status = 'info') {
        $output = json_encode([
            'status' => $status,
            'message' => "[" . date('Y-m-d H:i:s') . "] " . $message
        ]) . "\n";
        
        echo $output;
        if (ob_get_level() > 0) {
            ob_flush();
        }
        flush();
    }
    
    private function getEmailTemplate() {
        return '<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        .container { max-width: 600px; margin: 0 auto; padding: 20px; }
        .content { background-color: #ffffff; padding: 20px; border-radius: 8px; }
        .button { 
            display: inline-block;
            padding: 10px 20px;
            background-color: #3b82f6;
            color: #ffffff;
            text-decoration: none;
            border-radius: 4px;
        }
        .footer { margin-top: 20px; font-size: 12px; color: #64748b; }
    </style>
</head>
<body>
    <div class="container">
        <div class="content">
            <h1>Votre titre</h1>
            <p>Votre contenu personnalisé</p>
            <a href="#" class="button">Votre Call-to-Action</a>
            <div class="footer">
                <p>Pour vous désinscrire, <a href="mailto:unsubscribe@imators.com">cliquez ici</a></p>
            </div>
        </div>
    </div>
</body>
</html>';
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'send') {
    $sender = new EmailSender();
    $sender->sendEmails();
    exit;
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.tailwindcss.com"></script>
    <title>Envoi d'Emails</title>
</head>
<body class="bg-gray-50">
    <div class="max-w-4xl mx-auto p-8">
        <div class="bg-white rounded-xl shadow-lg p-6">
            <div class="flex items-center justify-between mb-6">
                <h1 class="text-2xl font-bold text-gray-800">Envoi d'Emails en Masse</h1>
                <div id="status" class="text-sm text-gray-500">Prêt</div>
            </div>

            <div class="mb-6">
                <div id="logs" class="h-96 bg-gray-50 rounded-lg p-4 overflow-y-auto font-mono text-sm">
                </div>
            </div>

            <button 
                id="startButton"
                class="w-full bg-blue-500 text-white px-6 py-3 rounded-lg hover:bg-blue-600 transition-colors"
            >
                Démarrer l'envoi
            </button>
        </div>
    </div>

    <script>
    document.getElementById('startButton').addEventListener('click', async () => {
        const button = document.getElementById('startButton');
        const logs = document.getElementById('logs');
        const status = document.getElementById('status');
        
        button.disabled = true;
        button.textContent = 'Envoi en cours...';
        status.textContent = 'En cours';
        logs.innerHTML = '';

        try {
            const response = await fetch(window.location.href, {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: 'action=send'
            });

            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let buffer = '';

            while (true) {
                const {value, done} = await reader.read();
                if (done) break;
                
                buffer += decoder.decode(value, {stream: true});
                const lines = buffer.split('\n');
                buffer = lines.pop() || '';

                for (const line of lines) {
                    if (!line.trim()) continue;
                    
                    try {
                        const logData = JSON.parse(line);
                        const logEntry = document.createElement('div');
                        logEntry.className = 'py-1';
                        logEntry.textContent = logData.message;
                        
                        switch (logData.status) {
                            case 'error':
                                logEntry.className += ' text-red-500';
                                break;
                            case 'success':
                                logEntry.className += ' text-green-500';
                                break;
                            case 'warning':
                                logEntry.className += ' text-yellow-500';
                                break;
                        }
                        
                        logs.appendChild(logEntry);
                        logs.scrollTop = logs.scrollHeight;
                    } catch (e) {
                        console.error('Erreur parsing JSON:', line, e);
                    }
                }
            }

        } catch (error) {
            const errorLog = document.createElement('div');
            errorLog.className = 'py-1 text-red-500';
            errorLog.textContent = `Erreur: ${error.message}`;
            logs.appendChild(errorLog);
        }

        status.textContent = 'Terminé';
        button.textContent = 'Terminé';
        button.disabled = false;
    });
    </script>
</body>
</html>