<?php

require_once __DIR__ . '/common.php';

admin_require_login();

$pdo       = db();
$adminUser = admin_current_user();
$siteTitle = get_setting('site.title', '六柱博客');

$errors = [];


$actionFilter = trim((string)($_GET['action'] ?? ''));
$adminFilter  = isset($_GET['admin_id']) ? (int)$_GET['admin_id'] : 0;
$page         = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$pageSize     = 50;
$offset       = ($page - 1) * $pageSize;


try {
    $pdo->exec("
CREATE TABLE IF NOT EXISTS admin_logs (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    admin_id INTEGER,
    action TEXT NOT NULL,
    details TEXT,
    ip TEXT,
    created_at INTEGER NOT NULL
)
");
} catch (Throwable $e) {
    
}


$total = 0;
$logs  = [];

$where  = [];
$params = [];

if ($actionFilter !== '') {
    $where[]            = 'action = :action';
    $params[':action']  = $actionFilter;
}
if ($adminFilter > 0) {
    $where[]             = 'admin_id = :admin_id';
    $params[':admin_id'] = $adminFilter;
}

$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

try {
    $stmt = $pdo->prepare("SELECT COUNT(*) AS c FROM admin_logs {$whereSql}");
    $stmt->execute($params);
    $total = (int)$stmt->fetchColumn();
} catch (Throwable $e) {
    $errors[] = '无法读取日志总数（可能尚未初始化 admin_logs 表）。';
}

try {
    $sql = "
SELECT l.id,
       l.admin_id,
       l.action,
       l.details,
       l.ip,
       l.created_at,
       u.nickname,
       u.email
FROM admin_logs l
LEFT JOIN users u ON u.id = l.admin_id
{$whereSql}
ORDER BY l.id DESC
LIMIT :limit OFFSET :offset
";
    $stmt = $pdo->prepare($sql);
    foreach ($params as $k => $v) {
        $stmt->bindValue($k, $v);
    }
    $stmt->bindValue(':limit', $pageSize, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();
    $logs = $stmt->fetchAll() ?: [];
} catch (Throwable $e) {
    $errors[] = '无法读取操作日志（请确认数据库已初始化）：' . $e->getMessage();
    $logs     = [];
}


$actionOptions = [];
try {
    $stmt = $pdo->query("SELECT DISTINCT action FROM admin_logs ORDER BY action ASC LIMIT 100");
    while ($row = $stmt->fetch()) {
        $actionOptions[] = (string)$row['action'];
    }
} catch (Throwable $e) {
    $actionOptions = [];
}

?><!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>操作日志 - <?php echo h($siteTitle); ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        html, body { height:100%;  margin:0; padding:0; }
        body {
            margin: 0; padding:0;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif;
            background: #020617;
            color: #e5e7eb;
        }
        a {
            color: #60a5fa;
            text-decoration: none;
        }
        a:hover {
            text-decoration: underline;
        }
        .topbar {
            background: #0f172a;
            border-bottom: 1px solid #1f2937;
            padding:18px 16px 6px;
            display: flex;
            align-items:flex-start;
            justify-content: space-between;
         margin:0;  margin-top:-12px; }
        .topbar-title {
            font-size: 16px;
            font-weight: 600;
        }
        .topbar-user {
            font-size: 13px;
            color: #9ca3af;
        }
        .topbar-nav a {
            margin-left: 10px;
            font-size: 13px;
        }
        .page {
            max-width: 1100px;
            margin: 0 auto;
            padding: 16px;
        }
        .card {
            background: #020617;
            border-radius: 6px;
            border: 1px solid #1f2937;
            padding: 12px 14px;
            margin-bottom: 12px;
        }
        .card-title {
            font-size: 14px;
            font-weight: 600;
            margin-bottom: 8px;
        }
        .small-text {
            font-size: 12px;
            color: #9ca3af;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 12px;
        }
        th, td {
            border-bottom: 1px solid #1f2937;
            padding: 4px 6px;
            text-align: left;
        }
        th {
            font-weight: 600;
            background: #020617;
        }
        .filters {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
            margin-bottom: 8px;
        }
        .filters input,
        .filters select {
            padding: 3px 6px;
            border-radius: 4px;
            border: 1px solid #374151;
            background: #020617;
            color: #e5e7eb;
            font-size: 12px;
        }
        .btn-small {
            border-radius: 999px;
            border: 1px solid #374151;
            background: transparent;
            color: #e5e7eb;
            font-size: 11px;
            padding: 2px 6px;
            cursor: pointer;
        }
        .errors {
            background: #7f1d1d;
            border: 1px solid #fecaca;
            color: #fee2e2;
            padding: 6px 8px;
            border-radius: 4px;
            font-size: 12px;
            margin-bottom: 10px;
        }
    </style>
</head>
<body style="margin:0;padding:0;"><div class="topbar">
    <div class="topbar-title">操作日志</div>
    <div class="topbar-user">
        管理员：<?php echo h($adminUser['nickname'] ?? $adminUser['email'] ?? ''); ?>
        <span class="topbar-nav">
            <a href="index.php">仪表盘</a>
            <a href="articles.php">文章</a>
            <a href="categories.php">分类</a>
            <a href="tags.php">&#26631;&#31614;</a>
            <a href="comments.php">评论</a>
            <a href="links.php">友链</a>
                <a href="media.php">文件</a>
            <a href="users.php">会员</a>
            <a href="sensitive_words.php">敏感词</a>
            <a href="stats.php">流量</a>
            <a href="security.php">防护</a>
            <a href="logs.php"><strong>日志</strong></a>
            <a href="settings.php">设置</a>
            <a href="backup_sqlite.php">&#25968;&#25454;</a>
            <a href="../index.php">前台</a>
            <a href="../logout.php">退出</a>
        </span>
    </div>
</div>

<div class="page">
    <?php if ($errors): ?>
        <div class="errors">
            <?php foreach ($errors as $err): ?>
                <div><?php echo h($err); ?></div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <div class="card">
        <div class="card-title">筛选</div>
        <form method="get" class="filters">
            <div>
                <select name="action">
                    <option value="">全部动作</option>
                    <?php foreach ($actionOptions as $act): ?>
                        <option value="<?php echo h($act); ?>" <?php echo $act === $actionFilter ? 'selected' : ''; ?>>
                            <?php echo h($act); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <input type="number" name="admin_id" placeholder="管理员ID" value="<?php echo $adminFilter > 0 ? (int)$adminFilter : ''; ?>">
            </div>
            <div>
                <button type="submit" class="btn-small">应用筛选</button>
            </div>
            <div class="small-text">
                共 <?php echo (int)$total; ?> 条记录，当前第 <?php echo (int)$page; ?> 页。
            </div>
        </form>
    </div>

    <div class="card">
        <div class="card-title">操作日志列表（按时间倒序，最多 50 条/页）</div>
        <?php if ($logs): ?>
            <table>
                <thead>
                <tr>
                    <th>ID</th>
                    <th>时间</th>
                    <th>管理员</th>
                    <th>动作</th>
                    <th>详情</th>
                    <th>IP</th>
                </tr>
                </thead>
                <tbody>
                <?php foreach ($logs as $row): ?>
                    <tr>
                        <td><?php echo (int)$row['id']; ?></td>
                        <td><?php echo date('Y-m-d H:i:s', (int)$row['created_at']); ?></td>
                        <td>
                            <?php
                            if (!empty($row['nickname']) || !empty($row['email'])) {
                                echo h($row['nickname'] ?: $row['email']) . ' (#' . (int)$row['admin_id'] . ')';
                            } elseif (!empty($row['admin_id'])) {
                                echo 'ID #' . (int)$row['admin_id'];
                            } else {
                                echo '系统/匿名';
                            }
                            ?>
                        </td>
                        <td><?php echo h($row['action']); ?></td>
                        <td>
                            <span class="small-text">
                                <?php
                                $detail = (string)($row['details'] ?? '');
                                if ($detail === '') {
                                    echo '-';
                                } else {
                                    if (function_exists('mb_substr')) {
                                        $short = mb_substr($detail, 0, 80, 'UTF-8');
                                    } else {
                                        $short = substr($detail, 0, 80);
                                    }
                                    echo h($short);
                                    if (strlen($detail) > strlen($short)) {
                                        echo '...';
                                    }
                                }
                                ?>
                            </span>
                        </td>
                        <td><?php echo h($row['ip']); ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>

            <?php if ($total > $pageSize): ?>
                <div class="small-text" style="margin-top:8px;">
                    <?php if ($page > 1): ?>
                        <a href="?<?php echo http_build_query(['action' => $actionFilter, 'admin_id' => $adminFilter, 'page' => $page - 1]); ?>">上一页</a>
                    <?php endif; ?>
                    <span>第 <?php echo (int)$page; ?> 页</span>
                    <?php if ($page * $pageSize < $total): ?>
                        <a href="?<?php echo http_build_query(['action' => $actionFilter, 'admin_id' => $adminFilter, 'page' => $page + 1]); ?>">下一页</a>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        <?php else: ?>
            <div class="small-text">暂未找到日志记录（可能尚未触发后台敏感操作）。</div>
        <?php endif; ?>
    </div>
</div>
</body>
</html>
