<?php
require_once __DIR__ . '/auth.php';
requireAdmin();
$user = currentUser();
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Administración – 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="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">
            <i class="bi bi-shield-shaded fs-4" style="color:#3b82f6"></i>
            <span class="fw-bold text-white">ZeroTrust Shield</span>
        </a>
        <div class="d-flex align-items-center gap-3 ms-auto">
            <span class="badge bg-primary">Admin</span>
            <a href="dashboard.php" class="btn btn-sm btn-outline-primary">
                <i class="bi bi-bar-chart me-1"></i>Dashboard
            </a>
            <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">
    <div class="row g-3 mb-4 align-items-center">
        <div class="col">
            <h4 class="mb-0 text-white fw-semibold"><i class="bi bi-gear-fill me-2" style="color:#3b82f6"></i>Panel de Administración</h4>
        </div>
    </div>

    <!-- TABS -->
    <ul class="nav nav-tabs zt-tabs mb-4" id="adminTabs">
        <li class="nav-item"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#tabUsers">
            <i class="bi bi-people me-1"></i>Clientes / Usuarios
        </button></li>
        <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#tabSync">
            <i class="bi bi-arrow-repeat me-1"></i>Sincronización
        </button></li>
        <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#tabAdguardClients">
            <i class="bi bi-router me-1"></i>Clientes AdGuard
        </button></li>
        <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#tabReports">
            <i class="bi bi-envelope-paper me-1"></i>Reportes Email
        </button></li>
        <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#tabSmtp">
            <i class="bi bi-envelope-at me-1"></i>Configuración SMTP
        </button></li>
    </ul>

    <div class="tab-content">

        <!-- TAB: USUARIOS -->
        <div class="tab-pane fade show active" id="tabUsers">
            <div class="zt-card-chart">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h6 class="text-white mb-0">Usuarios del Portal</h6>
                    <button class="btn btn-sm btn-primary" id="btnAddUser">
                        <i class="bi bi-person-plus me-1"></i>Nuevo Usuario
                    </button>
                </div>
                <div class="table-responsive">
                    <table class="table table-sm zt-table" id="usersTable">
                        <thead>
                            <tr>
                                <th>Usuario</th>
                                <th>Nombre</th>
                                <th>Email</th>
                                <th>Rol</th>
                                <th>Client IDs AdGuard</th>
                                <th>Estado</th>
                                <th>Último Acceso</th>
                                <th style="width:100px">Acciones</th>
                            </tr>
                        </thead>
                        <tbody id="usersTbody">
                            <tr><td colspan="8" class="text-center text-secondary">Cargando...</td></tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- TAB: SINCRONIZACIÓN -->
        <div class="tab-pane fade" id="tabSync">
            <div class="zt-card-chart">
                <h6 class="text-white mb-3">Estado de Sincronización</h6>
                <div id="syncStatus" class="text-secondary">Cargando...</div>

                <div class="mt-4">
                    <h6 class="text-white">Configuración del Cron Job (cPanel)</h6>
                    <p class="text-secondary" style="font-size:.85rem">
                        En cPanel → Cron Jobs, agregar la siguiente tarea con frecuencia <strong>cada 5 minutos</strong>:
                    </p>
                    <div class="zt-code" id="cronCommand">php <?= htmlspecialchars(dirname(__FILE__)) ?>/cron.php</div>
                    <p class="text-secondary mt-2" style="font-size:.82rem">
                        También puede ejecutarse via URL (requiere token configurado en config.php):
                    </p>
                    <div class="zt-code"><?= htmlspecialchars(APP_URL) ?>/cron.php?token=<em>[CRON_SECRET de config.php]</em></div>
                </div>
            </div>
        </div>

        <!-- TAB: CLIENTES ADGUARD -->
        <div class="tab-pane fade" id="tabAdguardClients">
            <div class="zt-card-chart">
                <h6 class="text-white mb-3">
                    Clientes detectados en AdGuard
                    <span class="text-secondary fs-6 fw-normal ms-2">(basado en logs sincronizados)</span>
                </h6>
                <p class="text-secondary" style="font-size:.83rem">
                    Use estos IDs al asignar clientes a usuarios del portal.
                </p>
                <div class="table-responsive">
                    <table class="table table-sm zt-table">
                        <thead>
                            <tr>
                                <th>Client ID (AdGuard)</th>
                                <th>Nombre</th>
                                <th class="text-end">Consultas (total)</th>
                                <th>Copiar ID</th>
                            </tr>
                        </thead>
                        <tbody id="adguardClientsTbody">
                            <tr><td colspan="4" class="text-center text-secondary">Cargando...</td></tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- TAB: REPORTES EMAIL -->
        <div class="tab-pane fade" id="tabReports">
            <div class="zt-card-chart">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h6 class="text-white mb-0">Reportes Semanales por Email</h6>
                    <div class="text-secondary" style="font-size:.8rem">
                        <i class="bi bi-info-circle me-1"></i>
                        Configure un cron diario: <code class="zt-code" style="display:inline;padding:.1rem .4rem;font-size:.78rem">0 * * * *  php .../report_cron.php</code>
                    </div>
                </div>
                <p class="text-secondary mb-3" style="font-size:.83rem">
                    Cada cliente puede recibir un informe HTML semanal por email con sus estadísticas de protección DNS.
                </p>
                <div class="table-responsive">
                    <table class="table table-sm zt-table">
                        <thead><tr>
                            <th>Cliente</th>
                            <th>Emails destino</th>
                            <th>Día</th>
                            <th>Hora</th>
                            <th>Estado</th>
                            <th>Último envío</th>
                            <th style="width:130px">Acciones</th>
                        </tr></thead>
                        <tbody id="reportsTbody">
                            <tr><td colspan="7" class="text-center text-secondary">Cargando...</td></tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- TAB: SMTP -->
        <div class="tab-pane fade" id="tabSmtp">
            <div class="zt-card-chart" style="max-width:640px">
                <h6 class="text-white mb-1">Configuración del Servidor SMTP</h6>
                <p class="text-secondary mb-4" style="font-size:.83rem">
                    Configurá el servidor SMTP para el envío de reportes por email. Si no está habilitado se usa la función <code>mail()</code> del servidor.
                </p>
                <div class="row g-3">
                    <div class="col-12 d-flex align-items-center gap-3">
                        <label class="form-label text-secondary mb-0">Usar SMTP</label>
                        <div class="form-check form-switch mb-0">
                            <input class="form-check-input" type="checkbox" id="smtpEnabled" role="switch">
                            <label class="form-check-label text-secondary" for="smtpEnabled" id="smtpEnabledLabel">Deshabilitado</label>
                        </div>
                    </div>
                    <div class="col-md-8">
                        <label class="form-label text-secondary">Servidor SMTP (host)</label>
                        <input type="text" class="form-control zt-input" id="smtpHost" placeholder="smtp.gmail.com / mail.pcassi.net">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label text-secondary">Puerto</label>
                        <input type="number" class="form-control zt-input" id="smtpPort" value="587">
                    </div>
                    <div class="col-12">
                        <label class="form-label text-secondary">Cifrado</label>
                        <div class="d-flex gap-3 flex-wrap">
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="smtpEnc" id="encTls" value="tls" checked>
                                <label class="form-check-label text-secondary" for="encTls">STARTTLS <span class="text-muted" style="font-size:.78rem">(puerto 587, recomendado)</span></label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="smtpEnc" id="encSsl" value="ssl">
                                <label class="form-check-label text-secondary" for="encSsl">SSL/TLS <span class="text-muted" style="font-size:.78rem">(puerto 465)</span></label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="smtpEnc" id="encNone" value="none">
                                <label class="form-check-label text-secondary" for="encNone">Sin cifrado <span class="text-muted" style="font-size:.78rem">(puerto 25)</span></label>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label text-secondary">Usuario / Email de autenticación</label>
                        <input type="text" class="form-control zt-input" id="smtpUser" placeholder="usuario@dominio.com" autocomplete="off">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label text-secondary">Contraseña</label>
                        <div class="input-group">
                            <input type="password" class="form-control zt-input" id="smtpPass" placeholder="(sin cambios si se deja vacío)" autocomplete="new-password">
                            <button class="btn btn-outline-secondary" type="button" id="btnTogglePass" tabindex="-1">
                                <i class="bi bi-eye" id="eyeIcon"></i>
                            </button>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label text-secondary">Email remitente (From)</label>
                        <input type="email" class="form-control zt-input" id="smtpFromEmail" placeholder="noreply@pcassi.net">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label text-secondary">Nombre remitente</label>
                        <input type="text" class="form-control zt-input" id="smtpFromName" placeholder="ZeroTrust Shield">
                    </div>
                </div>

                <hr style="border-color:rgba(255,255,255,0.08);margin:1.5rem 0">

                <!-- Envío de prueba -->
                <div class="d-flex gap-2 align-items-end flex-wrap">
                    <div style="flex:1;min-width:200px">
                        <label class="form-label text-secondary">Email de prueba</label>
                        <input type="email" class="form-control zt-input" id="smtpTestEmail" placeholder="tu@email.com">
                    </div>
                    <button class="btn btn-outline-info" id="btnSmtpTest">
                        <i class="bi bi-send me-1"></i>Enviar prueba
                    </button>
                    <button class="btn btn-primary" id="btnSmtpSave">
                        <i class="bi bi-floppy me-1"></i>Guardar configuración
                    </button>
                </div>

                <div id="smtpMsg" class="mt-3 d-none"></div>
            </div>
        </div>

    </div>
