<?php
require_once __DIR__ . '/../../config/bootstrap.php';
require_once __DIR__ . '/../../includes/require-auth.php';

use App\Services\AuthService;
use App\Services\SecurityService;
use App\Services\Database;

$auth = new AuthService();
$security = new SecurityService();
$db = Database::getInstance();

$user = requireAuth($auth);
$adminId = $user['id'];
$rol = $user['rol'] ?? 'asesor';

requireRole('administrador', $rol);

// ============================================================
// Filtros
// ============================================================
$filterTipo   = $security->sanitizeString($_GET['tipo'] ?? '');
$filterNivel  = $security->sanitizeString($_GET['nivel'] ?? '');
$filterAccion = $security->sanitizeString($_GET['accion'] ?? '');
$filterIp     = $security->sanitizeString($_GET['ip'] ?? '');
$filterSearch = $security->sanitizeString($_GET['search'] ?? '');
$filterFecha  = $security->sanitizeString($_GET['fecha'] ?? '');
$page = max(1, (int) ($_GET['page'] ?? 1));
$perPage = 50;
$offset = ($page - 1) * $perPage;

// Construir WHERE dinámico
$where = '1=1';
$params = [];

$tipos  = ['admin', 'firma', 'api', 'security', 'error'];
$niveles = ['debug', 'info', 'warning', 'error', 'critical'];

if ($filterTipo && in_array($filterTipo, $tipos, true)) {
    $where .= ' AND al.tipo = :tipo';
    $params[':tipo'] = $filterTipo;
}
if ($filterNivel && in_array($filterNivel, $niveles, true)) {
    $where .= ' AND al.nivel = :nivel';
    $params[':nivel'] = $filterNivel;
}
if (!empty($filterAccion)) {
    $where .= ' AND al.accion LIKE :accion';
    $params[':accion'] = "%{$filterAccion}%";
}
if (!empty($filterIp)) {
    $where .= ' AND al.ip_address LIKE :ip';
    $params[':ip'] = "%{$filterIp}%";
}
if (!empty($filterSearch)) {
    $where .= ' AND (al.descripcion LIKE :search OR al.accion LIKE :search2 OR al.ip_address LIKE :search3)';
    $params[':search']  = "%{$filterSearch}%";
    $params[':search2'] = "%{$filterSearch}%";
    $params[':search3'] = "%{$filterSearch}%";
}
if (!empty($filterFecha)) {
    $where .= ' AND DATE(al.created_at) = :fecha';
    $params[':fecha'] = $filterFecha;
}

// Total para paginación
$total = $db->fetchOne(
    "SELECT COUNT(*) as c FROM access_logs al WHERE {$where}",
    $params
)['c'] ?? 0;

$totalPages = max(1, ceil($total / $perPage));

// Obtener logs con datos del admin
$logs = $db->fetchAll(
    "SELECT al.*, a.nombre as admin_nombre, a.email as admin_email
     FROM access_logs al
     LEFT JOIN admins a ON al.usuario_id = a.id
     WHERE {$where}
     ORDER BY al.created_at DESC
     LIMIT {$perPage} OFFSET {$offset}",
    $params
);

// Estadísticas rápidas (últimas 24h)
$stats24h = $db->fetchOne(
    "SELECT
        COUNT(*) as total,
        SUM(CASE WHEN nivel = 'error' OR nivel = 'critical' THEN 1 ELSE 0 END) as errores,
        SUM(CASE WHEN nivel = 'warning' THEN 1 ELSE 0 END) as warnings,
        SUM(CASE WHEN tipo = 'security' THEN 1 ELSE 0 END) as security_events,
        COUNT(DISTINCT ip_address) as ips_unicas
     FROM access_logs
     WHERE created_at > DATE_SUB(NOW(), INTERVAL 24 HOUR)"
);

// IPs con más actividad (posibles bots/ataques)
$topIps = $db->fetchAll(
    "SELECT ip_address, COUNT(*) as total, MAX(created_at) as ultimo
     FROM access_logs
     WHERE created_at > DATE_SUB(NOW(), INTERVAL 24 HOUR)
     GROUP BY ip_address
     ORDER BY total DESC
     LIMIT 5"
);
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Access Logs - Admin</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        * { font-family: 'Inter', sans-serif; -webkit-font-smoothing: antialiased; letter-spacing: -0.011em; }
        .font-mono { font-family: 'Courier New', Courier, monospace; }
        .log-row:hover .log-details { display: block; }
        .log-details { display: none; }
    </style>
