<?php
session_start();
require_once '../inc/admin_auth.php';
requireAdmin();
require_once '../inc/functions.php';

$page = (int)($_GET['page'] ?? 1);
if ($page < 1) $page = 1;
$perPage = 10;
$offset = ($page - 1) * $perPage;

$typeFilter = $_GET['type'] ?? '';

// Основной запрос логов
$sql = "SELECT SQL_CALC_FOUND_ROWS * FROM security_logs";
$params = [];
if ($typeFilter) {
    $sql .= " WHERE type = ?";
    $params[] = $typeFilter;
}
$sql .= " ORDER BY created_at DESC LIMIT ? OFFSET ?";
$params[] = $perPage;
$params[] = $offset;

$stmt = $pdo->prepare($sql);
$i = 1;
foreach ($params as $param) {
    $stmt->bindValue($i++, $param, is_int($param) ? PDO::PARAM_INT : PDO::PARAM_STR);
}
$stmt->execute();
$logs = $stmt->fetchAll();
$total = $pdo->query("SELECT FOUND_ROWS()")->fetchColumn();

// Статистика по типам (общая, без учёта фильтра)
$stats = [
    'total' => 0,
    '404' => 0,
    'sql_injection' => 0,
    'suspicious' => 0,
    'other' => 0
];
$statsRaw = $pdo->query("SELECT type, COUNT(*) as cnt FROM security_logs GROUP BY type")->fetchAll();
foreach ($statsRaw as $row) {
    $type = $row['type'];
    if (isset($stats[$type])) {
        $stats[$type] = (int)$row['cnt'];
    } else {
        $stats['other'] += (int)$row['cnt'];
    }
    $stats['total'] += (int)$row['cnt'];
}

require_once '../inc/header.php';
?>

<style>
/* === Modern Dark Theme for Security Logs === */
.security-logs-dark {
    font-family: 'Inter', 'Segoe UI', Roboto, system-ui, sans-serif;
    background: #0b0f17;
    color: #e2e8f0;
    padding: 2rem;
    border-radius: 2rem;
    box-shadow: inset 0 0 0 1px rgba(255,255,255,0.05), 0 20px 30px -10px black;
    margin: 1rem 0;
}

/* header */
.logs-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 1rem;
    margin-bottom: 2rem;
}
.logs-header h2 {
    margin: 0;
    font-weight: 600;
    font-size: 2rem;
    background: linear-gradient(135deg, #a5b4fc, #818cf8);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    display: flex;
    align-items: center;
    gap: 0.75rem;
}

/* stats cards */
.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
    gap: 1rem;
    margin-bottom: 2rem;
}
.stat-card {
    background: rgba(18, 25, 40, 0.7);
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
    border: 1px solid rgba(255,255,255,0.05);
    border-radius: 1.5rem;
    padding: 1.2rem 1rem;
    box-shadow: 0 8px 20px rgba(0,0,0,0.6);
    transition: 0.2s;
}
.stat-card:hover {
    background: rgba(28, 35, 55, 0.8);
    border-color: rgba(255,255,255,0.1);
}
.stat-title {
    font-size: 0.9rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    color: #94a3b8;
    margin-bottom: 0.5rem;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}