</div>

<!-- MODAL: Crear/Editar usuario -->
<div class="modal fade" id="userModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content zt-modal">
            <div class="modal-header border-0">
                <h5 class="modal-title text-white" id="userModalTitle">Nuevo Usuario</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="editUserId" value="0">
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label text-secondary">Usuario *</label>
                        <input type="text" class="form-control zt-input" id="editUsername" placeholder="nombre.apellido">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label text-secondary">Nombre completo *</label>
                        <input type="text" class="form-control zt-input" id="editDisplayName" placeholder="Empresa / Cliente">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label text-secondary">Email</label>
                        <input type="email" class="form-control zt-input" id="editEmail" placeholder="contacto@empresa.com">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label text-secondary">Rol</label>
                        <select class="form-select zt-input" id="editRole">
                            <option value="client">Cliente</option>
                            <option value="admin">Admin</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label text-secondary">Estado</label>
                        <select class="form-select zt-input" id="editActive">
                            <option value="1">Activo</option>
                            <option value="0">Inactivo</option>
                        </select>
                    </div>
                    <div class="col-12">
                        <label class="form-label text-secondary">
                            Client IDs de AdGuard
                            <span class="text-muted" style="font-size:.78rem">(separados por coma)</span>
                        </label>
                        <input type="text" class="form-control zt-input" id="editClientIds"
                               placeholder="coopgpaz, loberazcasacentral, frigorificomark">
                        <div class="form-text text-secondary">
                            Los IDs se ven en la tab "Clientes AdGuard". Puede asignar múltiples IDs al mismo usuario.
                        </div>
                    </div>
                    <div class="col-12">
                        <label class="form-label text-secondary">
                            Contraseña
                            <span class="text-muted" style="font-size:.78rem" id="passwordHint">(requerida para nuevo usuario)</span>
                        </label>
                        <input type="password" class="form-control zt-input" id="editPassword" placeholder="••••••••" autocomplete="new-password">
                    </div>
                </div>
                <div id="userModalError" class="alert alert-danger mt-3 d-none"></div>
            </div>
            <div class="modal-footer border-0">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                <button type="button" class="btn btn-primary" id="btnSaveUser">
                    <i class="bi bi-floppy me-1"></i>Guardar
                </button>
            </div>
        </div>
    </div>
