<?php

require_once __DIR__ . '/common.php';

admin_require_login();

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

$errors = [];
$infos  = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!admin_csrf_check($_POST['csrf_token'] ?? null)) {
        $errors[] = '请求已失效，请刷新页面后重试。';
    } else {
        $action = trim((string)($_POST['action'] ?? ''));
        $id     = (int)($_POST['id'] ?? 0);
        $name   = trim((string)($_POST['name'] ?? ''));

        try {
            if ($action === 'create') {
                if ($name === '') {
                    $errors[] = '标签名称不能为空。';
                } else {
                    if (mb_strlen($name, 'UTF-8') > 20) {
                        $name = mb_substr($name, 0, 20, 'UTF-8');
                    }

                    $stmt = $pdo->prepare("SELECT id FROM tags WHERE name = :name LIMIT 1");
                    $stmt->execute([':name' => $name]);
                    if ($stmt->fetch()) {
                        $errors[] = '标签已存在，请勿重复新增。';
                    } else {
                        $stmt = $pdo->prepare("
                            INSERT INTO tags (name, slug, created_at)
                            VALUES (:name, NULL, :created_at)
                        ");
                        $stmt->execute([
                            ':name' => $name,
                            ':created_at' => time(),
                        ]);
                        $infos[] = '标签已新增：' . $name;
                        admin_log('tag_create', '新增标签：' . $name);
                    }
                }
            } elseif ($action === 'update') {
                if ($id <= 0) {
                    $errors[] = '参数错误：标签 ID 无效。';
                } elseif ($name === '') {
                    $errors[] = '标签名称不能为空。';
                } else {
                    if (mb_strlen($name, 'UTF-8') > 20) {
                        $name = mb_substr($name, 0, 20, 'UTF-8');
                    }

                    $stmt = $pdo->prepare("SELECT id FROM tags WHERE name = :name AND id <> :id LIMIT 1");
                    $stmt->execute([
                        ':name' => $name,
                        ':id' => $id,
                    ]);
                    if ($stmt->fetch()) {
                        $errors[] = '已存在同名标签，请更换名称。';
                    } else {
                        $stmt = $pdo->prepare("UPDATE tags SET name = :name WHERE id = :id");
                        $stmt->execute([
                            ':name' => $name,
                            ':id' => $id,
                        ]);
                        $infos[] = '标签已更新（ID=' . $id . '）。';
                        admin_log('tag_update', '更新标签 ID=' . $id . ' 为：' . $name);
                    }
                }
            } elseif ($action === 'delete') {
                if ($id <= 0) {
                    $errors[] = '参数错误：标签 ID 无效。';
                } else {
                    $stmt = $pdo->prepare("SELECT name FROM tags WHERE id = :id LIMIT 1");
                    $stmt->execute([':id' => $id]);
                    $row = $stmt->fetch();
                    if (!$row) {
                        $errors[] = '标签不存在，可能已被删除。';
                    } else {
                        $tagName = (string)$row['name'];
                        $pdo->beginTransaction();
                        $stmt = $pdo->prepare("DELETE FROM article_tag WHERE tag_id = :id");
                        $stmt->execute([':id' => $id]);
                        $stmt = $pdo->prepare("DELETE FROM tags WHERE id = :id");
                        $stmt->execute([':id' => $id]);
                        $pdo->commit();

                        $infos[] = '标签已删除：' . $tagName;
                        admin_log('tag_delete', '删除标签 ID=' . $id . '，名称：' . $tagName);
                    }
                }
            }
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $errors[] = '操作失败：' . $e->getMessage();
        }
    }
}

$q = trim((string)($_GET['q'] ?? ''));
$page = max(1, (int)($_GET['page'] ?? 1));
$pageSize = 50;
$offset = ($page - 1) * $pageSize;

$whereSql = '';
$params = [];
if ($q !== '') {
    $whereSql = 'WHERE t.name LIKE :q';
    $params[':q'] = '%' . $q . '%';
}

$total = 0;
$items = [];