</head>
<body class="bg-gray-50 flex flex-col min-h-screen">

    <?php include __DIR__ . '/../../includes/admin-nav.php'; ?>

    <main class="flex-1 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 w-full">

        <!-- Header -->
        <div class="mb-8 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
            <div>
                <h1 class="text-3xl font-bold text-gray-900">Access Logs</h1>
                <p class="mt-1 text-sm text-gray-600">Auditoría completa de actividad del sistema</p>
            </div>
            <a href="?<?= http_build_query(array_merge($_GET, ['export' => '1'])) ?>"
               class="inline-flex items-center px-4 py-2 bg-gray-800 text-white rounded-lg hover:bg-gray-900 text-sm font-medium transition">
                <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/>
                </svg>
                Exportar CSV
            </a>
        </div>

        <!-- Stats 24h -->
        <div class="grid grid-cols-2 sm:grid-cols-5 gap-4 mb-6">
            <?php
            $statCards = [
                ['label' => 'Total (24h)', 'value' => number_format($stats24h['total'] ?? 0), 'color' => 'indigo', 'icon' => 'M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2'],
                ['label' => 'Errores',    'value' => number_format($stats24h['errores'] ?? 0), 'color' => 'red',    'icon' => 'M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z'],
                ['label' => 'Warnings',   'value' => number_format($stats24h['warnings'] ?? 0),'color' => 'yellow', 'icon' => 'M12 9v2m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z'],
                ['label' => 'Seguridad',  'value' => number_format($stats24h['security_events'] ?? 0), 'color' => 'orange', 'icon' => 'M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z'],
                ['label' => 'IPs únicas', 'value' => number_format($stats24h['ips_unicas'] ?? 0), 'color' => 'purple', 'icon' => 'M3.055 11H5a2 2 0 012 2v1a2 2 0 002 2 2 2 0 012 2v2.945M8 3.935V5.5A2.5 2.5 0 0010.5 8h.5a2 2 0 012 2 2 2 0 104 0 2 2 0 012-2h1.064M15 20.488V18a2 2 0 012-2h3.064'],
            ];
            foreach ($statCards as $card):
                $colors = [
                    'indigo' => ['bg' => 'bg-indigo-50', 'icon' => 'text-indigo-600', 'text' => 'text-indigo-700'],
                    'red'    => ['bg' => 'bg-red-50',    'icon' => 'text-red-600',    'text' => 'text-red-700'],
                    'yellow' => ['bg' => 'bg-yellow-50', 'icon' => 'text-yellow-600', 'text' => 'text-yellow-700'],
                    'orange' => ['bg' => 'bg-orange-50', 'icon' => 'text-orange-600', 'text' => 'text-orange-700'],
                    'purple' => ['bg' => 'bg-purple-50', 'icon' => 'text-purple-600', 'text' => 'text-purple-700'],
                ];
                $c = $colors[$card['color']];
            ?>
            <div class="bg-white rounded-lg shadow p-4">
                <div class="flex items-center gap-3">
                    <div class="<?= $c['bg'] ?> rounded-lg p-2">
                        <svg class="w-5 h-5 <?= $c['icon'] ?>" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="<?= $card['icon'] ?>"/>
                        </svg>
                    </div>
                    <div>
                        <p class="text-xs text-gray-500"><?= $card['label'] ?></p>
                        <p class="text-xl font-bold <?= $c['text'] ?>"><?= $card['value'] ?></p>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-4 gap-6">

            <!-- Sidebar: Top IPs -->
            <div class="lg:col-span-1">
                <div class="bg-white rounded-lg shadow p-5 mb-5">
                    <h3 class="text-sm font-semibold text-gray-700 mb-3 flex items-center gap-2">
                        <svg class="w-4 h-4 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/>
                        </svg>
                        Top IPs (24h)
                    </h3>
                    <?php if (empty($topIps)): ?>
                    <p class="text-xs text-gray-400">Sin datos</p>
                    <?php else: ?>
                    <div class="space-y-2">
                        <?php foreach ($topIps as $i => $ip): ?>
                        <div class="flex items-center justify-between">
                            <div>
                                <a href="?ip=<?= urlencode($ip['ip_address']) ?>"
                                   class="text-xs font-mono text-indigo-600 hover:text-indigo-800"><?= htmlspecialchars($ip['ip_address']) ?></a>
                            </div>
                            <span class="text-xs font-semibold <?= $ip['total'] > 100 ? 'text-red-600 bg-red-50' : 'text-gray-600 bg-gray-100' ?> px-2 py-0.5 rounded-full">
                                <?= number_format($ip['total']) ?>
                            </span>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>
                </div>

                <!-- Filtros rápidos de tipo -->
                <div class="bg-white rounded-lg shadow p-5">
                    <h3 class="text-sm font-semibold text-gray-700 mb-3">Filtrar por Tipo</h3>
                    <div class="space-y-1">
                        <?php
                        $typeCounts = $db->fetchAll("SELECT tipo, COUNT(*) as c FROM access_logs WHERE created_at > DATE_SUB(NOW(), INTERVAL 7 DAY) GROUP BY tipo");
                        $typeMap = [];
                        foreach ($typeCounts as $t) $typeMap[$t['tipo']] = $t['c'];
                        $typeColors = ['admin' => 'indigo', 'firma' => 'green', 'api' => 'blue', 'security' => 'orange', 'error' => 'red'];
                        ?>
                        <a href="?" class="flex items-center justify-between px-3 py-2 rounded-lg hover:bg-gray-50 <?= !$filterTipo ? 'bg-gray-100 font-medium' : '' ?> text-sm text-gray-700">
                            <span>Todos</span>
                        </a>
                        <?php foreach ($tipos as $t): ?>
                        <a href="?tipo=<?= $t ?><?= $filterNivel ? '&nivel='.$filterNivel : '' ?>"
                           class="flex items-center justify-between px-3 py-2 rounded-lg hover:bg-gray-50 <?= $filterTipo === $t ? 'bg-indigo-50 text-indigo-700 font-medium' : 'text-gray-600' ?> text-sm">
                            <span class="capitalize"><?= $t ?></span>
                            <span class="text-xs bg-gray-100 text-gray-500 px-1.5 py-0.5 rounded"><?= number_format($typeMap[$t] ?? 0) ?></span>
                        </a>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>

            <!-- Main: Logs table -->
            <div class="lg:col-span-3">

                <!-- Filtros avanzados -->
                <div class="bg-white rounded-lg shadow mb-4 p-4">
                    <form method="GET" class="flex flex-wrap gap-2">
                        <?php if ($filterTipo): ?>
                        <input type="hidden" name="tipo" value="<?= htmlspecialchars($filterTipo) ?>">
                        <?php endif; ?>
                        <input type="text" name="search" placeholder="Buscar en logs..."
                            value="<?= htmlspecialchars($filterSearch) ?>"
                            class="flex-1 min-w-40 px-3 py-1.5 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500">
                        <input type="text" name="ip" placeholder="Filtrar IP..."
                            value="<?= htmlspecialchars($filterIp) ?>"
                            class="w-36 px-3 py-1.5 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500 font-mono">
                        <select name="nivel" class="px-3 py-1.5 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500">
                            <option value="">Nivel</option>
                            <?php foreach ($niveles as $n): ?>
                            <option value="<?= $n ?>" <?= $filterNivel === $n ? 'selected' : '' ?>><?= ucfirst($n) ?></option>
                            <?php endforeach; ?>
                        </select>
                        <input type="date" name="fecha" value="<?= htmlspecialchars($filterFecha) ?>"
                            class="px-3 py-1.5 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500">
                        <button type="submit" class="px-4 py-1.5 bg-indigo-600 text-white rounded-lg text-sm font-medium hover:bg-indigo-700">Filtrar</button>
                        <?php if ($filterSearch || $filterIp || $filterNivel || $filterFecha || $filterTipo): ?>
                        <a href="?" class="px-4 py-1.5 bg-gray-100 text-gray-600 rounded-lg text-sm font-medium hover:bg-gray-200">Limpiar</a>
                        <?php endif; ?>
                    </form>
                </div>

                <!-- Resultado -->
                <div class="text-xs text-gray-500 mb-2 flex items-center justify-between">
                    <span><?= number_format($total) ?> registros encontrados (página <?= $page ?> de <?= $totalPages ?>)</span>
                    <span>Mostrando <?= count($logs) ?> de <?= $perPage ?> por página</span>
                </div>

                <!-- Tabla -->
                <div class="bg-white rounded-lg shadow overflow-hidden">
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200 text-sm">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-36">Fecha</th>
                                    <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-20">Tipo</th>
                                    <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-20">Nivel</th>
                                    <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Acción / Descripción</th>
                                    <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-32">IP</th>
                                    <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-28">Usuario</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-100">
                                <?php if (empty($logs)): ?>
                                <tr>
                                    <td colspan="6" class="px-4 py-10 text-center text-gray-400 text-sm">
                                        No se encontraron registros con los filtros actuales
                                    </td>
                                </tr>
                                <?php else: ?>
                                <?php foreach ($logs as $log):
                                    $nivelColors = [
                                        'debug'    => 'bg-gray-100 text-gray-600',
                                        'info'     => 'bg-blue-50 text-blue-700',
                                        'warning'  => 'bg-yellow-50 text-yellow-700',
                                        'error'    => 'bg-red-50 text-red-700',
                                        'critical' => 'bg-red-100 text-red-800 font-bold'
                                    ];
                                    $tipoColors = [
                                        'admin'    => 'bg-indigo-50 text-indigo-700',
                                        'firma'    => 'bg-green-50 text-green-700',
                                        'api'      => 'bg-blue-50 text-blue-700',
                                        'security' => 'bg-orange-50 text-orange-700',
                                        'error'    => 'bg-red-50 text-red-700'
                                    ];
                                    $nivelClass = $nivelColors[$log['nivel']] ?? 'bg-gray-100 text-gray-600';
                                    $tipoClass  = $tipoColors[$log['tipo']] ?? 'bg-gray-100 text-gray-600';
                                    $detalles   = $log['detalles'] ? json_decode($log['detalles'], true) : [];
                                    $rowBg = ($log['nivel'] === 'error' || $log['nivel'] === 'critical') ? 'bg-red-50/30' : '';
                                ?>
                                <tr class="log-row hover:bg-gray-50 <?= $rowBg ?> cursor-pointer" onclick="toggleDetails(<?= $log['id'] ?>)">
                                    <td class="px-4 py-3 font-mono text-xs text-gray-500 whitespace-nowrap">
                                        <?= date('d/m/Y H:i:s', strtotime($log['created_at'])) ?>
                                    </td>
                                    <td class="px-4 py-3">
                                        <span class="inline-block px-2 py-0.5 rounded text-xs font-medium <?= $tipoClass ?>">
                                            <?= htmlspecialchars($log['tipo']) ?>
                                        </span>
                                    </td>
                                    <td class="px-4 py-3">
                                        <span class="inline-block px-2 py-0.5 rounded text-xs font-medium <?= $nivelClass ?>">
                                            <?= htmlspecialchars($log['nivel']) ?>
                                        </span>
                                    </td>
                                    <td class="px-4 py-3">
                                        <div class="font-medium text-gray-800 text-xs"><?= htmlspecialchars($log['accion']) ?></div>
                                        <?php if ($log['descripcion']): ?>
                                        <div class="text-xs text-gray-500 mt-0.5 truncate max-w-xs"><?= htmlspecialchars($log['descripcion']) ?></div>
                                        <?php endif; ?>
                                        <!-- Detalle expandible -->
                                        <div id="details-<?= $log['id'] ?>" class="hidden mt-2 pt-2 border-t border-gray-100">
                                            <div class="grid grid-cols-2 gap-x-4 gap-y-1 text-xs">
                                                <?php if ($log['user_agent']): ?>
                                                <div class="col-span-2">
                                                    <span class="text-gray-400">User-Agent:</span>
                                                    <span class="text-gray-600 ml-1 break-all"><?= htmlspecialchars(substr($log['user_agent'], 0, 120)) ?></span>
                                                </div>
                                                <?php endif; ?>
                                                <?php if ($log['contract_id']): ?>
                                                <div>
                                                    <span class="text-gray-400">Contrato ID:</span>
                                                    <a href="<?= base_url('admin/ver-contrato') ?>?id=<?= $log['contract_id'] ?>" class="text-indigo-600 ml-1">#<?= $log['contract_id'] ?></a>
                                                </div>
                                                <?php endif; ?>
                                                <?php if (!empty($detalles)): ?>
                                                <div class="col-span-2 mt-1">
                                                    <span class="text-gray-400">Detalles:</span>
                                                    <pre class="mt-1 bg-gray-50 rounded p-2 text-xs text-gray-700 overflow-x-auto"><?= htmlspecialchars(json_encode($detalles, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)) ?></pre>
                                                </div>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="px-4 py-3 font-mono text-xs text-gray-600 whitespace-nowrap">
                                        <a href="?ip=<?= urlencode($log['ip_address']) ?>" class="hover:text-indigo-600" onclick="event.stopPropagation()">
                                            <?= htmlspecialchars($log['ip_address']) ?>
                                        </a>
                                    </td>
                                    <td class="px-4 py-3 text-xs">
                                        <?php if ($log['admin_nombre']): ?>
                                        <div class="font-medium text-gray-700"><?= htmlspecialchars($log['admin_nombre']) ?></div>
                                        <div class="text-gray-400"><?= htmlspecialchars($log['admin_email']) ?></div>
                                        <?php else: ?>
                                        <span class="text-gray-400 italic">Sistema</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Paginación -->
                <?php if ($totalPages > 1): ?>
                <div class="mt-4 flex items-center justify-between">
                    <div class="text-sm text-gray-500">Página <?= $page ?> de <?= $totalPages ?></div>
                    <div class="flex gap-1">
                        <?php if ($page > 1): ?>
                        <a href="?<?= http_build_query(array_merge($_GET, ['page' => $page - 1])) ?>"
                           class="px-3 py-1.5 text-sm bg-white border border-gray-300 rounded-lg hover:bg-gray-50">Anterior</a>
                        <?php endif; ?>

                        <?php
                        $startPage = max(1, $page - 2);
                        $endPage   = min($totalPages, $page + 2);
                        for ($p = $startPage; $p <= $endPage; $p++):
                        ?>
                        <a href="?<?= http_build_query(array_merge($_GET, ['page' => $p])) ?>"
                           class="px-3 py-1.5 text-sm <?= $p === $page ? 'bg-indigo-600 text-white border-indigo-600' : 'bg-white border-gray-300 hover:bg-gray-50 text-gray-700' ?> border rounded-lg">
                            <?= $p ?>
                        </a>
                        <?php endfor; ?>

                        <?php if ($page < $totalPages): ?>
                        <a href="?<?= http_build_query(array_merge($_GET, ['page' => $page + 1])) ?>"
                           class="px-3 py-1.5 text-sm bg-white border border-gray-300 rounded-lg hover:bg-gray-50">Siguiente</a>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </main>

    <script>
    function toggleDetails(id) {
        const el = document.getElementById('details-' + id);
        el.classList.toggle('hidden');
    }
    </script>

    <?php include __DIR__ . '/../../includes/admin-footer.php'; ?>
