<?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);

// ============================================================
// Helpers de parsing de User-Agent
// ============================================================
function parseUserAgent(string $ua): array
{
    $result = [
        'browser'       => 'Desconocido',
        'browser_ver'   => '',
        'engine'        => '',
        'os'            => 'Desconocido',
        'os_ver'        => '',
        'device_type'   => 'Desktop',
        'device_brand'  => '',
        'device_model'  => '',
        'is_bot'        => false,
        'is_mobile'     => false,
        'is_tablet'     => false,
        'raw'           => $ua,
    ];

    if (empty($ua) || $ua === 'Unknown') return $result;

    // Detectar bots
    $botPatterns = ['bot', 'crawl', 'spider', 'slurp', 'googlebot', 'bingbot', 'yandex', 'facebot', 'ia_archiver', 'wget', 'curl', 'python', 'scrapy'];
    foreach ($botPatterns as $bot) {
        if (stripos($ua, $bot) !== false) {
            $result['is_bot'] = true;
            $result['browser'] = 'Bot/Crawler';
            $result['device_type'] = 'Bot';
            return $result;
        }
    }

    // Sistema operativo
    if (preg_match('/Windows NT ([\d.]+)/i', $ua, $m)) {
        $winVer = ['10.0' => '10/11', '6.3' => '8.1', '6.2' => '8', '6.1' => '7', '6.0' => 'Vista', '5.1' => 'XP'];
        $result['os'] = 'Windows';
        $result['os_ver'] = $winVer[$m[1]] ?? $m[1];
    } elseif (preg_match('/Mac OS X ([\d_]+)/i', $ua, $m)) {
        $result['os'] = 'macOS';
        $result['os_ver'] = str_replace('_', '.', $m[1]);
    } elseif (preg_match('/iPhone OS ([\d_]+)/i', $ua, $m)) {
        $result['os'] = 'iOS';
        $result['os_ver'] = str_replace('_', '.', $m[1]);
        $result['is_mobile'] = true;
        $result['device_type'] = 'Mobile';
        $result['device_brand'] = 'Apple';
        $result['device_model'] = 'iPhone';
    } elseif (preg_match('/iPad; CPU OS ([\d_]+)/i', $ua, $m)) {
        $result['os'] = 'iOS';
        $result['os_ver'] = str_replace('_', '.', $m[1]);
        $result['is_tablet'] = true;
        $result['device_type'] = 'Tablet';
        $result['device_brand'] = 'Apple';
        $result['device_model'] = 'iPad';
    } elseif (preg_match('/Android ([\d.]+)/i', $ua, $m)) {
        $result['os'] = 'Android';
        $result['os_ver'] = $m[1];
        if (stripos($ua, 'Mobile') !== false) {
            $result['is_mobile'] = true;
            $result['device_type'] = 'Mobile';
        } else {
            $result['is_tablet'] = true;
            $result['device_type'] = 'Tablet';
        }
    } elseif (stripos($ua, 'Linux') !== false) {
        $result['os'] = 'Linux';
        if (preg_match('/Ubuntu\/([\d.]+)/i', $ua, $m)) $result['os_ver'] = 'Ubuntu ' . $m[1];
    } elseif (stripos($ua, 'CrOS') !== false) {
        $result['os'] = 'ChromeOS';
    }

    // Marca Android
    if ($result['os'] === 'Android') {
        $brands = ['Samsung', 'Xiaomi', 'Huawei', 'OPPO', 'Vivo', 'OnePlus', 'Motorola', 'LG', 'Sony', 'Nokia', 'Realme'];
        foreach ($brands as $brand) {
            if (stripos($ua, $brand) !== false) {
                $result['device_brand'] = $brand;
                break;
            }
        }
    }

    // Navegador (orden importa: Edge antes que Chrome)
    if (preg_match('/Edg\/([\d.]+)/i', $ua, $m)) {
        $result['browser']     = 'Microsoft Edge';
        $result['browser_ver'] = $m[1];
        $result['engine']      = 'Blink';
    } elseif (preg_match('/OPR\/([\d.]+)/i', $ua, $m) || preg_match('/Opera\/([\d.]+)/i', $ua, $m)) {
        $result['browser']     = 'Opera';
        $result['browser_ver'] = $m[1];
        $result['engine']      = 'Blink';
    } elseif (preg_match('/SamsungBrowser\/([\d.]+)/i', $ua, $m)) {
        $result['browser']     = 'Samsung Browser';
        $result['browser_ver'] = $m[1];
        $result['engine']      = 'Blink';
    } elseif (preg_match('/UCBrowser\/([\d.]+)/i', $ua, $m)) {
        $result['browser']     = 'UC Browser';
        $result['browser_ver'] = $m[1];
    } elseif (preg_match('/Chrome\/([\d.]+)/i', $ua, $m)) {
        $result['browser']     = 'Chrome';
        $result['browser_ver'] = $m[1];
        $result['engine']      = 'Blink';
    } elseif (preg_match('/Firefox\/([\d.]+)/i', $ua, $m)) {
        $result['browser']     = 'Firefox';
        $result['browser_ver'] = $m[1];
        $result['engine']      = 'Gecko';
    } elseif (preg_match('/Safari\/([\d.]+)/i', $ua, $m) && preg_match('/Version\/([\d.]+)/i', $ua, $mv)) {
        $result['browser']     = 'Safari';
        $result['browser_ver'] = $mv[1];
        $result['engine']      = 'WebKit';
    } elseif (preg_match('/MSIE ([\d.]+)/i', $ua, $m) || preg_match('/Trident\/.*rv:([\d.]+)/i', $ua, $m)) {
        $result['browser']     = 'Internet Explorer';
        $result['browser_ver'] = $m[1];
        $result['engine']      = 'Trident';
    }

    return $result;
}

