<?php
/**
 * API - Obtener logs del sistema
 * Fecha: 12 de enero de 2026 
 */

require_once '../config/config.php';

// Verificar autenticación
requireAuthentication();

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
header('Access-Control-Allow-Headers: Content-Type');

try {
    $db = Database::getInstance();
    
    $limit = intval($_GET['limit'] ?? 50);
    $offset = intval($_GET['offset'] ?? 0);
    $type = $_GET['type'] ?? 'system'; // 'system' o 'webhook'
    
    if ($limit > 100) $limit = 100; // Máximo 100 registros
    
    // Verificar qué tablas existen
    $existingTables = $db->fetchAll("SHOW TABLES");
    $tableNames = array_column($existingTables, 'Tables_in_' . DB_NAME);
    
    $logs = [];
    
    if ($type === 'webhook' && in_array('webhook_logs', $tableNames)) {
        // Logs de webhook (formato original)
        $logs = $db->fetchAll(
            "SELECT 
                id,
                status_code,
                ip_address, 
                created_at,
                SUBSTRING(request_body, 1, 100) as request_preview,
                SUBSTRING(response_body, 1, 100) as response_preview,
                'webhook' as source,
                'INFO' as level,
                CONCAT('Webhook request - Status: ', COALESCE(status_code, 'N/A')) as message
             FROM webhook_logs 
             ORDER BY created_at DESC 
             LIMIT ? OFFSET ?",
            [$limit, $offset]
        );
        
    } else {
        // Logs del sistema
        if (!in_array('system_logs', $tableNames)) {
            // Crear tabla de logs del sistema
            $createLogsSQL = "CREATE TABLE IF NOT EXISTS system_logs (
                id INT AUTO_INCREMENT PRIMARY KEY,
                datetime DATETIME DEFAULT CURRENT_TIMESTAMP,
                level ENUM('ERROR', 'WARNING', 'INFO', 'DEBUG', 'SUCCESS') DEFAULT 'INFO',
                message TEXT NOT NULL,
                source VARCHAR(255) DEFAULT 'Sistema',
                data JSON,
                user_id INT,
                ip_address VARCHAR(45),
                user_agent TEXT,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                INDEX idx_datetime (datetime),
                INDEX idx_level (level),
                INDEX idx_source (source)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
            
            $db->execute($createLogsSQL);
            
            // Insertar logs de ejemplo
            $exampleLogs = [
                [
                    'level' => 'INFO',
                    'message' => 'Sistema de WhatsApp Bot iniciado correctamente',
                    'source' => 'Sistema',
                    'ip_address' => $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1'
                ],
                [
                    'level' => 'SUCCESS', 
                    'message' => 'Módulo de respuestas automáticas cargado',
                    'source' => 'AutoResponse',
                    'ip_address' => $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1'
                ],
                [
                    'level' => 'INFO',
                    'message' => 'Sistema de menús inicializado',
                    'source' => 'MenuSystem',
                    'ip_address' => $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1'
                ],
                [
                    'level' => 'WARNING',
                    'message' => 'Verificar configuración de tokens WhatsApp',
                    'source' => 'Config',
                    'ip_address' => $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1'
                ]
            ];
            
            foreach ($exampleLogs as $log) {
                $db->insert('system_logs', $log);
            }
        }
        
        $logs = $db->fetchAll(
            "SELECT 
                id,
                datetime,
                level,
                message,
                source,
                data,
                ip_address,
                created_at
             FROM system_logs 
             ORDER BY datetime DESC, id DESC
             LIMIT ? OFFSET ?",
            [$limit, $offset]
        );
    }
    
    echo json_encode([
        'success' => true,
        'data' => $logs,
        'total' => count($logs),
        'type' => $type,
        'message' => 'Logs cargados correctamente'
    ]);
    
} catch (Exception $e) {
    error_log("Error en get_logs.php: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Error interno del servidor',
        'debug' => $e->getMessage(),
        'data' => []
    ]);
}
?>