</div>

<!-- MODAL: Configurar reporte email -->
<div class="modal fade" id="reportModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content zt-modal">
            <div class="modal-header border-0">
                <h5 class="modal-title text-white" id="reportModalTitle">Configurar Reporte Email</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="reportUserId" value="0">
                <div class="row g-3">
                    <div class="col-12">
                        <label class="form-label text-secondary">Cliente</label>
                        <input type="text" class="form-control zt-input" id="reportUserName" readonly>
                    </div>
                    <div class="col-12">
                        <label class="form-label text-secondary">
                            Emails destino
                            <span class="text-muted" style="font-size:.78rem">(separados por coma)</span>
                        </label>
                        <input type="text" class="form-control zt-input" id="reportEmails"
                               placeholder="gerencia@empresa.com, it@empresa.com">
                    </div>
                    <div class="col-md-5">
                        <label class="form-label text-secondary">Día de envío</label>
                        <select class="form-select zt-input" id="reportDayOfWeek">
                            <option value="0">Domingo</option>
                            <option value="1" selected>Lunes</option>
                            <option value="2">Martes</option>
                            <option value="3">Miércoles</option>
                            <option value="4">Jueves</option>
                            <option value="5">Viernes</option>
                            <option value="6">Sábado</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label text-secondary">Hora</label>
                        <input type="number" class="form-control zt-input" id="reportSendHour" min="0" max="23" value="8">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label text-secondary">Minuto</label>
                        <select class="form-select zt-input" id="reportSendMinute">
                            <option value="0">:00</option>
                            <option value="5">:05</option>
                            <option value="10">:10</option>
                            <option value="15">:15</option>
                            <option value="20">:20</option>
                            <option value="25">:25</option>
                            <option value="30">:30</option>
                            <option value="35">:35</option>
                            <option value="40">:40</option>
                            <option value="45">:45</option>
                            <option value="50">:50</option>
                            <option value="55">:55</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label text-secondary">Estado</label>
                        <select class="form-select zt-input" id="reportActive">
                            <option value="0">Inactivo</option>
                            <option value="1">Activo</option>
                        </select>
                    </div>
                </div>
                <div id="reportModalError" class="alert alert-danger mt-3 d-none"></div>
                <div id="reportModalOk" class="alert alert-success mt-3 d-none">Configuración guardada.</div>
            </div>
            <div class="modal-footer border-0 d-flex gap-2 flex-wrap">
                <a id="btnPreviewReport" href="#" target="_blank" class="btn btn-sm btn-outline-secondary me-auto">
                    <i class="bi bi-eye me-1"></i>Preview
                </a>
                <button type="button" class="btn btn-sm btn-outline-info" id="btnSendTestReport">
                    <i class="bi bi-send me-1"></i>Enviar copia ahora
                </button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button>
                <button type="button" class="btn btn-primary" id="btnSaveReport">
                    <i class="bi bi-floppy me-1"></i>Guardar
                </button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