// ============================================================
// Recopilar y guardar tracking del visitante actual (admin)
// ============================================================
$trackingFile = storage_path('logs/user_tracking.json');

// Asegurar directorio
if (!is_dir(dirname($trackingFile))) {
    mkdir(dirname($trackingFile), 0755, true);
}

// Cargar tracking existente
$trackingData = [];
if (file_exists($trackingFile)) {
    $raw = file_get_contents($trackingFile);
    $trackingData = json_decode($raw, true) ?? [];
}

// Guardar visita del admin actual a esta página
$clientIp  = $security->getClientIP();
$clientUA  = $security->getUserAgent();
$parsedUA  = parseUserAgent($clientUA);

// Aceptar cabeceras del navegador
$acceptLang = $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? '';
$language = '';
if (preg_match('/^([a-z]{2}(?:-[A-Z]{2})?)/i', $acceptLang, $lm)) {
    $language = $lm[1];
}

$visitEntry = [
    'timestamp'      => date('Y-m-d H:i:s'),
    'timestamp_unix' => time(),
    'admin_id'       => $adminId,
    'admin_nombre'   => $user['nombre'],
    'admin_email'    => $user['email'],
    'ip'             => $clientIp,
    'ip_info'        => [
        'is_private' => filter_var($clientIp, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false,
        'headers_detected' => [
            'cf_ip'          => $_SERVER['HTTP_CF_CONNECTING_IP'] ?? null,
            'x_forwarded'    => $_SERVER['HTTP_X_FORWARDED_FOR'] ?? null,
            'x_real_ip'      => $_SERVER['HTTP_X_REAL_IP'] ?? null,
            'remote_addr'    => $_SERVER['REMOTE_ADDR'] ?? null,
        ]
    ],
    'browser'        => $parsedUA,
    'http_headers'   => [
        'host'            => $_SERVER['HTTP_HOST'] ?? '',
        'referer'         => $_SERVER['HTTP_REFERER'] ?? '',
        'accept'          => $_SERVER['HTTP_ACCEPT'] ?? '',
        'accept_encoding' => $_SERVER['HTTP_ACCEPT_ENCODING'] ?? '',
        'accept_language' => $acceptLang,
        'language_primary'=> $language,
        'connection'      => $_SERVER['HTTP_CONNECTION'] ?? '',
        'cache_control'   => $_SERVER['HTTP_CACHE_CONTROL'] ?? '',
        'dnt'             => $_SERVER['HTTP_DNT'] ?? '',
        'upgrade_insecure'=> $_SERVER['HTTP_UPGRADE_INSECURE_REQUESTS'] ?? '',
        'sec_fetch_site'  => $_SERVER['HTTP_SEC_FETCH_SITE'] ?? '',
        'sec_fetch_mode'  => $_SERVER['HTTP_SEC_FETCH_MODE'] ?? '',
        'sec_fetch_dest'  => $_SERVER['HTTP_SEC_FETCH_DEST'] ?? '',
        'sec_ch_ua'       => $_SERVER['HTTP_SEC_CH_UA'] ?? '',
        'sec_ch_ua_mobile'=> $_SERVER['HTTP_SEC_CH_UA_MOBILE'] ?? '',
        'sec_ch_ua_platform' => $_SERVER['HTTP_SEC_CH_UA_PLATFORM'] ?? '',
    ],
    'server'         => [
        'protocol'   => $_SERVER['SERVER_PROTOCOL'] ?? '',
        'method'     => $_SERVER['REQUEST_METHOD'] ?? '',
        'uri'        => $_SERVER['REQUEST_URI'] ?? '',
        'port'       => $_SERVER['SERVER_PORT'] ?? '',
        'https'      => $security->isSecureConnection() ? 'yes' : 'no',
    ],
    'fingerprint'    => md5($clientIp . $clientUA . date('Y-m-d')),
    'page'           => 'user-tracker.php',
];

// Mantener máximo 500 registros (FIFO)
$trackingData[] = $visitEntry;
if (count($trackingData) > 500) {
    $trackingData = array_slice($trackingData, -500);
}

file_put_contents($trackingFile, json_encode($trackingData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), LOCK_EX);

// ============================================================
// Obtener tracking enriquecido de la BD (access_logs + signatures)
// ============================================================
$page = max(1, (int) ($_GET['page'] ?? 1));
$perPage = 40;
$offset = ($page - 1) * $perPage;

$filterIp   = $security->sanitizeString($_GET['ip'] ?? '');
$filterType = $security->sanitizeString($_GET['source'] ?? '');

$whereDB = '1=1';
$paramsDB = [];
if (!empty($filterIp)) {
    $whereDB .= ' AND ip_address LIKE :ip';
    $paramsDB[':ip'] = "%{$filterIp}%";
}

// Fuentes: access_logs (admins) y signatures (firmantes)
if ($filterType === 'admin' || $filterType === '') {
    $adminTracking = $db->fetchAll(
        "SELECT
            al.ip_address,
            al.user_agent,
            al.created_at,
            al.accion,
            al.tipo,
            a.nombre   as user_name,
            a.email    as user_email,
            'admin'    as source
         FROM access_logs al
         LEFT JOIN admins a ON al.usuario_id = a.id
         WHERE {$whereDB}
         ORDER BY al.created_at DESC
         LIMIT 200",
        $paramsDB
    );
} else {
    $adminTracking = [];
}

if ($filterType === 'signer' || $filterType === '') {
    $signerTracking = $db->fetchAll(
        "SELECT
            s.ip_address,
            s.user_agent,
            s.firmado_at   as created_at,
            'firma'        as accion,
            'firma'        as tipo,
            s.numero_documento as user_name,
            c.cliente_nombre   as user_email,
            'signer'           as source,
            s.ubicacion_lat,
            s.ubicacion_lng,
            s.metadata,
            c.titulo       as contract_title
         FROM signatures s
         LEFT JOIN contracts c ON s.contract_id = c.id
         WHERE s.ip_address LIKE :ip
         ORDER BY s.firmado_at DESC
         LIMIT 200",
        [':ip' => "%{$filterIp}%"]
    );
} else {
    $signerTracking = [];
}

// Combinar y ordenar por fecha
$allTracking = array_merge($adminTracking, $signerTracking);
usort($allTracking, fn($a, $b) => strtotime($b['created_at']) - strtotime($a['created_at']));

// Paginar
$totalTracking = count($allTracking);
$totalPages = max(1, ceil($totalTracking / $perPage));
$pagedTracking = array_slice($allTracking, $offset, $perPage);

// Estadísticas de browsers desde BD
$browserStats = [];
$osStats = [];
$deviceStats = [];
$ipStats = [];

foreach ($allTracking as $entry) {
    $parsed = parseUserAgent($entry['user_agent'] ?? '');
    $b = $parsed['browser'];
    $o = $parsed['os'];
    $d = $parsed['device_type'];
    $i = $entry['ip_address'];

    $browserStats[$b] = ($browserStats[$b] ?? 0) + 1;
    $osStats[$o]      = ($osStats[$o] ?? 0) + 1;
    $deviceStats[$d]  = ($deviceStats[$d] ?? 0) + 1;
    $ipStats[$i]      = ($ipStats[$i] ?? 0) + 1;
}

arsort($browserStats);
arsort($osStats);
arsort($deviceStats);
arsort($ipStats);

$topBrowsers = array_slice($browserStats, 0, 6, true);
$topOs       = array_slice($osStats, 0, 5, true);
$topDevices  = $deviceStats;
$topIps      = array_slice($ipStats, 0, 10, true);

$totalEntries = count($allTracking);
$botCount = 0;
foreach ($allTracking as $e) {
    $p = parseUserAgent($e['user_agent'] ?? '');
    if ($p['is_bot']) $botCount++;
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Tracker - 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; }
        .bar { transition: width 0.6s ease; }
    </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">User Tracker</h1>
                <p class="mt-1 text-sm text-gray-600">Análisis detallado de dispositivos, navegadores y actividad</p>
            </div>
            <div class="flex gap-2">
                <a href="../../storage/logs/user_tracking.json" target="_blank"
                   class="inline-flex items-center px-4 py-2 bg-gray-800 text-white rounded-lg hover:bg-gray-900 text-sm font-medium">
                    <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="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"/>
                    </svg>
                    Ver JSON Raw
                </a>
            </div>
        </div>

        <!-- Tu sesión actual -->
        <div class="bg-gradient-to-r from-indigo-600 to-indigo-700 rounded-xl shadow-lg p-6 mb-8 text-white">
            <h2 class="text-lg font-semibold mb-4 flex items-center gap-2">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17H3a2 2 0 01-2-2V5a2 2 0 012-2h14a2 2 0 012 2v10a2 2 0 01-2 2h-2"/>
                </svg>
                Tu Sesión Actual
                <span class="text-xs bg-indigo-500 px-2 py-0.5 rounded-full">En vivo</span>
            </h2>
            <div class="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                <div class="bg-indigo-500/40 rounded-lg p-3">
                    <div class="text-indigo-200 text-xs mb-1">IP Address</div>
                    <div class="font-mono font-semibold"><?= htmlspecialchars($clientIp) ?></div>
                    <?php if ($visitEntry['ip_info']['is_private']): ?>
                    <div class="text-xs text-indigo-300 mt-0.5">Red privada</div>
                    <?php endif; ?>
                </div>
                <div class="bg-indigo-500/40 rounded-lg p-3">
                    <div class="text-indigo-200 text-xs mb-1">Navegador</div>
                    <div class="font-semibold"><?= htmlspecialchars($parsedUA['browser']) ?></div>
                    <div class="text-xs text-indigo-300"><?= htmlspecialchars($parsedUA['browser_ver']) ?></div>
                </div>
                <div class="bg-indigo-500/40 rounded-lg p-3">
                    <div class="text-indigo-200 text-xs mb-1">Sistema Operativo</div>
                    <div class="font-semibold"><?= htmlspecialchars($parsedUA['os']) ?></div>
                    <div class="text-xs text-indigo-300"><?= htmlspecialchars($parsedUA['os_ver']) ?></div>
                </div>
                <div class="bg-indigo-500/40 rounded-lg p-3">
                    <div class="text-indigo-200 text-xs mb-1">Dispositivo</div>
                    <div class="font-semibold"><?= htmlspecialchars($parsedUA['device_type']) ?></div>
                    <?php if ($parsedUA['device_brand']): ?>
                    <div class="text-xs text-indigo-300"><?= htmlspecialchars($parsedUA['device_brand']) ?> <?= htmlspecialchars($parsedUA['device_model']) ?></div>
                    <?php endif; ?>
                </div>
            </div>
            <!-- Headers HTTP -->
            <details class="mt-4">
                <summary class="cursor-pointer text-sm text-indigo-200 hover:text-white flex items-center gap-1">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                    </svg>
                    Ver todos los headers HTTP capturados
                </summary>
                <div class="mt-3 bg-indigo-900/50 rounded-lg p-4 font-mono text-xs grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-1">
                    <?php foreach ($visitEntry['http_headers'] as $hKey => $hVal): ?>
                    <?php if (!empty($hVal)): ?>
                    <div class="flex gap-2">
                        <span class="text-indigo-300 whitespace-nowrap"><?= htmlspecialchars(str_replace('_', '-', $hKey)) ?>:</span>
                        <span class="text-white truncate"><?= htmlspecialchars($hVal) ?></span>
                    </div>
                    <?php endif; ?>
                    <?php endforeach; ?>
                </div>
            </details>
            <div class="mt-3 text-xs text-indigo-300">
                User-Agent: <span class="text-white"><?= htmlspecialchars(substr($clientUA, 0, 150)) ?>...</span>
            </div>
        </div>

        <!-- Estadísticas visuales -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">

            <!-- Navegadores -->
            <div class="bg-white rounded-lg shadow p-6">
                <h3 class="text-sm font-semibold text-gray-700 mb-4 flex items-center gap-2">
                    <svg class="w-4 h-4 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="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.064"/>
                    </svg>
                    Navegadores
                </h3>
                <?php if (empty($topBrowsers)): ?>
                <p class="text-xs text-gray-400">Sin datos</p>
                <?php else: ?>
                <div class="space-y-3">
                    <?php $maxB = max($topBrowsers); ?>
                    <?php foreach ($topBrowsers as $name => $count): ?>
                    <div>
                        <div class="flex justify-between text-xs mb-1">
                            <span class="text-gray-700 font-medium"><?= htmlspecialchars($name) ?></span>
                            <span class="text-gray-500"><?= $count ?></span>
                        </div>
                        <div class="h-2 bg-gray-100 rounded-full overflow-hidden">
                            <div class="bar h-full bg-blue-400 rounded-full" style="width: <?= round(($count / $maxB) * 100) ?>%"></div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>

            <!-- Sistemas operativos -->
            <div class="bg-white rounded-lg shadow p-6">
                <h3 class="text-sm font-semibold text-gray-700 mb-4 flex items-center gap-2">
                    <svg class="w-4 h-4 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17H3a2 2 0 01-2-2V5a2 2 0 012-2h14a2 2 0 012 2v10a2 2 0 01-2 2h-2"/>
                    </svg>
                    Sistemas Operativos
                </h3>
                <?php if (empty($topOs)): ?>
                <p class="text-xs text-gray-400">Sin datos</p>
                <?php else: ?>
                <div class="space-y-3">
                    <?php $maxO = max($topOs); ?>
                    <?php foreach ($topOs as $name => $count): ?>
                    <div>
                        <div class="flex justify-between text-xs mb-1">
                            <span class="text-gray-700 font-medium"><?= htmlspecialchars($name) ?></span>
                            <span class="text-gray-500"><?= $count ?></span>
                        </div>
                        <div class="h-2 bg-gray-100 rounded-full overflow-hidden">
                            <div class="bar h-full bg-green-400 rounded-full" style="width: <?= round(($count / $maxO) * 100) ?>%"></div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>

            <!-- Dispositivos + IPs Top -->
            <div class="space-y-6">
                <div class="bg-white rounded-lg shadow p-6">
                    <h3 class="text-sm font-semibold text-gray-700 mb-4 flex items-center gap-2">
                        <svg class="w-4 h-4 text-purple-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z"/>
                        </svg>
                        Tipo de Dispositivo
                    </h3>
                    <?php if (empty($topDevices)): ?>
                    <p class="text-xs text-gray-400">Sin datos</p>
                    <?php else: ?>
                    <div class="space-y-2">
                        <?php $maxD = max($topDevices); ?>
                        <?php
                        $deviceIcons = ['Desktop' => '🖥', 'Mobile' => '📱', 'Tablet' => '📋', 'Bot' => '🤖'];
                        foreach ($topDevices as $name => $count):
                        ?>
                        <div class="flex items-center gap-2">
                            <span class="text-lg"><?= $deviceIcons[$name] ?? '💻' ?></span>
                            <div class="flex-1">
                                <div class="flex justify-between text-xs mb-0.5">
                                    <span class="text-gray-700"><?= htmlspecialchars($name) ?></span>
                                    <span class="text-gray-500"><?= $count ?></span>
                                </div>
                                <div class="h-1.5 bg-gray-100 rounded-full overflow-hidden">
                                    <div class="bar h-full bg-purple-400 rounded-full" style="width: <?= round(($count / $maxD) * 100) ?>%"></div>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>
                </div>

                <div class="bg-white rounded-lg shadow p-5">
                    <h3 class="text-sm font-semibold text-gray-700 mb-3">Resumen general</h3>
                    <div class="space-y-2 text-sm">
                        <div class="flex justify-between">
                            <span class="text-gray-500">Total registros</span>
                            <span class="font-semibold"><?= number_format($totalEntries) ?></span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-gray-500">IPs únicas</span>
                            <span class="font-semibold"><?= number_format(count($ipStats)) ?></span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-gray-500">Bots detectados</span>
                            <span class="font-semibold text-red-600"><?= $botCount ?></span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-gray-500">Entradas en JSON</span>
                            <span class="font-semibold text-indigo-600"><?= count($trackingData) ?></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Top IPs -->
        <div class="bg-white rounded-lg shadow p-6 mb-8">
            <h3 class="text-sm font-semibold text-gray-700 mb-4 flex items-center gap-2">
                <svg class="w-4 h-4 text-orange-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 por actividad
            </h3>
            <div class="grid grid-cols-2 sm:grid-cols-5 gap-3">
                <?php $maxIP = $topIps ? max($topIps) : 1; ?>
                <?php foreach ($topIps as $ip => $count): ?>
                <div class="border border-gray-100 rounded-lg p-3 text-center hover:border-indigo-300 transition">
                    <a href="?ip=<?= urlencode($ip) ?>" class="font-mono text-xs text-indigo-600 hover:text-indigo-800 font-semibold block truncate">
                        <?= htmlspecialchars($ip) ?>
                    </a>
                    <div class="mt-1 text-lg font-bold <?= $count > 50 ? 'text-red-600' : 'text-gray-700' ?>"><?= $count ?></div>
                    <div class="mt-1 h-1 bg-gray-100 rounded-full overflow-hidden">
                        <div class="h-full <?= $count > 50 ? 'bg-red-400' : 'bg-indigo-400' ?> rounded-full" style="width: <?= round(($count / $maxIP) * 100) ?>%"></div>
                    </div>
                </div>
                <?php endforeach; ?>
                <?php if (empty($topIps)): ?>
                <div class="col-span-5 text-center text-xs text-gray-400 py-4">Sin datos</div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Tabla de tracking -->
        <div class="bg-white rounded-lg shadow overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-200 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
                <h3 class="text-base font-semibold text-gray-900">
                    Historial Detallado
                    <span class="text-sm font-normal text-gray-500 ml-2"><?= number_format($totalTracking) ?> registros</span>
                </h3>
                <form method="GET" class="flex gap-2">
                    <input type="text" name="ip" placeholder="Filtrar por IP..."
                        value="<?= htmlspecialchars($filterIp) ?>"
                        class="px-3 py-1.5 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500 font-mono w-40">
                    <select name="source" class="px-3 py-1.5 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500">
                        <option value="">Todos</option>
                        <option value="admin" <?= $filterType === 'admin' ? 'selected' : '' ?>>Admins</option>
                        <option value="signer" <?= $filterType === 'signer' ? 'selected' : '' ?>>Firmantes</option>
                    </select>
                    <button type="submit" class="px-3 py-1.5 bg-indigo-600 text-white rounded-lg text-sm">Filtrar</button>
                    <?php if ($filterIp || $filterType): ?>
                    <a href="?" class="px-3 py-1.5 bg-gray-100 text-gray-600 rounded-lg text-sm">✕</a>
                    <?php endif; ?>
                </form>
            </div>

            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200 text-xs">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Fecha</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Fuente</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">IP</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Navegador</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">OS / Dispositivo</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Usuario</th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Acción</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-100">
                        <?php if (empty($pagedTracking)): ?>
                        <tr>
                            <td colspan="7" class="px-4 py-10 text-center text-gray-400">Sin registros</td>
                        </tr>
                        <?php else: ?>
                        <?php foreach ($pagedTracking as $entry):
                            $parsed = parseUserAgent($entry['user_agent'] ?? '');
                            $isBot  = $parsed['is_bot'];
                            $isMob  = $parsed['is_mobile'];
                            $isSrc  = $entry['source'];
                        ?>
                        <tr class="hover:bg-gray-50 <?= $isBot ? 'bg-red-50/50' : '' ?>" title="<?= htmlspecialchars($entry['user_agent'] ?? '') ?>">
                            <td class="px-4 py-3 font-mono text-gray-500 whitespace-nowrap">
                                <?= date('d/m/y H:i:s', strtotime($entry['created_at'])) ?>
                            </td>
                            <td class="px-4 py-3">
                                <?php if ($isSrc === 'admin'): ?>
                                <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium bg-indigo-50 text-indigo-700">
                                    Admin
                                </span>
                                <?php else: ?>
                                <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium bg-green-50 text-green-700">
                                    Firmante
                                </span>
                                <?php endif; ?>
                            </td>
                            <td class="px-4 py-3 font-mono">
                                <a href="?ip=<?= urlencode($entry['ip_address']) ?>" class="text-indigo-600 hover:text-indigo-800 font-semibold">
                                    <?= htmlspecialchars($entry['ip_address']) ?>
                                </a>
                            </td>
                            <td class="px-4 py-3">
                                <div class="font-medium text-gray-800">
                                    <?php
                                    $browserIcons = ['Chrome' => '🌐', 'Firefox' => '🦊', 'Safari' => '🧭', 'Edge' => '⚡', 'Opera' => '🎵', 'Bot/Crawler' => '🤖'];
                                    echo ($browserIcons[$parsed['browser']] ?? '🌐') . ' ';
                                    echo htmlspecialchars($parsed['browser']);
                                    ?>
                                </div>
                                <?php if ($parsed['browser_ver']): ?>
                                <div class="text-gray-400"><?= htmlspecialchars(substr($parsed['browser_ver'], 0, 10)) ?></div>
                                <?php endif; ?>
                            </td>
                            <td class="px-4 py-3">
                                <div class="text-gray-800">
                                    <?php
                                    $osIcons = ['Windows' => '🪟', 'macOS' => '🍎', 'iOS' => '📱', 'Android' => '🤖', 'Linux' => '🐧', 'ChromeOS' => '🌐'];
                                    echo ($osIcons[$parsed['os']] ?? '💻') . ' ';
                                    echo htmlspecialchars($parsed['os']);
                                    if ($parsed['os_ver']) echo ' ' . htmlspecialchars($parsed['os_ver']);
                                    ?>
                                </div>
                                <div class="text-gray-400"><?= htmlspecialchars($parsed['device_type']) ?>
                                    <?= $parsed['device_brand'] ? ' · ' . htmlspecialchars($parsed['device_brand']) : '' ?>
                                </div>
                            </td>
                            <td class="px-4 py-3">
                                <?php if (!empty($entry['user_name'])): ?>
                                <div class="font-medium text-gray-800"><?= htmlspecialchars($entry['user_name']) ?></div>
                                <?php endif; ?>
                                <?php if (!empty($entry['user_email'])): ?>
                                <div class="text-gray-500"><?= htmlspecialchars($entry['user_email']) ?></div>
                                <?php endif; ?>
                            </td>
                            <td class="px-4 py-3 text-gray-600">
                                <?= htmlspecialchars($entry['accion'] ?? '-') ?>
                                <?php if (!empty($entry['contract_title'])): ?>
                                <div class="text-gray-400 truncate max-w-32"><?= htmlspecialchars($entry['contract_title']) ?></div>
                                <?php endif; ?>
                                <?php
                                if (!empty($entry['ubicacion_lat']) && !empty($entry['ubicacion_lng'])):
                                    $lat = (float)$entry['ubicacion_lat'];
                                    $lng = (float)$entry['ubicacion_lng'];
                                ?>
                                <a href="https://maps.google.com/?q=<?= $lat ?>,<?= $lng ?>" target="_blank"
                                   class="inline-flex items-center gap-1 text-xs text-green-600 hover:text-green-800 mt-0.5">
                                    📍 Ver en mapa
                                </a>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <!-- Paginación -->
            <?php if ($totalPages > 1): ?>
            <div class="px-6 py-4 border-t border-gray-200 flex items-center justify-between">
                <div class="text-xs 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-xs bg-white border border-gray-300 rounded-lg hover:bg-gray-50">Anterior</a>
                    <?php endif; ?>
                    <?php if ($page < $totalPages): ?>
                    <a href="?<?= http_build_query(array_merge($_GET, ['page' => $page + 1])) ?>" class="px-3 py-1.5 text-xs bg-white border border-gray-300 rounded-lg hover:bg-gray-50">Siguiente</a>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>
        </div>

        <!-- Info del archivo JSON -->
        <div class="mt-6 bg-gray-800 text-gray-200 rounded-lg p-5">
            <h3 class="text-sm font-semibold mb-3 flex items-center gap-2">
                <svg class="w-4 h-4 text-yellow-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"/>
                </svg>
                Archivo de Tracking JSON
            </h3>
            <div class="font-mono text-xs text-gray-400 space-y-1">
                <div>Ruta: <span class="text-yellow-400"><?= htmlspecialchars($trackingFile) ?></span></div>
                <div>Registros guardados: <span class="text-green-400"><?= count($trackingData) ?></span> / 500 máx.</div>
                <div>Tamaño: <span class="text-green-400"><?= file_exists($trackingFile) ? number_format(filesize($trackingFile) / 1024, 1) . ' KB' : 'N/A' ?></span></div>
                <div>Última actualización: <span class="text-green-400"><?= file_exists($trackingFile) ? date('d/m/Y H:i:s', filemtime($trackingFile)) : 'N/A' ?></span></div>
                <div class="mt-2 text-gray-500">Cada visita a esta página se registra automáticamente con: IP, headers HTTP, User-Agent completo, navegador, OS, dispositivo, idioma y fingerprint de sesión.</div>
            </div>
        </div>

    </main>

    <!-- Script de tracking del lado cliente -->
    <script>
    (function() {
        'use strict';

        var data = {
            page: window.location.pathname,
            referrer: document.referrer || '',
            screen_width: screen.width,
            screen_height: screen.height,
            window_width: window.innerWidth,
            window_height: window.innerHeight,
            color_depth: screen.colorDepth,
            pixel_ratio: window.devicePixelRatio || 1,
            timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || '',
            timezone_offset: new Date().getTimezoneOffset(),
            language: navigator.language || '',
            languages: (navigator.languages || []).join(','),
            platform: navigator.platform || '',
            cores: navigator.hardwareConcurrency || 0,
            memory: navigator.deviceMemory || 0,
            touch_points: navigator.maxTouchPoints || 0,
            touch_support: ('ontouchstart' in window) || (navigator.maxTouchPoints > 0),
            cookies_enabled: navigator.cookieEnabled,
            java_enabled: !!(navigator.javaEnabled && navigator.javaEnabled()),
            do_not_track: navigator.doNotTrack || window.doNotTrack || '',
            online: navigator.onLine,
            connection_type: (navigator.connection && navigator.connection.effectiveType) ? navigator.connection.effectiveType : '',
            performance_navigation: (performance && performance.navigation) ? performance.navigation.type : '',
        };

        // Detectar plugins del navegador
        if (navigator.plugins && navigator.plugins.length > 0) {
            var plugins = [];
            for (var i = 0; i < Math.min(navigator.plugins.length, 10); i++) {
                plugins.push(navigator.plugins[i].name);
            }
            data.plugins = plugins.join(', ');
            data.fonts_count = navigator.plugins.length;
        }

        // Canvas fingerprint (no invasivo, solo detecta soporte)
        try {
            var canvas = document.createElement('canvas');
            var ctx = canvas.getContext('2d');
            ctx.textBaseline = 'top';
            ctx.font = '14px Arial';
            ctx.fillText('fp', 2, 2);
            data.canvas_fp = canvas.toDataURL().length > 100 ? 'supported' : 'blocked';
        } catch(e) {
            data.canvas_fp = 'error';
        }

        // WebGL vendor info
        try {
            var gl = document.createElement('canvas').getContext('webgl') ||
                     document.createElement('canvas').getContext('experimental-webgl');
            if (gl) {
                var dbgInfo = gl.getExtension('WEBGL_debug_renderer_info');
                if (dbgInfo) {
                    data.webgl_vendor   = gl.getParameter(dbgInfo.UNMASKED_VENDOR_WEBGL);
                    data.webgl_renderer = gl.getParameter(dbgInfo.UNMASKED_RENDERER_WEBGL);
                }
            }
        } catch(e) {}

        // Battery API
        if (navigator.getBattery) {
            navigator.getBattery().then(function(battery) {
                data.battery_level    = Math.round(battery.level * 100);
                data.battery_charging = battery.charging;
                sendTracking(data);
            }).catch(function() { sendTracking(data); });
        } else {
            sendTracking(data);
        }

        function sendTracking(payload) {
            fetch('api/track.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload),
                credentials: 'same-origin'
            }).catch(function() {});
        }
    })();
    </script>

    <?php include __DIR__ . '/../../includes/admin-footer.php'; ?>
</body>
</html>
