<?php
require_once 'database_config.php';

class EmailQueuePopulator {
    private $pdo;
    
    public function __construct() {
        $this->pdo = DatabaseConfig::getConnection();
    }
    
    public function populateFromJsonFiles() {
        $dataFiles = [
            '../data/data_3k.json' => '3K',
            '../data/data_5k.json' => '5K',
            '../data/data_10k.json' => '10K',
            '../data/data_21k.json' => '21K'
        ];
        
        $totalQueued = 0;
        
        foreach ($dataFiles as $filePath => $category) {
            if (file_exists($filePath)) {
                $queued = $this->processJsonFile($filePath, $category);
                $totalQueued += $queued;
                echo "Procesado $category: $queued registros añadidos a la cola\n";
            } else {
                echo "Archivo no encontrado: $filePath\n";
            }
        }
        
        // Log del proceso
        $this->logBatchProcess($totalQueued, 0, 0, 0, "Cola poblada desde archivos JSON");
        
        echo "Total de registros añadidos a la cola: $totalQueued\n";
        return $totalQueued;
    }
    
    private function processJsonFile($filePath, $category) {
        $jsonContent = file_get_contents($filePath);
        $runners = json_decode($jsonContent, true);
        
        if (!$runners) {
            echo "Error al leer el archivo JSON: $filePath\n";
            return 0;
        }
        
        $queued = 0;
        
        foreach ($runners as $runner) {
            // Solo procesar corredores que tengan email
            if (isset($runner['Email']) && !empty($runner['Email'])) {
                if ($this->addToQueue($runner, $category)) {
                    $queued++;
                }
            }
        }
        
        return $queued;
    }
    
    private function addToQueue($runner, $category) {
        try {
            $sql = "INSERT IGNORE INTO email_queue 
                    (runner_id, runner_name, email, race_category, bib_number, position, finish_time, gun_time) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
            
            $stmt = $this->pdo->prepare($sql);
            
            $runnerId = $runner['UniqueId'] ?? uniqid();
            $runnerName = $runner['Athlete'] ?? 'Sin nombre';
            $email = $runner['Email'];
            $bibNumber = $runner['Bib'] ?? 0;
            $position = $runner['Pos'] ?? 0;
            $finishTime = $runner['FinishTime'] ?? '';
            $gunTime = $runner['GunTime'] ?? '';
            
            return $stmt->execute([
                $runnerId,
                $runnerName,
                $email,
                $category,
                $bibNumber,
                $position,
                $finishTime,
                $gunTime
            ]);
            
        } catch (PDOException $e) {
            error_log("Error al añadir a la cola: " . $e->getMessage());
            return false;
        }
    }
    
    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
                FROM email_queue 
                GROUP BY status";
        
        $stmt = $this->pdo->query($sql);
        return $stmt->fetchAll();
    }
}

// Ejecución del script
if (basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME'])) {
    try {
        $populator = new EmailQueuePopulator();
        
        echo "Iniciando población de la cola de emails...\n";
        echo "==========================================\n";
        
        $totalQueued = $populator->populateFromJsonFiles();
        
        echo "\nEstadísticas de la cola:\n";
        echo "========================\n";
        $stats = $populator->getQueueStats();
        foreach ($stats as $stat) {
            echo ucfirst($stat['status']) . ": " . $stat['count'] . " registros\n";
        }
        
    } catch (Exception $e) {
        echo "Error: " . $e->getMessage() . "\n";
        exit(1);
    }
}
?>