'use strict';

// ---- Cargar usuarios ----
async function loadUsers() {
    const r = await fetch('api.php?action=admin_users');
    const d = await r.json();
    const tbody = document.getElementById('usersTbody');
    if (!Array.isArray(d) || d.length === 0) {
        tbody.innerHTML = '<tr><td colspan="8" class="text-center text-secondary">Sin usuarios</td></tr>';
        return;
    }
    tbody.innerHTML = d.map(u => `
        <tr>
            <td class="fw-semibold text-white">${esc(u.username)}</td>
            <td>${esc(u.display_name)}</td>
            <td class="text-secondary" style="font-size:.82rem">${esc(u.email || '–')}</td>
            <td><span class="badge ${u.role === 'admin' ? 'bg-primary' : 'bg-secondary'}">${u.role}</span></td>
            <td style="font-size:.78rem;max-width:200px">
                ${u.client_ids ? u.client_ids.split(',').map(id =>
                    `<span class="badge bg-dark border me-1 mb-1">${esc(id.trim())}</span>`
                ).join('') : '<span class="text-secondary">–</span>'}
            </td>
            <td><span class="badge ${u.active == 1 ? 'bg-success' : 'bg-danger'}">${u.active == 1 ? 'Activo' : 'Inactivo'}</span></td>
            <td class="text-secondary" style="font-size:.78rem">${u.last_login ? u.last_login.slice(0,16).replace('T',' ') : 'Nunca'}</td>
            <td>
                <button class="btn btn-xs btn-outline-primary me-1" onclick="editUser(${JSON.stringify(u).replace(/"/g,'&quot;')})">
                    <i class="bi bi-pencil"></i>
                </button>
                <button class="btn btn-xs btn-outline-danger" onclick="deleteUser(${u.id}, '${esc(u.username)}')">
                    <i class="bi bi-trash"></i>
                </button>
            </td>
        </tr>
    `).join('');
}