</body>
</html>
<?php
// ============================================================
// Exportar CSV
// ============================================================
if (isset($_GET['export']) && $_GET['export'] === '1') {
    // Re-ejecutar sin límite
    $allLogs = $db->fetchAll(
        "SELECT al.*, a.nombre as admin_nombre, a.email as admin_email
         FROM access_logs al
         LEFT JOIN admins a ON al.usuario_id = a.id
         WHERE {$where}
         ORDER BY al.created_at DESC
         LIMIT 10000",
        $params
    );

    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="access_logs_' . date('Ymd_His') . '.csv"');
    header('Pragma: no-cache');

    $out = fopen('php://output', 'w');
    fputcsv($out, ['ID', 'Fecha', 'Tipo', 'Nivel', 'Acción', 'Descripción', 'IP', 'User-Agent', 'Admin', 'Email Admin', 'Detalles']);

    foreach ($allLogs as $log) {
        fputcsv($out, [
            $log['id'],
            $log['created_at'],
            $log['tipo'],
            $log['nivel'],
            $log['accion'],
            $log['descripcion'],
            $log['ip_address'],
            $log['user_agent'],
            $log['admin_nombre'] ?? '',
            $log['admin_email'] ?? '',
            $log['detalles'] ?? ''
        ]);
    }
    fclose($out);
    exit;
}
?>
