<?php
/**
 * TechShop Perú - Panel Admin: Log de Auditoría (Mejora 13)
 */
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/database.php';
require_once __DIR__ . '/../includes/functions.php';

require_admin();

$page_title = 'Log de Auditoría';
$db = db();

// Crear tabla si no existe
try {
    $db->exec("CREATE TABLE IF NOT EXISTS admin_audit_log (
        id INT AUTO_INCREMENT PRIMARY KEY,
        usuario_id INT DEFAULT NULL,
        accion VARCHAR(100) NOT NULL,
        tabla VARCHAR(100) NOT NULL,
        registro_id INT DEFAULT 0,
        datos JSON DEFAULT NULL,
        ip VARCHAR(64) DEFAULT NULL,
        creado_en TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        KEY idx_tabla_reg (tabla, registro_id),
        KEY idx_usuario (usuario_id),
        KEY idx_creado (creado_en)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
} catch (Exception $e) {}

$pagina = max(1, (int)($_GET['pagina'] ?? 1));
$por_pagina = 30;
$offset = ($pagina - 1) * $por_pagina;

$filtro_accion = trim($_GET['accion'] ?? '');
$filtro_admin  = trim($_GET['admin'] ?? '');
$filtro_tabla  = trim($_GET['tabla'] ?? '');

$where = [];
$params = [];
if ($filtro_accion !== '') { $where[] = 'l.accion LIKE ?'; $params[] = '%' . $filtro_accion . '%'; }
if ($filtro_admin  !== '') { $where[] = '(CONCAT(u.nombres, COALESCE(CONCAT(" ", u.apellidos), "")) LIKE ? OR u.email LIKE ?)'; $params[] = '%' . $filtro_admin . '%'; $params[] = '%' . $filtro_admin . '%'; }
if ($filtro_tabla  !== '') { $where[] = 'l.tabla LIKE ?'; $params[] = '%' . $filtro_tabla . '%'; }
$whereSQL = $where ? 'WHERE ' . implode(' AND ', $where) : '';

try {
    $total = $db->prepare("SELECT COUNT(*) FROM admin_audit_log l LEFT JOIN usuarios u ON l.usuario_id = u.id $whereSQL");
    $total->execute($params);
    $total = (int)$total->fetchColumn();

    $stmt = $db->prepare("SELECT l.*, CONCAT(u.nombres, COALESCE(CONCAT(' ', u.apellidos), '')) AS admin_nombre, u.email AS admin_email
        FROM admin_audit_log l 
        LEFT JOIN usuarios u ON l.usuario_id = u.id
        $whereSQL
        ORDER BY l.creado_en DESC LIMIT $por_pagina OFFSET $offset");
    $stmt->execute($params);
    $logs = $stmt->fetchAll();
} catch (Exception $e) {
    $logs = [];
    $total = 0;
}

$total_paginas = ceil($total / $por_pagina);

require_once __DIR__ . '/views/layout.php';
?>
<div class="d-flex justify-content-between align-items-center mb-4">
    <h4 class="fw-bold mb-0"><i class="bi bi-shield-check text-primary me-2"></i>Log de Auditoría Admin</h4>
    <a href="<?= url('api/export-csv.php?tipo=pedidos') ?>" class="btn btn-outline-success btn-sm">
        <i class="bi bi-download me-1"></i>Exportar Pedidos CSV
    </a>
</div>

<!-- Filtros -->
<div class="card shadow-sm border-0 mb-4" style="border-radius:12px;">
    <div class="card-body p-3">
        <form method="GET" class="row g-2 align-items-end">
            <div class="col-md-3">
                <label class="form-label small mb-1">Acción</label>
                <input type="text" name="accion" class="form-control form-control-sm" placeholder="stock_update, delete..." value="<?= e($filtro_accion) ?>">
            </div>
            <div class="col-md-3">
                <label class="form-label small mb-1">Administrador</label>
                <input type="text" name="admin" class="form-control form-control-sm" placeholder="nombre o email" value="<?= e($filtro_admin) ?>">
            </div>
            <div class="col-md-3">
                <label class="form-label small mb-1">Tabla</label>
                <input type="text" name="tabla" class="form-control form-control-sm" placeholder="productos, pedidos..." value="<?= e($filtro_tabla) ?>">
            </div>
            <div class="col-md-3">
                <button type="submit" class="btn btn-primary btn-sm w-100"><i class="bi bi-search me-1"></i>Filtrar</button>
            </div>
        </form>
    </div>
</div>

<div class="card shadow-sm border-0" style="border-radius:12px;">
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-light">
                    <tr>
                        <th>#</th>
                        <th>Admin</th>
                        <th>Acción</th>
                        <th>Tabla</th>
                        <th>ID Reg.</th>
                        <th>IP</th>
                        <th>Fecha</th>
                        <th>Datos</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($logs)): ?>
                    <tr><td colspan="8" class="text-center text-muted py-4">No hay registros de auditoría todavía.</td></tr>
                    <?php else: ?>
                    <?php foreach ($logs as $log): ?>
                    <tr>
                        <td class="text-muted small"><?= $log['id'] ?></td>
                        <td>
                            <small class="fw-semibold"><?= e($log['admin_nombre'] ?? 'Sistema') ?></small><br>
                            <small class="text-muted"><?= e($log['admin_email'] ?? '') ?></small>
                        </td>
                        <td><span class="badge bg-primary-subtle text-primary border border-primary" style="font-size:.78rem;"><?= e($log['accion']) ?></span></td>
                        <td><code class="small"><?= e($log['tabla']) ?></code></td>
                        <td class="text-center"><?= $log['registro_id'] ?: '-' ?></td>
                        <td><small class="text-muted font-monospace"><?= e($log['ip'] ?? '-') ?></small></td>
                        <td><small><?= date('d/m/Y H:i', strtotime($log['creado_en'])) ?></small></td>
                        <td>
                            <?php if ($log['datos']): ?>
                            <button class="btn btn-outline-secondary btn-sm py-0" 
                                    onclick="this.nextElementSibling.classList.toggle('d-none')" title="Ver datos">
                                <i class="bi bi-code-slash"></i>
                            </button>
                            <pre class="d-none mt-1 p-2 bg-light rounded small" style="max-width:300px;max-height:150px;overflow:auto;font-size:.72rem;"><?= e($log['datos']) ?></pre>
                            <?php else: ?>
                            <span class="text-muted">—</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <?php if ($total_paginas > 1): ?>
        <div class="p-3">
            <nav><ul class="pagination justify-content-center pagination-sm mb-0">
                <?php for ($i = 1; $i <= $total_paginas; $i++): ?>
                <li class="page-item <?= $i === $pagina ? 'active' : '' ?>">
                    <a class="page-link" href="?pagina=<?= $i ?>&accion=<?= urlencode($filtro_accion) ?>&admin=<?= urlencode($filtro_admin) ?>&tabla=<?= urlencode($filtro_tabla) ?>"><?= $i ?></a>
                </li>
                <?php endfor; ?>
            </ul></nav>
        </div>
        <?php endif; ?>
    </div>
</div>
<p class="text-muted small mt-2">Total: <?= $total ?> acciones registradas.</p>
