<?php
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/config.php';
requireLogin();
$user = currentUser();
$isAdmin = $user['role'] === 'admin';

// Para admin: puede ver cliente específico por parámetro
$viewClientId = $_GET['client'] ?? '';

// Lista de usuarios cliente para el switcher (solo admin)
$clientUsers = [];
if ($isAdmin) {
    $pdo = db();
    $stmt = $pdo->query("
        SELECT u.id, u.display_name
        FROM users u
        WHERE u.active = 1 AND u.role = 'client'
        ORDER BY u.display_name
    ");
    $clientUsers = $stmt->fetchAll();
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Dashboard – ZeroTrust Shield</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
    <link rel="stylesheet" href="assets/css/style.css">
</head>
<body class="zt-body">

<!-- NAVBAR -->
<nav class="navbar navbar-expand-lg zt-navbar">
    <div class="container-fluid px-4">
        <a class="navbar-brand d-flex align-items-center gap-2" href="dashboard.php">
            <img src="assets/img/simbolo-pcassi.png" alt="PCASSI" style="height:34px;">
            <div style="line-height:1.15;">
                <div style="font-weight:700;color:#e2e8f0;font-size:.95rem;">ZeroTrust DNS</div>
                <div style="font-size:.68rem;color:#94a3b8;letter-spacing:.02em;">by PCASSI</div>
            </div>
        </a>
        <div class="d-flex align-items-center gap-3 ms-auto">
            <span class="text-secondary d-none d-md-inline" style="font-size:.82rem">
                <i class="bi bi-person-circle me-1"></i><?= htmlspecialchars($user['display_name']) ?>
            </span>
            <?php if ($isAdmin): ?>
                <a href="admin.php" class="btn btn-sm btn-outline-primary">
                    <i class="bi bi-gear me-1"></i>Admin
                </a>
            <?php endif; ?>
            <a href="logout.php" class="btn btn-sm btn-outline-secondary">
                <i class="bi bi-box-arrow-right me-1"></i>Salir
            </a>
        </div>
    </div>
</nav>

<div class="container-fluid px-4 py-4">

    <!-- CONTROLES SUPERIORES -->
    <div class="row align-items-center mb-4 g-2">
        <div class="col-auto">
            <h4 class="mb-0 text-white fw-semibold">
                <i class="bi bi-bar-chart-line-fill me-2" style="color:#3b82f6"></i>
                Panel de Protección DNS
            </h4>
        </div>
        <div class="col ms-auto text-end d-flex gap-2 justify-content-end flex-wrap align-items-center">
            <?php if ($isAdmin): ?>
            <!-- Selector de usuario (solo admin) -->
            <div class="d-flex align-items-center gap-1" id="userSwitcherWrap">
                <span class="text-secondary" style="font-size:.78rem;white-space:nowrap"><i class="bi bi-eye me-1"></i>Ver:</span>
                <select id="userSwitcher" class="form-select form-select-sm zt-input" style="width:190px">
                    <option value="">— Seleccioná un cliente —</option>
                </select>
            </div>
            <?php endif; ?>
            <!-- Selector de periodo -->
            <div class="btn-group" id="periodBtns" role="group">
                <button class="btn btn-sm zt-period-btn" data-period="6h">6h</button>
                <button class="btn btn-sm zt-period-btn active" data-period="24h">24h</button>
                <button class="btn btn-sm zt-period-btn" data-period="7d">7 días</button>
                <button class="btn btn-sm zt-period-btn" data-period="30d">30 días</button>
            </div>
            <button class="btn btn-sm btn-outline-secondary" id="btnRefresh" title="Actualizar datos">
                <i class="bi bi-arrow-clockwise"></i>
            </button>
            <button class="btn btn-sm btn-outline-secondary" id="btnExport" title="Exportar informe">
                <i class="bi bi-download me-1"></i>Exportar
            </button>
        </div>
    </div>

    <!-- TARJETAS DE RESUMEN -->
    <div class="row g-3 mb-4" id="statsCards">
        <div class="col-6 col-md-3">
            <div class="zt-card h-100">
                <div class="zt-card-icon" style="background:rgba(59,130,246,0.15);color:#3b82f6">
                    <i class="bi bi-globe"></i>
                </div>
                <div class="zt-card-value" id="statTotalQueries">–</div>
                <div class="zt-card-label">Consultas DNS</div>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="zt-card h-100">
                <div class="zt-card-icon" style="background:rgba(220,53,69,0.15);color:#dc3545">
                    <i class="bi bi-shield-x"></i>
                </div>
                <div class="zt-card-value" id="statTotalBlocked">–</div>
                <div class="zt-card-label">Bloqueadas</div>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="zt-card h-100">
                <div class="zt-card-icon" style="background:rgba(25,135,84,0.15);color:#198754">
                    <i class="bi bi-percent"></i>
                </div>
                <div class="zt-card-value" id="statBlockRate">–</div>
                <div class="zt-card-label">Tasa de Bloqueo</div>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="zt-card h-100">
                <div class="zt-card-icon" style="background:rgba(156,39,176,0.15);color:#9c27b0">
                    <i class="bi bi-tag"></i>
                </div>
                <div class="zt-card-value text-truncate" id="statTopCategory" style="font-size:1rem">–</div>
                <div class="zt-card-label">Categoría Principal</div>
            </div>
        </div>
    </div>

    <!-- GRÁFICOS PRINCIPALES -->
    <div class="row g-3 mb-4">
        <!-- Timeline — ocupa más espacio horizontal -->
        <div class="col-12 col-xl-9">
            <div class="zt-card-chart h-100 d-flex flex-column">
                <div class="d-flex align-items-center justify-content-between mb-3">
                    <h6 class="mb-0 text-white"><i class="bi bi-activity me-2" style="color:#3b82f6"></i>Actividad DNS</h6>
                    <span class="badge bg-secondary" id="timelineSubtitle" style="font-size:.7rem">últimas 24 horas</span>
                </div>
                <div style="position:relative;flex:1;min-height:240px">
                    <canvas id="chartTimeline"></canvas>
                </div>
            </div>
        </div>
        <!-- Categorías donut -->
        <div class="col-12 col-xl-3">
            <div class="zt-card-chart h-100">
                <h6 class="mb-3 text-white"><i class="bi bi-pie-chart me-2" style="color:#3b82f6"></i>Por Categoría</h6>
                <div style="position:relative;height:180px">
                    <canvas id="chartCategories"></canvas>
                </div>
                <div id="categoryLegend" class="mt-3" style="font-size:.76rem"></div>
            </div>
        </div>
    </div>

    <!-- TOP DOMINIOS BLOQUEADOS -->
    <div class="row g-3 mb-4">
        <div class="col-12 col-xl-6">
            <div class="zt-card-chart h-100">
                <h6 class="mb-3 text-white"><i class="bi bi-bar-chart-h me-2" style="color:#dc3545"></i>Top 10 Dominios Bloqueados</h6>
                <div style="position:relative;height:280px">
                    <canvas id="chartTopDomains"></canvas>
                </div>
            </div>
        </div>
        <?php if ($isAdmin): ?>
        <!-- Top clientes (solo admin) -->
        <div class="col-12 col-xl-6">
            <div class="zt-card-chart h-100">
                <h6 class="mb-3 text-white"><i class="bi bi-people me-2" style="color:#ffc107"></i>Actividad por Cliente</h6>
                <div style="position:relative;height:280px">
                    <canvas id="chartTopClients"></canvas>
                </div>
            </div>
        </div>
        <?php else: ?>
        <!-- Resumen categorías tabla (solo cliente) -->
        <div class="col-12 col-xl-6">
            <div class="zt-card-chart h-100">
                <h6 class="mb-3 text-white"><i class="bi bi-list-check me-2" style="color:#ffc107"></i>Resumen de Protección</h6>
                <div id="categorySummaryTable"></div>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <!-- LOG DE CONSULTAS -->
    <div class="zt-card-chart mb-4">
        <div class="d-flex align-items-center justify-content-between mb-3 flex-wrap gap-2">
            <h6 class="mb-0 text-white"><i class="bi bi-list-ul me-2" style="color:#3b82f6"></i>Registro de Consultas DNS</h6>
            <div class="d-flex gap-2 flex-wrap">
                <input type="text"   id="logSearch"   class="form-control form-control-sm zt-input" placeholder="Buscar dominio..." style="width:180px">
                <select id="logCategory"  class="form-select form-select-sm zt-input" style="width:160px">
                    <option value="">Todas las categorías</option>
                </select>
                <select id="logReason" class="form-select form-select-sm zt-input" style="width:140px">
                    <option value="">Todos los estados</option>
                    <option value="FilteredBlackList">Bloqueado (Lista)</option>
                    <option value="FilteredSafeBrowsing">Bloqueado (Seg.)</option>
                    <option value="FilteredParental">Control Parental</option>
                    <option value="NotFilteredWhiteList">Lista Blanca</option>
                    <option value="NotFilteredNotFound">Permitido</option>
                </select>
                <button class="btn btn-sm btn-outline-primary" id="logApplyFilter">
                    <i class="bi bi-funnel"></i> Filtrar
                </button>
                <button class="btn btn-sm btn-outline-secondary" id="logClearFilter">
                    <i class="bi bi-x-circle"></i>
                </button>
            </div>
        </div>

        <div class="table-responsive">
            <table class="table table-sm zt-table" id="logTable">
                <thead>
                    <tr>
                        <th style="width:145px">Fecha/Hora</th>
                        <th>Dominio</th>
                        <th style="width:50px">Tipo</th>
                        <th style="width:130px">Estado</th>
                        <th style="width:140px">Categoría</th>
                        <th style="width:200px">Lista</th>
                    </tr>
                </thead>
                <tbody id="logTableBody">
                    <tr><td colspan="6" class="text-center text-secondary py-4">Cargando...</td></tr>
                </tbody>
            </table>
        </div>

        <!-- Paginación -->
        <div class="d-flex align-items-center justify-content-between mt-3 flex-wrap gap-2">
            <span class="text-secondary" style="font-size:.8rem" id="logInfo">–</span>
            <nav><ul class="pagination pagination-sm mb-0" id="logPagination"></ul></nav>
        </div>
    </div>

    <div class="text-center text-secondary py-3" style="font-size:.75rem">
        <i class="bi bi-shield-check me-1" style="color:#3b82f6"></i>
        ZeroTrust Shield by PCASSI · Protección DNS en tiempo real
    </div>
</div>

<!-- MODAL: Explicación de dominio (IA) -->
<div class="modal fade" id="explainModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content" style="background:#162032;border:1px solid rgba(255,255,255,0.08)">
      <div class="modal-header" style="border-bottom:1px solid rgba(255,255,255,0.08)">
        <div class="d-flex align-items-center gap-2">
          <img src="assets/img/simbolo-pcassi.png" alt="ZeroTrust DNS" style="height:32px;">
          <div style="line-height:1.15;">
            <div style="font-weight:700;color:#e2e8f0;font-size:.95rem;">ZeroTrust DNS</div>
            <div style="font-size:.68rem;color:#94a3b8;letter-spacing:.02em;">by PCASSI</div>
          </div>
        </div>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Cerrar"></button>
      </div>
      <div class="modal-body" id="explainModalBody">
        <!-- Contenido dinámico -->
      </div>
      <div class="modal-footer" style="border-top:1px solid rgba(255,255,255,0.08)">
        <span class="text-secondary me-auto" style="font-size:.7rem">
          <i class="bi bi-robot me-1"></i>Explicación generada por IA · puede contener imprecisiones
        </span>
        <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-dismiss="modal">Cerrar</button>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
<script>
// Configuración pasada desde PHP
const ZT_CONFIG = {
    isAdmin: <?= $isAdmin ? 'true' : 'false' ?>,
    clientFilter: <?= json_encode($viewClientId) ?>,
    displayName: <?= json_encode($user['display_name']) ?>,
    userId: <?= (int)$user['id'] ?>,
    clientUsers: <?= json_encode($clientUsers) ?>,
    aiEnabled: <?= OPENAI_ENABLED ? 'true' : 'false' ?>,
};
</script>
<script src="assets/js/dashboard.js?v=20260529-ai"></script>
</body>
</html>