// ---- Cargar clientes AdGuard ----
async function loadAdguardClients() {
    const r = await fetch('api.php?action=adguard_clients&period=30d');
    const d = await r.json();
    const tbody = document.getElementById('adguardClientsTbody');
    if (!Array.isArray(d)) { tbody.innerHTML = '<tr><td colspan="4" class="text-center text-secondary">Sin datos sincronizados aún</td></tr>'; return; }
    tbody.innerHTML = d.map(row => `
        <tr>
            <td><code class="text-primary">${esc(row.adguard_client_id)}</code></td>
            <td class="text-secondary">${esc(row.client_name || '–')}</td>
            <td class="text-end">${parseInt(row.total).toLocaleString('es-AR')}</td>
            <td>
                <button class="btn btn-xs btn-outline-secondary" onclick="copyToClipboard('${esc(row.adguard_client_id)}')">
                    <i class="bi bi-clipboard"></i>
                </button>
            </td>
        </tr>
    `).join('');
}

// ---- Estado de sincronización ----
async function loadSyncStatus() {
    const r  = await fetch('api.php?action=sync_status&period=24h');
    const servers = await r.json();
    const el = document.getElementById('syncStatus');

    if (!Array.isArray(servers) || servers.length === 0) {
        el.innerHTML = '<div class="alert alert-warning">No hay datos de sincronización aún.</div>';
        return;
    }

    el.innerHTML = servers.map(srv => {
        const s = srv.last_sync;
        const statusClass = !s ? 'warning' : s.status === 'ok' ? 'success' : s.status === 'running' ? 'info' : 'danger';
        const statusLabel = !s ? 'sin datos' : s.status;
        return `
        <div class="mb-4">
            <h6 class="text-white mb-3">
                <span class="badge bg-secondary me-2">${esc(srv.server_id.toUpperCase())}</span>
                ${esc(srv.server_name)}
            </h6>
            <div class="row g-2">
                <div class="col-md-3"><div class="zt-card text-center">
                    <div class="zt-card-value">${s ? parseInt(s.records_new || 0).toLocaleString('es-AR') : '–'}</div>
                    <div class="zt-card-label">Nuevos (último sync)</div>
                </div></div>
                <div class="col-md-3"><div class="zt-card text-center">
                    <div class="zt-card-value">${s ? parseInt(s.records_fetched || 0).toLocaleString('es-AR') : '–'}</div>
                    <div class="zt-card-label">Leídos (último sync)</div>
                </div></div>
                <div class="col-md-3"><div class="zt-card text-center">
                    <div class="zt-card-value"><span class="badge bg-${statusClass}">${statusLabel}</span></div>
                    <div class="zt-card-label">Estado</div>
                </div></div>
                <div class="col-md-3"><div class="zt-card text-center">
                    <div class="zt-card-value" style="font-size:.85rem">
                        ${s ? (s.finished_at || s.started_at || '–').slice(0,16).replace('T',' ') : '–'}
                    </div>
                    <div class="zt-card-label">Última ejecución</div>
                </div></div>
            </div>
            ${s?.error_message ? `<div class="alert alert-danger mt-2 py-2">${esc(s.error_message)}</div>` : ''}
            <div class="mt-2 text-secondary" style="font-size:.8rem">
                Último registro: <strong class="text-white">${srv.last_log_time || 'N/A'}</strong>
            </div>
        </div>
        ${servers.indexOf(srv) < servers.length - 1 ? '<hr style="border-color:rgba(255,255,255,0.07)">' : ''}
        `;
    }).join('');
}

// ---- Editar usuario ----
function editUser(u) {
    document.getElementById('editUserId').value       = u.id;
    document.getElementById('editUsername').value     = u.username;
    document.getElementById('editDisplayName').value  = u.display_name;
    document.getElementById('editEmail').value        = u.email || '';
    document.getElementById('editRole').value         = u.role;
    document.getElementById('editActive').value       = u.active;
    document.getElementById('editClientIds').value    = u.client_ids || '';
    document.getElementById('editPassword').value     = '';
    document.getElementById('userModalTitle').textContent = 'Editar Usuario';
    document.getElementById('passwordHint').textContent  = '(dejar vacío para no cambiar)';
    document.getElementById('userModalError').classList.add('d-none');
    new bootstrap.Modal(document.getElementById('userModal')).show();
}

