<?php
/**
 * Endpoint para obtener logs según filtros
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

try {
    $tab = $_GET['tab'] ?? 'live';
    $file = $_GET['file'] ?? '';
    $limit = intval($_GET['limit'] ?? 100);
    
    $logDir = __DIR__ . '/logs';
    $logs = [];
    $stats = [
        'total' => 0,
        'critical' => 0,
        'recent' => 0
    ];
    
    if (!is_dir($logDir)) {
        echo json_encode(['logs' => [], 'stats' => $stats]);
        exit;
    }
    
    // Determinar qué archivos leer según el tab
    $filesToRead = [];
    
    switch ($tab) {
        case 'frontend':
            $filesToRead = glob($logDir . '/frontend_errors_*.log');
            break;
            
        case 'backend':
            $filesToRead = glob($logDir . '/add_note_errors_*.log');
            break;
            
        case 'critical':
            $filesToRead = glob($logDir . '/critical_errors.log');
            break;
            
        case 'live':
        default:
            if ($file && file_exists($logDir . '/' . $file)) {
                $filesToRead = [$logDir . '/' . $file];
            } else {
                $filesToRead = glob($logDir . '/*.log');
            }
            break;
    }
    
    // Leer logs de los archivos
    foreach ($filesToRead as $logFile) {
        if (!file_exists($logFile)) continue;
        
        $lines = file($logFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        
        foreach ($lines as $line) {
            $logEntry = parseLogLine($line);
            if ($logEntry) {
                $logs[] = $logEntry;
                
                // Actualizar estadísticas
                $stats['total']++;
                
                if (isCriticalError($logEntry)) {
                    $stats['critical']++;
                }
                
                if (isRecentError($logEntry)) {
                    $stats['recent']++;
                }
            }
        }
    }
    
    // Ordenar por timestamp (más reciente primero)
    usort($logs, function($a, $b) {
        return strtotime($b['timestamp']) - strtotime($a['timestamp']);
    });
    
    // Limitar resultados
    $logs = array_slice($logs, 0, $limit);
    
    echo json_encode([
        'logs' => $logs,
        'stats' => $stats,
        'files_read' => count($filesToRead)
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'error' => 'Error obteniendo logs: ' . $e->getMessage(),
        'logs' => [],
        'stats' => ['total' => 0, 'critical' => 0, 'recent' => 0]
    ]);
}

function parseLogLine($line) {
    // Formato: TIMESTAMP | JSON_DATA
    $parts = explode(' | ', $line, 2);
    
    if (count($parts) < 2) {
        return null;
    }
    
    $timestamp = $parts[0];
    $jsonData = $parts[1];
    
    // Intentar decodificar JSON
    $data = json_decode($jsonData, true);
    
    if (!$data) {
        // Si no es JSON, tratar como mensaje simple
        return [
            'timestamp' => $timestamp,
            'message' => $jsonData,
            'type' => 'Simple Log',
            'context' => null
        ];
    }
    
    // Extraer información del JSON
    return [
        'timestamp' => $data['timestamp'] ?? $timestamp,
        'message' => $data['message'] ?? 'Sin mensaje',
        'type' => $data['type'] ?? 'Unknown',
        'context' => $data['context'] ?? $data['error_data'] ?? null,
        'stack_trace' => $data['stack_trace'] ?? null,
        'url' => $data['url'] ?? null,
        'user_agent' => $data['user_agent'] ?? null,
        'remote_addr' => $data['remote_addr'] ?? null
    ];
}

function isCriticalError($logEntry) {
    $criticalKeywords = ['critical', 'fatal', 'conexión', 'connection', 'database'];
    
    $message = strtolower($logEntry['message']);
    $type = strtolower($logEntry['type'] ?? '');
    
    foreach ($criticalKeywords as $keyword) {
        if (strpos($message, $keyword) !== false || strpos($type, $keyword) !== false) {
            return true;
        }
    }
    
    return false;
}

function isRecentError($logEntry) {
    $timestamp = strtotime($logEntry['timestamp']);
    $fiveMinutesAgo = time() - (5 * 60);
    
    return $timestamp > $fiveMinutesAgo;
}
?>