<?php
require_once 'database_config.php';

class MassEmailSender {
    private $pdo;
    private $apiKey;
    private $senderName;
    private $senderEmail;
    private $batchSize;
    private $maxAttempts;
    private $statsBaseUrl;
    
    public function __construct() {
        $this->pdo = DatabaseConfig::getConnection();
        $this->apiKey = DatabaseConfig::BREVO_API_KEY;
        $this->senderName = DatabaseConfig::SENDER_NAME;
        $this->senderEmail = DatabaseConfig::SENDER_EMAIL;
        $this->batchSize = DatabaseConfig::BATCH_SIZE;
        $this->maxAttempts = DatabaseConfig::MAX_ATTEMPTS;
        $this->statsBaseUrl = DatabaseConfig::STATS_BASE_URL;
    }
    
    public function processEmailQueue() {
        $startTime = microtime(true);
        $totalSent = 0;
        $totalFailed = 0;
        
        echo "[" . date('Y-m-d H:i:s') . "] Iniciando procesamiento de cola de emails...\n";
        
        // Obtener emails pendientes
        $pendingEmails = $this->getPendingEmails();
        $totalPending = count($pendingEmails);
        
        if ($totalPending === 0) {
            echo "[" . date('Y-m-d H:i:s') . "] No hay emails pendientes para enviar.\n";
            return;
        }
        
        echo "[" . date('Y-m-d H:i:s') . "] Encontrados $totalPending emails pendientes.\n";
        
        // Procesar en lotes
        $batches = array_chunk($pendingEmails, $this->batchSize);
        
        foreach ($batches as $batchIndex => $batch) {
            $batchNumber = $batchIndex + 1;
            $batchSize = count($batch);
            
            echo "[" . date('Y-m-d H:i:s') . "] Procesando lote $batchNumber ($batchSize emails)...\n";
            
            foreach ($batch as $emailData) {
                $result = $this->sendCertificateEmail($emailData);
                
                if ($result['success']) {
                    $this->markEmailAsSent($emailData['id']);
                    $totalSent++;
                    echo "✓ Enviado a: {$emailData['email']} ({$emailData['runner_name']})\n";
                } else {
                    $this->markEmailAsFailed($emailData['id'], $result['error']);
                    $totalFailed++;
                    echo "✗ Error enviando a: {$emailData['email']} - {$result['error']}\n";
                }
                
                // Pequeña pausa entre emails para evitar rate limiting
                usleep(100000); // 0.1 segundos
            }
            
            // Pausa entre lotes
            if ($batchNumber < count($batches)) {
                echo "[" . date('Y-m-d H:i:s') . "] Pausa entre lotes...\n";
                sleep(DatabaseConfig::DELAY_BETWEEN_BATCHES);
            }
        }
        
        $executionTime = round(microtime(true) - $startTime, 2);
        
        // Log del proceso
        $this->logBatchProcess(0, $totalSent, $totalFailed, $executionTime, 
            "Procesamiento automático - Lotes: " . count($batches));
        
        echo "[" . date('Y-m-d H:i:s') . "] Proceso completado:\n";
        echo "  - Emails enviados: $totalSent\n";
        echo "  - Emails fallidos: $totalFailed\n";
        echo "  - Tiempo de ejecución: {$executionTime}s\n";
    }
    
    private function getPendingEmails() {
        $sql = "SELECT * FROM email_queue 
                WHERE status = 'pending' 
                AND attempts < ? 
                ORDER BY created_at ASC 
                LIMIT ?";
        
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([$this->maxAttempts, $this->batchSize]);
        
        return $stmt->fetchAll();
    }
    
    private function sendCertificateEmail($emailData) {
        try {
            // Actualizar intentos
            $this->incrementAttempts($emailData['id']);
            
            // Generar el contenido HTML del certificado
            $certificateHtml = $this->generateCertificateHtml($emailData);
            
            // Generar el contenido del email
            $emailHtml = $this->generateEmailHtml($emailData, $certificateHtml);
            
            // Enviar email usando Brevo API
            return $this->sendEmailViaBrevo($emailData['email'], $emailHtml, $emailData);
            
        } catch (Exception $e) {
            return [
                'success' => false,
                'error' => 'Error interno: ' . $e->getMessage()
            ];
        }
    }
    