document.getElementById('btnAddUser').addEventListener('click', () => {
    ['editUserId','editUsername','editDisplayName','editEmail','editClientIds','editPassword']
        .forEach(id => document.getElementById(id).value = id === 'editUserId' ? '0' : '');
    document.getElementById('editRole').value   = 'client';
    document.getElementById('editActive').value = '1';
    document.getElementById('userModalTitle').textContent = 'Nuevo Usuario';
    document.getElementById('passwordHint').textContent  = '(requerida para nuevo usuario)';
    document.getElementById('userModalError').classList.add('d-none');
    new bootstrap.Modal(document.getElementById('userModal')).show();
});

document.getElementById('btnSaveUser').addEventListener('click', async () => {
    const payload = {
        id:           parseInt(document.getElementById('editUserId').value),
        username:     document.getElementById('editUsername').value.trim(),
        display_name: document.getElementById('editDisplayName').value.trim(),
        email:        document.getElementById('editEmail').value.trim(),
        role:         document.getElementById('editRole').value,
        active:       document.getElementById('editActive').value,
        client_ids:   document.getElementById('editClientIds').value.trim(),
        password:     document.getElementById('editPassword').value,
    };
    const r = await fetch('api.php?action=admin_save_user', { method:'POST', body: JSON.stringify(payload) });
    const d = await r.json();
    if (d.error) {
        const errEl = document.getElementById('userModalError');
        errEl.textContent = d.error;
        errEl.classList.remove('d-none');
        return;
    }
    bootstrap.Modal.getInstance(document.getElementById('userModal')).hide();
    loadUsers();
});

async function deleteUser(id, username) {
    if (!confirm(`¿Eliminar el usuario "${username}"? Esta acción no se puede deshacer.`)) return;
    const r = await fetch('api.php?action=admin_delete_user', { method:'POST', body: JSON.stringify({ id }) });
    const d = await r.json();
    if (d.error) alert(d.error);
    else loadUsers();
}

function esc(str) {
    const d = document.createElement('div');
    d.textContent = String(str || '');
    return d.innerHTML;
}

function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(() => {
        // Pequeña confirmación visual
        const btn = event.currentTarget;
        btn.innerHTML = '<i class="bi bi-check text-success"></i>';
        setTimeout(() => btn.innerHTML = '<i class="bi bi-clipboard"></i>', 1500);
    });
}

// ---- Reportes Email ----
const DAYS = ['Domingo','Lunes','Martes','Miércoles','Jueves','Viernes','Sábado'];

async function loadReports() {
    const r = await fetch('api.php?action=users_list');
    const users = await r.json();
    const tbody = document.getElementById('reportsTbody');
    if (!Array.isArray(users) || users.length === 0) {
        tbody.innerHTML = '<tr><td colspan="7" class="text-center text-secondary">Sin usuarios cliente</td></tr>';
        return;
    }
    // Obtener configs de todos los usuarios
    const configs = {};
    await Promise.all(users.map(async u => {
        const c = await fetch(`api.php?action=report_config_get&user_id=${u.id}`).then(r2 => r2.json());
        configs[u.id] = c;
    }));
    tbody.innerHTML = users.map(u => {
        const c = configs[u.id] || {};
        return `<tr>
            <td class="fw-semibold text-white">${esc(u.display_name)}</td>
            <td style="font-size:.8rem;max-width:200px;overflow:hidden;text-overflow:ellipsis">${esc(c.emails || '–')}</td>
            <td>${DAYS[c.day_of_week ?? 1] || '–'}</td>
            <td>${c.send_hour !== undefined ? String(c.send_hour).padStart(2,'0') + ':' + String(c.send_minute ?? 0).padStart(2,'0') : '–'}</td>
            <td><span class="badge ${c.active ? 'bg-success' : 'bg-secondary'}">${c.active ? 'Activo' : 'Inactivo'}</span></td>
            <td class="text-secondary" style="font-size:.78rem">${c.last_sent_at ? c.last_sent_at.slice(0,16) : 'Nunca'}</td>
            <td>
                <button class="btn btn-xs btn-outline-primary me-1" onclick="openReportModal(${JSON.stringify(u).replace(/"/g,'&quot;')}, ${JSON.stringify(c).replace(/"/g,'&quot;')})">
                    <i class="bi bi-pencil"></i> Configurar
                </button>
            </td>
        </tr>`;
    }).join('');
}