.stat-value {
    font-size: 2.5rem;
    font-weight: 700;
    line-height: 1;
    color: white;
}
.stat-card.total   { border-left: 4px solid #818cf8; }
.stat-card._404    { border-left: 4px solid #f59e0b; }
.stat-card.sql     { border-left: 4px solid #ef4444; }
.stat-card.susp    { border-left: 4px solid #3b82f6; }
.stat-card.other   { border-left: 4px solid #64748b; }

/* filter bar */
.filter-bar {
    background: rgba(18, 25, 40, 0.8);
    backdrop-filter: blur(8px);
    border: 1px solid rgba(255,255,255,0.05);
    border-radius: 3rem;
    padding: 0.8rem 1.5rem;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 1rem;
    margin-bottom: 2rem;
    box-shadow: 0 8px 16px rgba(0,0,0,0.4);
}
.filter-group {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    flex-wrap: wrap;
}
.filter-group label {
    font-weight: 500;
    color: #cbd5e1;
    font-size: 0.95rem;
}
.filter-group select {
    background: #1e293b;
    border: 1px solid #334155;
    color: #f1f5f9;
    padding: 0.5rem 2.5rem 0.5rem 1.2rem;
    border-radius: 2rem;
    font-size: 0.95rem;
    cursor: pointer;
    appearance: none;
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%2394a3b8' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
    background-repeat: no-repeat;
    background-position: right 1rem center;
}
.btn {
    padding: 0.5rem 1.5rem;
    border-radius: 2rem;
    font-weight: 500;
    font-size: 0.95rem;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    transition: 0.2s;
    border: none;
    cursor: pointer;
    background: transparent;
    color: #e2e8f0;
}
.btn-primary {
    background: linear-gradient(145deg, #4f46e5, #6366f1);
    color: white;
    box-shadow: 0 8px 16px -5px #4f46e5;
}
.btn-primary:hover {
    background: linear-gradient(145deg, #6366f1, #818cf8);
    transform: translateY(-2px);
}
.btn-secondary {
    background: #1e293b;
    color: #e2e8f0;
    border: 1px solid #334155;
}
.btn-secondary:hover {
    background: #2d3a4f;
}

/* table */
.table-responsive {
    overflow-x: auto;
    border-radius: 1.5rem;
    background: #0f172a;
    border: 1px solid #1e293b;
    box-shadow: 0 15px 30px -12px black;
}
.modern-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 0.9rem;
    color: #e2e8f0;
}
.modern-table th {
    background: #111c2e;
    color: #a5b4fc;
    font-weight: 600;
    padding: 1rem 0.75rem;
    text-align: left;
    white-space: nowrap;
    border-bottom: 1px solid #1e293b;
}
.modern-table td {
    padding: 1rem 0.75rem;
    border-bottom: 1px solid #1e293b;
    vertical-align: top;
}
.modern-table tbody tr:hover {
    background: #1a2538;
}
.modern-table tbody tr:last-child td {
    border-bottom: none;
}

/* badges */
.badge {
    display: inline-flex;
    align-items: center;
    gap: 0.4rem;
    padding: 0.3rem 1rem;
    border-radius: 20px;
    font-weight: 600;
    font-size: 0.8rem;
    letter-spacing: 0.3px;
    text-transform: uppercase;
    background: #1e293b;
    color: #e2e8f0;
    white-space: nowrap;
}
.badge-404 {
    background: #7b341e;
    color: #fed7aa;
}
.badge-sql_injection {
    background: #7f1d1d;
    color: #fecaca;
}
.badge-suspicious {
    background: #1e3a8a;
    color: #bfdbfe;
}
.badge-other {
    background: #2d3748;
    color: #cbd5e0;
}

/* json viewer */
.json-view {
    background: #0b101a;
    border: 1px solid #1e293b;
    border-radius: 1rem;
    padding: 0.75rem;
    font-family: 'JetBrains Mono', 'Fira Code', monospace;
    font-size: 0.75rem;
    line-height: 1.5;
    max-width: 350px;
    max-height: 200px;
    overflow: auto;
    white-space: pre-wrap;
    word-break: break-word;
    color: #cbd5e1;
    box-shadow: inset 0 4px 8px rgba(0,0,0,0.6);
}

/* pagination */
.pagination {
    margin-top: 2rem;
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    gap: 0.4rem;
}
.page-item {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 2.5rem;
    height: 2.5rem;
    padding: 0 0.2rem;
    border-radius: 9999px;
    background: #1e293b;
    border: 1px solid #334155;
    color: #cbd5e1;
    text-decoration: none;
    font-weight: 500;
    transition: 0.2s;
}
.page-item:hover {
    background: #2d3a4f;
    border-color: #4f46e5;
    color: white;
}
.page-item.active {
    background: #4f46e5;
    border-color: #4f46e5;
    color: white;
}

/* counter */
.record-counter {
    margin-top: 1rem;
    font-size: 0.9rem;
    color: #94a3b8;
    background: #111c2e;
    padding: 0.5rem 1.2rem;
    border-radius: 2rem;
    display: inline-block;
    border: 1px solid #1e293b;
}
</style>

<div class="security-logs-dark">

    <!-- header -->
    <div class="logs-header">
        <h2>
            <span>🛡️</span> Логи безопасности
        </h2>
        <a class="btn btn-secondary" href="index.php">
            ← В админ-панель
        </a>
    </div>

    <!-- statistics cards -->
    <div class="stats-grid">
        <div class="stat-card total">
            <div class="stat-title"><span>📋</span> Всего</div>
            <div class="stat-value"><?= $stats['total'] ?></div>
        </div>
        <div class="stat-card _404">
            <div class="stat-title"><span>🚫</span> 404</div>
            <div class="stat-value"><?= $stats['404'] ?></div>
        </div>
        <div class="stat-card sql">
            <div class="stat-title"><span>💉</span> SQL-инъекции</div>
            <div class="stat-value"><?= $stats['sql_injection'] ?></div>
        </div>
        <div class="stat-card susp">
            <div class="stat-title"><span>👀</span> Подозрительные</div>
            <div class="stat-value"><?= $stats['suspicious'] ?></div>
        </div>
        <div class="stat-card other">
            <div class="stat-title"><span>⚙️</span> Другое</div>
            <div class="stat-value"><?= $stats['other'] ?></div>
        </div>
    </div>

    <!-- filter -->
    <div class="filter-bar">
        <form method="get" style="display: contents;">
            <div class="filter-group">
                <label for="type-filter">Тип события:</label>
                <select name="type" id="type-filter">
                    <option value="">Все</option>
                    <option value="404" <?= $typeFilter == '404' ? 'selected' : '' ?>>404</option>
                    <option value="sql_injection" <?= $typeFilter == 'sql_injection' ? 'selected' : '' ?>>SQL-инъекция</option>
                    <option value="suspicious" <?= $typeFilter == 'suspicious' ? 'selected' : '' ?>>Подозрительный</option>
                    <option value="other" <?= $typeFilter == 'other' ? 'selected' : '' ?>>Другое</option>
                </select>
            </div>
            <button type="submit" class="btn btn-primary">
                🔍 Применить
            </button>
            <?php if ($typeFilter): ?>
                <a href="security_logs.php" class="btn btn-secondary">
                    ✕ Сбросить
                </a>
            <?php endif; ?>
        </form>
    </div>

    <!-- logs table -->
    <div class="table-responsive">
        <table class="modern-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Тип</th>
                    <th>URL</th>
                    <th>IP</th>
                    <th>User-Agent</th>
                    <th>Данные запроса</th>
                    <th>Время</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($logs as $log): 
                $requestData = !empty($log['request_data']) ? json_decode($log['request_data'], true) : null;
                $badgeClass = 'badge';
                $icon = '';
                switch ($log['type']) {
                    case '404': $badgeClass .= ' badge-404'; $icon = '🚫'; break;
                    case 'sql_injection': $badgeClass .= ' badge-sql_injection'; $icon = '💉'; break;
                    case 'suspicious': $badgeClass .= ' badge-suspicious'; $icon = '👀'; break;
                    default: $badgeClass .= ' badge-other'; $icon = '⚙️';
                }
            ?>
                <tr>
                    <td><code>#<?= $log['id'] ?></code></td>
                    <td>
                        <span class="<?= $badgeClass ?>">
                            <?= $icon ?> <?= htmlspecialchars($log['type']) ?>
                        </span>
                    </td>
                    <td><small><?= htmlspecialchars($log['url']) ?></small></td>
                    <td><code><?= htmlspecialchars($log['ip']) ?></code></td>
                    <td style="max-width:200px;"><small><?= htmlspecialchars($log['user_agent']) ?></small></td>
                    <td>
                        <?php if ($requestData && is_array($requestData)): ?>
                            <div class="json-view"><?php
                                echo htmlspecialchars(json_encode($requestData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
                            ?></div>
                        <?php else: ?>
                            <span class="badge badge-other" style="background:transparent; padding:0;">—</span>
                        <?php endif; ?>
                    </td>
                    <td><small><?= date('d.m.Y H:i:s', strtotime($log['created_at'])) ?></small></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <!-- record info -->
    <div class="record-counter">
        <?php
        $from = $offset + 1;
        $to = min($offset + $perPage, $total);
        if ($total > 0) {
            echo "Показано записей: $from – $to из $total";
        } else {
            echo "Записей не найдено";
        }
        ?>
    </div>

    <!-- pagination -->
    <?php if ($total > $perPage): ?>
        <div class="pagination">
            <?php for ($i = 1; $i <= ceil($total / $perPage); $i++): ?>
                <a class="page-item <?= ($i == $page) ? 'active' : '' ?>" 
                   href="?type=<?= urlencode($typeFilter) ?>&page=<?= $i ?>">
                    <?= $i ?>
                </a>
            <?php endfor; ?>
        </div>
    <?php endif; ?>

</div> <!-- .security-logs-dark -->

<?php require_once '../inc/foot.php'; ?>