try {
    $sqlCount = "SELECT COUNT(*) AS c FROM tags t " . $whereSql;
    $stmt = $pdo->prepare($sqlCount);
    $stmt->execute($params);
    $total = (int)($stmt->fetchColumn() ?: 0);

    $sqlItems = "
        SELECT
            t.id,
            t.name,
            t.created_at,
            COUNT(at.article_id) AS article_count
        FROM tags t
        LEFT JOIN article_tag at ON at.tag_id = t.id
        " . $whereSql . "
        GROUP BY t.id, t.name, t.created_at
        ORDER BY article_count DESC, t.id DESC
        LIMIT :limit OFFSET :offset
    ";
    $stmt = $pdo->prepare($sqlItems);
    foreach ($params as $k => $v) {
        $stmt->bindValue($k, $v, PDO::PARAM_STR);
    }
    $stmt->bindValue(':limit', $pageSize, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();
    $items = $stmt->fetchAll() ?: [];
} catch (Throwable $e) {
    $errors[] = '无法读取标签列表（可能尚未初始化数据库）。';
}

$totalPages = max(1, (int)ceil($total / $pageSize));
if ($page > $totalPages) {
    $page = $totalPages;
}

?>
<!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: 980px;
            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;
        }

        .form-row {
            display: flex;
            gap: 6px;
            margin-bottom: 6px;
        }
        .form-row input {
            padding: 4px 6px;
            border-radius: 4px;
            border: 1px solid #374151;
            background: #020617;
            color: #e5e7eb;
            font-size: 13px;
        }

        .btn {
            border-radius: 999px;
            border: 1px solid #3b82f6;
            background: #1d4ed8;
            color: #e5e7eb;
            font-size: 12px;
            padding: 4px 8px;
            cursor: pointer;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 13px;
        }
        th, td {
            border-bottom: 1px solid #1f2937;
            padding: 6px 4px;
            text-align: left;
            vertical-align: top;
        }
        th {
            color: #9ca3af;
            font-weight: 500;
        }

        .errors {
            background: #7f1d1d;
            border: 1px solid #fecaca;
            color: #fee2e2;
            padding: 6px 8px;
            border-radius: 4px;
            font-size: 12px;
            margin-bottom: 10px;
        }
        .infos {
            background: #14532d;
            border: 1px solid #22c55e;
            color: #bbf7d0;
            padding: 6px 8px;
            border-radius: 4px;
            font-size: 12px;
            margin-bottom: 10px;
        }
        .small-text {
            font-size: 12px;
            color: #9ca3af;
        }
        .pagination {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-top: 8px;
            font-size: 12px;
        }
    </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"><strong>标签</strong></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">日志</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; ?>
        <?php if ($infos): ?>
            <div class="infos">
                <?php foreach ($infos as $msg): ?>
                    <div><?php echo h($msg); ?></div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <div class="card">
            <div class="card-title">新增标签</div>
            <form method="post">
                <input type="hidden" name="csrf_token" value="<?php echo h(admin_csrf_token()); ?>">
                <input type="hidden" name="action" value="create">
                <div class="form-row">
                    <input type="text" name="name" placeholder="标签名称（最多 20 字）" required style="min-width:220px;">
                    <button type="submit" class="btn">新增标签</button>
                </div>
                <div class="small-text">提示：标签名称区分内容，不建议创建语义重复标签（如“资源”与“资源站资源”）。</div>
            </form>
        </div>

        <div class="card">
            <div class="card-title">标签列表</div>
            <form method="get" class="form-row" style="margin-bottom:8px;">
                <input type="text" name="q" value="<?php echo h($q); ?>" placeholder="搜索标签名称" style="min-width:220px;">
                <button type="submit" class="btn">搜索</button>
                <?php if ($q !== ''): ?>
                    <a href="tags.php" class="btn" style="display:inline-flex;align-items:center;">清空</a>
                <?php endif; ?>
            </form>

            <table>
                <thead>
                    <tr>
                        <th style="width:60px;">ID</th>
                        <th>标签名</th>
                        <th style="width:100px;">文章数</th>
                        <th style="width:160px;">创建时间</th>
                        <th style="width:220px;">操作</th>
                    </tr>
                </thead>
                <tbody>
                <?php if ($items): ?>
                    <?php foreach ($items as $item): ?>
                        <?php $tid = (int)$item['id']; ?>
                        <tr>
                            <td><?php echo $tid; ?></td>
                            <td>
                                <form method="post" id="tag-form-<?php echo $tid; ?>" class="form-row" style="margin:0;">
                                    <input type="hidden" name="csrf_token" value="<?php echo h(admin_csrf_token()); ?>">
                                    <input type="hidden" name="action" value="update">
                                    <input type="hidden" name="id" value="<?php echo $tid; ?>">
                                    <input type="text" name="name" value="<?php echo h((string)$item['name']); ?>" style="width:180px;">
                                </form>
                            </td>
                            <td><?php echo (int)$item['article_count']; ?></td>
                            <td><?php echo !empty($item['created_at']) ? date('Y-m-d H:i', (int)$item['created_at']) : '-'; ?></td>
                            <td>
                                <button type="submit" class="btn" form="tag-form-<?php echo $tid; ?>">保存</button>
                                <form method="post" style="display:inline;margin-left:4px;" onsubmit="return confirm('确定删除该标签？将同时解除与文章的标签关联。');">
                                    <input type="hidden" name="csrf_token" value="<?php echo h(admin_csrf_token()); ?>">
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="id" value="<?php echo $tid; ?>">
                                    <button type="submit" class="btn">删除</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="5" class="small-text">暂无标签记录。</td>
                    </tr>
                <?php endif; ?>
                </tbody>
            </table>

            <div class="pagination">
                <span>共 <?php echo $total; ?> 条</span>
                <span>第 <?php echo $page; ?> / <?php echo $totalPages; ?> 页</span>
                <?php if ($page > 1): ?>
                    <a href="tags.php?<?php echo h(http_build_query(['q' => $q, 'page' => $page - 1])); ?>">上一页</a>
                <?php endif; ?>
                <?php if ($page < $totalPages): ?>
                    <a href="tags.php?<?php echo h(http_build_query(['q' => $q, 'page' => $page + 1])); ?>">下一页</a>
                <?php endif; ?>
            </div>
        </div>
    </div>
</body>
</html>