function openReportModal(u, c) {
    document.getElementById('reportUserId').value       = u.id;
    document.getElementById('reportUserName').value     = u.display_name;
    document.getElementById('reportEmails').value       = c.emails || '';
    document.getElementById('reportDayOfWeek').value    = c.day_of_week ?? 1;
    document.getElementById('reportSendHour').value     = c.send_hour ?? 8;
    document.getElementById('reportSendMinute').value   = c.send_minute ?? 0;
    document.getElementById('reportActive').value       = c.active ? '1' : '0';
    document.getElementById('reportModalError').classList.add('d-none');
    document.getElementById('reportModalOk').classList.add('d-none');
    document.getElementById('reportModalTitle').textContent = `Reporte: ${u.display_name}`;
    document.getElementById('btnPreviewReport').href = `report.php?user_id=${u.id}`;
    new bootstrap.Modal(document.getElementById('reportModal')).show();
}

document.getElementById('btnSendTestReport').addEventListener('click', async () => {
    const userId = parseInt(document.getElementById('reportUserId').value);
    const emails = document.getElementById('reportEmails').value.trim();
    if (!emails) {
        const errEl = document.getElementById('reportModalError');
        errEl.textContent = 'Completá los emails destino antes de enviar.';
        errEl.classList.remove('d-none');
        return;
    }
    const btn = document.getElementById('btnSendTestReport');
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Enviando...';
    document.getElementById('reportModalError').classList.add('d-none');
    document.getElementById('reportModalOk').classList.add('d-none');

    try {
        const r = await fetch('api.php?action=report_send_test', {
            method: 'POST',
            body: JSON.stringify({ user_id: userId, emails })
        });
        const d = await r.json();
        if (d.error) {
            const errEl = document.getElementById('reportModalError');
            errEl.textContent = d.error;
            errEl.classList.remove('d-none');
        } else {
            const okEl = document.getElementById('reportModalOk');
            okEl.textContent = d.message || 'Enviado.';
            okEl.classList.remove('d-none');
        }
    } catch (err) {
        const errEl = document.getElementById('reportModalError');
        errEl.textContent = 'Error del servidor. Revisá los logs de PHP.';
        errEl.classList.remove('d-none');
    } finally {
        btn.disabled = false;
        btn.innerHTML = '<i class="bi bi-send me-1"></i>Enviar copia ahora';
    }
});

document.getElementById('btnSaveReport').addEventListener('click', async () => {
    const payload = {
        user_id:     parseInt(document.getElementById('reportUserId').value),
        emails:      document.getElementById('reportEmails').value.trim(),
        day_of_week: parseInt(document.getElementById('reportDayOfWeek').value),
        send_hour:   parseInt(document.getElementById('reportSendHour').value),
        send_minute: parseInt(document.getElementById('reportSendMinute').value),
        active:      document.getElementById('reportActive').value,
    };
    const r = await fetch('api.php?action=report_config_save', { method: 'POST', body: JSON.stringify(payload) });
    const d = await r.json();
    if (d.error) {
        const errEl = document.getElementById('reportModalError');
        errEl.textContent = d.error;
        errEl.classList.remove('d-none');
    } else {
        document.getElementById('reportModalOk').classList.remove('d-none');
        document.getElementById('reportModalError').classList.add('d-none');
        setTimeout(() => loadReports(), 300);
    }
});

// ---- SMTP ----
async function loadSmtpConfig() {
    const r = await fetch('api.php?action=smtp_config_get');
    const d = await r.json();
    document.getElementById('smtpHost').value      = d.host       || '';
    document.getElementById('smtpPort').value      = d.port       || '587';
    document.getElementById('smtpUser').value      = d.user       || '';
    document.getElementById('smtpPass').value      = '';  // no pre-llenar la clave
    document.getElementById('smtpFromEmail').value = d.from_email || '';
    document.getElementById('smtpFromName').value  = d.from_name  || 'ZeroTrust Shield';
    const enc = d.encryption || 'tls';
    const radio = document.querySelector(`input[name="smtpEnc"][value="${enc}"]`);
    if (radio) radio.checked = true;
    const enabled = d.enabled === '1';
    document.getElementById('smtpEnabled').checked = enabled;
    document.getElementById('smtpEnabledLabel').textContent = enabled ? 'Habilitado' : 'Deshabilitado';
}