    private function generateCertificateHtml($emailData) {
        $statsUrl = $this->statsBaseUrl . $emailData['runner_id'];
        
        // Generar un código QR simple (en un entorno real, usar una librería de QR)
        $qrData = "https://resultados.cronoh.mx/espn_2025/certificado.html?id=" . $emailData['runner_id'];
        
        return "
        <div style='background-color: white; max-width: 100%; margin: 0 auto; position: relative; 
                    box-shadow: 0 10px 30px rgba(0,0,0,0.3); font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;'>
            
            <!-- Header -->
            <div style='min-height: 80px; width: 100%; background-color: black; position: relative; 
                        display: flex; justify-content: center; align-items: center; padding: 15px 20px;'>
                <div style='color: white; text-align: center; width: 100%;'>
                    <div style='color: #ffffff; font-size: 18px; font-weight: 900; text-transform: uppercase; 
                                letter-spacing: 2px; text-shadow: 0 2px 4px rgba(0,0,0,0.3); margin: 0; line-height: 1.3;'>
                        Reconocimiento Oficial
                    </div>
                    <div style='color: #ffffff; font-size: 12px; margin-top: 8px; line-height: 1.2;'>
                        ID de Verificación: <span style='font-weight: bold; font-family: monospace; letter-spacing: 1px; 
                        background-color: rgba(255, 255, 255, 0.2); padding: 3px 8px; border-radius: 4px;'>{$emailData['runner_id']}</span>
                    </div>
                </div>
            </div>
            
            <!-- Body -->
            <div style='padding: 30px 20px; text-align: center; position: relative; min-height: 500px; background-color: white;'>
                
                <!-- Event Image -->
                <div style='margin-bottom: 20px;'>
                    <img src='https://resultados.cronoh.mx/espn_2025/assets/images/head.jpg' alt='Imagen del evento' 
                         style='width: 100%; height: auto; margin: 0 auto;'>
                </div>
                
                <!-- Recognition Label -->
                <div style='text-align: center; color: #666; font-size: 18px; margin-bottom: 5px;'>Reconocemos a:</div>
                
                <!-- Runner Name -->
                <h2 style='font-size: 28px; font-weight: 700; color: #1d3557; margin-bottom: 15px;'>
                    {$emailData['runner_name']}
                </h2>
                
                <!-- Category Label -->
                <div style='text-align: center; color: #666; font-size: 18px; margin-bottom: 5px;'>CATEGORÍA:</div>
                <div style='font-size: 20px; color: #1d3557; font-weight: 700; margin-bottom: 10px;'>
                    {$emailData['race_category']}
                </div>
                
                <!-- Description -->
                <p style='font-size: 16px; line-height: 1.5; color: #666; margin-bottom: 25px; 
                          max-width: 600px; margin-left: auto; margin-right: auto;'>
                    Ha completado exitosamente la carrera con los siguientes resultados:
                </p>
                
                <!-- Stats -->
                <div style='display: flex; justify-content: center; gap: 15px; margin: 30px auto; flex-wrap: wrap; max-width: 600px;'>
                    <div style='background-color: white; border-radius: 10px; padding: 15px; text-align: center; 
                                box-shadow: 0 3px 10px rgba(0,0,0,0.1); position: relative; min-width: 110px; flex: 1;
                                border-top: 5px solid black; margin: 5px;'>
                        <div style='font-size: 12px; color: #666; margin-bottom: 8px; font-weight: 500;'>Distancia</div>
                        <div style='font-size: 18px; font-weight: 700; color: #1d3557;'>{$emailData['race_category']}</div>
                    </div>
                    <div style='background-color: white; border-radius: 10px; padding: 15px; text-align: center; 
                                box-shadow: 0 3px 10px rgba(0,0,0,0.1); position: relative; min-width: 110px; flex: 1;
                                border-top: 5px solid black; margin: 5px;'>
                        <div style='font-size: 12px; color: #666; margin-bottom: 8px; font-weight: 500;'>Posición</div>
                        <div style='font-size: 18px; font-weight: 700; color: #1d3557;'>#{$emailData['position']}</div>
                    </div>
                    <div style='background-color: white; border-radius: 10px; padding: 15px; text-align: center; 
                                box-shadow: 0 3px 10px rgba(0,0,0,0.1); position: relative; min-width: 110px; flex: 1;
                                border-top: 5px solid black; margin: 5px;'>
                        <div style='font-size: 12px; color: #666; margin-bottom: 8px; font-weight: 500;'>Tiempo Chip</div>
                        <div style='font-size: 16px; font-weight: 700; color: #1d3557; font-family: monospace;'>{$emailData['finish_time']}</div>
                    </div>
                    " . (!empty($emailData['gun_time']) ? "
                    <div style='background-color: white; border-radius: 10px; padding: 15px; text-align: center; 
                                box-shadow: 0 3px 10px rgba(0,0,0,0.1); position: relative; min-width: 110px; flex: 1;
                                border-top: 5px solid black; margin: 5px;'>
                        <div style='font-size: 12px; color: #666; margin-bottom: 8px; font-weight: 500;'>Tiempo Oficial</div>
                        <div style='font-size: 18px; font-weight: 700; color: #1d3557; font-family: monospace;'>{$emailData['gun_time']}</div>
                    </div>
                    " : "") . "
                </div>
                

            </div>
            
            <!-- Footer -->
            <div style='background-color: #f8f9fa; padding: 20px; text-align: center; 
                        border-top: 4px solid black;'>
                <div style='margin-bottom: 15px;'>
                    <a href='https://resultados.cronoh.mx/espn_2025/certificado.html?id={$emailData['runner_id']}' style='display: inline-block; background-color: #2a9d8f; color: white; 
                       padding: 12px 24px; text-decoration: none; border-radius: 6px; font-weight: bold; 
                       font-size: 14px; margin-right: 10px; margin-bottom: 10px;' target='_blank'>
                        📜 Descargar Certificado
                    </a>
                    <a href='https://resultados.cronoh.mx/espn_2025/index.html?openModal={$emailData['runner_id']}' style='display: inline-block; background-color: black; color: white; 
                       padding: 12px 24px; text-decoration: none; border-radius: 6px; font-weight: bold; 
                       font-size: 14px; margin-bottom: 10px;' target='_blank'>
                        🏃‍♂️ Ver Estadísticas Completas
                    </a>
                </div>
                <div style='color: #666; font-size: 12px;'>
                    <p style='margin: 5px 0;'>" . date('d \d\e F \d\e Y') . "</p>
                </div>
            </div>
        </div>";
    }
    
