<?php
require_once 'config.php';
checkAccess(['programmer', 'admin', 'board']);

try {
    // 1. Obtener los últimos 500 registros para una auditoría real
    $stmt = $pdo->query("SELECT * FROM system_audit_logs ORDER BY id DESC LIMIT 500");
    $logs = $stmt->fetchAll();

    // 2. Calcular tamaño real de la tabla de logs en KB (con manejo de errores)
    $stats = ["size_kb" => 0, "count" => 0];
    
    try {
        $dbName = $pdo->query("SELECT DATABASE()")->fetchColumn();
        if ($dbName) {
            $sizeStmt = $pdo->prepare("SELECT 
                ROUND((DATA_LENGTH + INDEX_LENGTH) / 1024, 2) as size_kb
                FROM information_schema.TABLES 
                WHERE TABLE_SCHEMA = ? 
                AND TABLE_NAME = 'system_audit_logs'");
            $sizeStmt->execute([$dbName]);
            $res = $sizeStmt->fetch();
            if ($res) $stats['size_kb'] = (float)$res['size_kb'];
        }
    } catch (Exception $e) {
        // Fallback: estimar por número de registros si information_schema no es accesible
    }

    $stats['count'] = (int)$pdo->query("SELECT COUNT(*) FROM system_audit_logs")->fetchColumn();

    response([
        "logs" => $logs,
        "stats" => $stats
    ]);
} catch (PDOException $e) {
    response(["error" => "SERVER_ERROR", "details" => $e->getMessage()], 500);
}
?>