function smtpPayload() {
    return {
        host:       document.getElementById('smtpHost').value.trim(),
        port:       document.getElementById('smtpPort').value.trim(),
        encryption: document.querySelector('input[name="smtpEnc"]:checked')?.value || 'tls',
        user:       document.getElementById('smtpUser').value.trim(),
        pass:       document.getElementById('smtpPass').value,
        from_email: document.getElementById('smtpFromEmail').value.trim(),
        from_name:  document.getElementById('smtpFromName').value.trim(),
        enabled:    document.getElementById('smtpEnabled').checked ? '1' : '0',
    };
}

function smtpShowMsg(text, type) {
    const el = document.getElementById('smtpMsg');
    el.className = `alert alert-${type} mt-3`;
    el.textContent = text;
    el.classList.remove('d-none');
}

document.getElementById('smtpEnabled').addEventListener('change', function() {
    document.getElementById('smtpEnabledLabel').textContent = this.checked ? 'Habilitado' : 'Deshabilitado';
});

// Auto-rellenar puerto al cambiar cifrado
document.querySelectorAll('input[name="smtpEnc"]').forEach(r => {
    r.addEventListener('change', () => {
        const portMap = { ssl: '465', tls: '587', none: '25' };
        document.getElementById('smtpPort').value = portMap[r.value] || '587';
    });
});

// Toggle password visibility
document.getElementById('btnTogglePass').addEventListener('click', () => {
    const inp  = document.getElementById('smtpPass');
    const icon = document.getElementById('eyeIcon');
    if (inp.type === 'password') { inp.type = 'text';     icon.className = 'bi bi-eye-slash'; }
    else                         { inp.type = 'password'; icon.className = 'bi bi-eye'; }
});

document.getElementById('btnSmtpSave').addEventListener('click', async () => {
    const btn = document.getElementById('btnSmtpSave');
    btn.disabled = true; btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Guardando...';
    const r = await fetch('api.php?action=smtp_config_save', { method: 'POST', body: JSON.stringify(smtpPayload()) });
    const d = await r.json();
    btn.disabled = false; btn.innerHTML = '<i class="bi bi-floppy me-1"></i>Guardar configuración';
    smtpShowMsg(d.error ? d.error : 'Configuración guardada correctamente.', d.error ? 'danger' : 'success');
});

document.getElementById('btnSmtpTest').addEventListener('click', async () => {
    const to = document.getElementById('smtpTestEmail').value.trim();
    if (!to) { smtpShowMsg('Ingresá un email de prueba.', 'warning'); return; }
    const btn = document.getElementById('btnSmtpTest');
    btn.disabled = true; btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Enviando...';
    // Guardamos primero para que los cambios no guardados también apliquen al test
    await fetch('api.php?action=smtp_config_save', { method: 'POST', body: JSON.stringify(smtpPayload()) });
    const r = await fetch('api.php?action=smtp_test', { method: 'POST', body: JSON.stringify({ to, ...smtpPayload() }) });
    const d = await r.json();
    btn.disabled = false; btn.innerHTML = '<i class="bi bi-send me-1"></i>Enviar prueba';
    smtpShowMsg(d.error || d.message, d.error ? 'danger' : 'success');
});

// ---- Inicializar ----
document.addEventListener('DOMContentLoaded', () => {
    loadUsers();
    loadSyncStatus();

    document.querySelector('[data-bs-target="#tabAdguardClients"]').addEventListener('shown.bs.tab', loadAdguardClients);
    document.querySelector('[data-bs-target="#tabReports"]').addEventListener('shown.bs.tab', loadReports);
    document.querySelector('[data-bs-target="#tabSmtp"]').addEventListener('shown.bs.tab', loadSmtpConfig);
});
</script>
</body>
</html>