    private function generateEmailHtml($emailData, $certificateHtml) {
        $statsUrl = $this->statsBaseUrl . $emailData['runner_id'];
        
        return "
        <!DOCTYPE html>
        <html lang='es'>
        <head>
            <meta charset='UTF-8'>
            <meta name='viewport' content='width=device-width, initial-scale=1.0'>
            <title>Tu Certificado de Participación</title>
            <style>
                :root {
                    --primary-color: black;
                    --secondary-color: #457b9d;
                    --dark-color: #1d3557;
                    --light-color: #f1faee;
                    --success-color: #2a9d8f;
                    --warning-color: #e9c46a;
                }
                
                * {
                    margin: 0;
                    padding: 0;
                    box-sizing: border-box;
                    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                }
                
                body {
                    background-color: #f5f5f5;
                    color: #333;
                    line-height: 1.6;
                }
                
                .email-container {
                    max-width: 800px;
                    margin: 0 auto;
                    background: white;
                    border-radius: 10px;
                    overflow: hidden;
                    box-shadow: 0 5px 15px rgba(0,0,0,0.1);
                }
                
                .email-header {
                    background: black;
                    color: white;
                    padding: 30px;
                    text-align: center;
                }
                
                .email-content {
                    padding: 30px;
                }
                
                .social-buttons {
                    display: flex;
                    justify-content: center;
                    gap: 15px;
                    margin: 20px 0;
                }
                
                .social-button {
                    display: inline-block;
                    width: 40px;
                    height: 40px;
                    border-radius: 50%;
                    text-align: center;
                    line-height: 40px;
                    color: white;
                    text-decoration: none;
                    font-weight: bold;
                }
                
                .facebook { background-color: #3b5998; }
                .twitter { background-color: #1da1f2; }
                .whatsapp { background-color: #25d366; }
                .instagram { background-color: #e1306c; }
                
                .cta-button {
                    display: inline-block;
                    background: black;
                    color: white;
                    padding: 12px 30px;
                    text-decoration: none;
                    border-radius: 6px;
                    margin: 10px;
                    font-weight: bold;
                }
                
                .email-footer {
                    background: #f8f9fa;
                    padding: 20px;
                    text-align: center;
                    color: #666;
                    font-size: 12px;
                    border-top: 1px solid #eee;
                }
                
                /* Media Queries para móvil */
                @media only screen and (max-width: 600px) {
                    .email-container {
                        margin: 0 !important;
                        border-radius: 0 !important;
                    }
                    
                    .email-header h1 {
                        font-size: 20px !important;
                    }
                    
                    .email-header p {
                        font-size: 12px !important;
                    }
                    
                    .email-content {
                        padding: 20px !important;
                    }
                    
                    .email-content p {
                        font-size: 14px !important;
                    }
                }
            </style>
        </head>
        <body>
            <div class='email-container'>
                
                <!-- Header del Email -->
                <div class='email-header' style='background: black; color: white; padding: 30px; text-align: center;'>
                    <h1 style='margin: 0; font-size: 24px;'>¡Felicidades {$emailData['runner_name']}!</h1>
                    <p style='margin: 10px 0 0 0; font-size: 14px; color: white;'>
                        Tu certificado de participación está listo
                    </p>
                </div>
                
                <!-- Contenido Principal -->
                <div class='email-content'>
                    <p style='font-size: 16px; margin-bottom: 20px; text-align: center;'>
                        Cada paso en tu entrenamiento te trajo hasta aquí, y aquí y ahora comienza tu próxima aventura. ¡Felicidades!
                    </p>
                    
                    <!-- Certificado -->
                    <div style='text-align: center; margin: 30px 0;'>
                        $certificateHtml
                    </div>
                </div>
                
                <!-- Footer del Email -->
                <div class='email-footer'>
                    <p style='margin: 0;'>
                        Este email fue generado automáticamente.
                    </p>
                </div>
                
            </div>
        </body>
        </html>";
    }
    
    private function sendEmailViaBrevo($email, $htmlContent, $emailData) {
        $payload = [
            'sender' => [
                'name' => $this->senderName,
                'email' => $this->senderEmail
            ],
            'to' => [
                ['email' => $email, 'name' => $emailData['runner_name']]
            ],
            'subject' => "🏃‍♂️ Tu certificado de participación",
            'htmlContent' => $htmlContent
        ];
        
        $ch = curl_init('https://api.brevo.com/v3/smtp/email');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'api-key: ' . $this->apiKey,
            'Content-Type: application/json',
            'accept: application/json'
        ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        curl_close($ch);
        
        if ($curlError) {
            return [
                'success' => false,
                'error' => 'Error cURL: ' . $curlError
            ];
        }
        
        if ($httpCode >= 200 && $httpCode < 300) {
            return ['success' => true];
        } else {
            $errorData = json_decode($response, true);
            $errorMessage = isset($errorData['message']) ? $errorData['message'] : 'Error HTTP: ' . $httpCode;
            return [
                'success' => false,
                'error' => $errorMessage
            ];
        }
    }
    
    private function markEmailAsSent($emailId) {
        $sql = "UPDATE email_queue 
                SET status = 'sent', sent_at = NOW() 
                WHERE id = ?";
        
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([$emailId]);
    }
    
    private function markEmailAsFailed($emailId, $errorMessage) {
        $sql = "UPDATE email_queue 
                SET status = 'failed', last_attempt_at = NOW(), error_message = ? 
                WHERE id = ?";
        
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([$errorMessage, $emailId]);
    }
    
    private function incrementAttempts($emailId) {
        $sql = "UPDATE email_queue 
                SET attempts = attempts + 1, last_attempt_at = NOW() 
                WHERE id = ?";
        
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([$emailId]);
    }
    
    private function logBatchProcess($totalQueued, $totalSent, $totalFailed, $executionTime, $notes) {
        try {
            $sql = "INSERT INTO email_batch_log 
                    (total_queued, total_sent, total_failed, execution_time, notes) 
                    VALUES (?, ?, ?, ?, ?)";
            
            $stmt = $this->pdo->prepare($sql);
            $stmt->execute([$totalQueued, $totalSent, $totalFailed, $executionTime, $notes]);
        } catch (PDOException $e) {
            error_log("Error al registrar log del lote: " . $e->getMessage());
        }
    }
    
    public function getQueueStats() {
        $sql = "SELECT 
                    status,
                    COUNT(*) as count,
                    race_category
                FROM email_queue 
                GROUP BY status, race_category
                ORDER BY race_category, status";
        
        $stmt = $this->pdo->query($sql);
        return $stmt->fetchAll();
    }
    
    public function resetFailedEmails() {
        $sql = "UPDATE email_queue 
                SET status = 'pending', attempts = 0, error_message = NULL 
                WHERE status = 'failed' AND attempts < ?";
        
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([$this->maxAttempts]);
        
        return $stmt->rowCount();
    }
}

// Ejecución del script
if (basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME'])) {
    try {
        $sender = new MassEmailSender();
        $sender->processEmailQueue();
        
    } catch (Exception $e) {
        echo "[" . date('Y-m-d H:i:s') . "] Error fatal: " . $e->getMessage() . "\n";
        exit(1);
    }
}
?>
