<?php

require_once __DIR__ . '/common.php';

admin_require_login();

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

$errors = [];





if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!admin_csrf_check($_POST['csrf_token'] ?? null)) {
        $errors[] = '请求已失效（CSRF 校验失败），请刷新页面后重试。';
    }

    $action      = $_POST['action'] ?? '';
    $name        = trim((string)($_POST['name'] ?? ''));
    $slug        = trim((string)($_POST['slug'] ?? ''));
    $description = trim((string)($_POST['description'] ?? ''));
    $sortOrder   = (int)($_POST['sort_order'] ?? 0);
    $id          = (int)($_POST['id'] ?? 0);

    if (!$errors) {
        try {
            if ($action === 'update_home') {
                $homeName = trim((string)($_POST['home_category_name'] ?? ''));
                if ($homeName === '') {
                    $errors[] = '主页分类名称不能为空。';
                } else {
                    $stmt = $pdo->prepare("
                    INSERT INTO settings (key, value) VALUES ('site.home_category_name', :value)
                    ON CONFLICT(key) DO UPDATE SET value = excluded.value
                ");
                    $stmt->execute([':value' => $homeName]);
                    $homeCategoryName = $homeName;
                }
            } elseif ($action === 'create' && $name !== '') {
                $stmt = $pdo->prepare("
                INSERT INTO categories (name, slug, description, sort_order, created_at, updated_at)
                VALUES (:name, :slug, :description, :sort_order, :t, :t)
            ");
                $stmt->execute([
                ':name'        => $name,
                ':slug'        => $slug !== '' ? $slug : null,
                ':description' => $description,
                ':sort_order'  => $sortOrder,
                ':t'           => time(),
                ]);
            } elseif ($action === 'update' && $id > 0) {
                $iconPath    = null;
                $deleteIcon  = isset($_POST['delete_icon']) && $_POST['delete_icon'] === '1';
                $currentIcon = trim((string)($_POST['current_icon'] ?? ''));

            
            if (!$deleteIcon && isset($_FILES['icon']) && is_array($_FILES['icon']) && $_FILES['icon']['error'] !== UPLOAD_ERR_NO_FILE) {
                $file = $_FILES['icon'];
                if ($file['error'] !== UPLOAD_ERR_OK) {
                    $errors[] = '分类图标上传失败（错误代码：' . $file['error'] . '）。';
                } else {
                    if ($file['size'] > 512 * 1024) {
                        $errors[] = '分类图标大小不能超过 512KB。';
                    } else {
                        $ext        = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
                        $allowedExt = ['jpg', 'jpeg', 'png', 'gif'];
                        if (!in_array($ext, $allowedExt, true)) {
                            $errors[] = '仅支持 JPG / PNG / GIF 格式的小图标。';
                        } else {
                            $tmpPath = $file['tmp_name'];
                            $mimeOk  = false;

                            if (function_exists('finfo_open')) {
                                $finfo = finfo_open(FILEINFO_MIME_TYPE);
                                if ($finfo) {
                                    $mime = finfo_file($finfo, $tmpPath);
                                    finfo_close($finfo);
                                    if (in_array($mime, ['image/jpeg', 'image/png', 'image/gif'], true)) {
                                        $mimeOk = true;
                                    }
                                }
                            }

                            if (!$mimeOk) {
                                $info = @getimagesize($tmpPath);
                                if ($info && in_array($info[2], [IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF], true)) {
                                    $mimeOk = true;
                                }
                            }

                            if (!$mimeOk) {
                                $errors[] = '上传的文件不是有效的图片。';
                            } else {
                                $dir = BASE_PATH . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'article_icons';
                                if (!is_dir($dir)) {
                                    @mkdir($dir, 0777, true);
                                }
                                $filename = 'cat' . $id . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
                                $target   = $dir . DIRECTORY_SEPARATOR . $filename;
                                if (!@move_uploaded_file($file['tmp_name'], $target)) {
                                    $errors[] = '移动分类图标文件失败。';
                                } else {
                                    $iconPath = 'uploads/article_icons/' . $filename;
                                    
                                    if ($currentIcon !== '' && strpos($currentIcon, 'uploads/article_icons/') === 0) {
                                        $old = BASE_PATH . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $currentIcon);
                                        if (is_file($old)) {
                                            @unlink($old);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            } elseif ($deleteIcon && $currentIcon !== '') {
                if (strpos($currentIcon, 'uploads/article_icons/') === 0) {
                    $old = BASE_PATH . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $currentIcon);
                    if (is_file($old)) {
                        @unlink($old);
                    }
                }
                $iconPath = '';
            }

            if (!$errors) {
                if ($iconPath === null) {
                    $stmt = $pdo->prepare("
                        UPDATE categories
                        SET name = :name,
                            slug = :slug,
                            description = :description,
                            sort_order = :sort_order,
                            updated_at = :t
                        WHERE id = :id
                    ");
                    $stmt->execute([
                        ':name'        => $name,
                        ':slug'        => $slug !== '' ? $slug : null,
                        ':description' => $description,
                        ':sort_order'  => $sortOrder,
                        ':t'           => time(),
                        ':id'          => $id,
                    ]);
                } else {
                    $stmt = $pdo->prepare("
                        UPDATE categories
                        SET name = :name,
                            slug = :slug,
                            description = :description,
                            sort_order = :sort_order,
                            icon_path  = :icon_path,
                            updated_at = :t
                        WHERE id = :id
                    ");
                    $stmt->execute([
                        ':name'        => $name,
                        ':slug'        => $slug !== '' ? $slug : null,
                        ':description' => $description,
                        ':sort_order'  => $sortOrder,
                        ':icon_path'   => $iconPath,
                        ':t'           => time(),
                        ':id'          => $id,
                    ]);
                }
            }
            } elseif ($action === 'delete' && $id > 0) {
                $stmt = $pdo->prepare("DELETE FROM categories WHERE id = :id");
                $stmt->execute([':id' => $id]);
            }
        } catch (Throwable $e) {
            $errors[] = '操作失败：' . $e->getMessage();
        }
    }
}


$categories = [];
try {
    $stmt = $pdo->query("
        SELECT id, name, slug, description, sort_order, icon_path
        FROM categories
        ORDER BY sort_order DESC, id ASC
    ");
    $categories = $stmt->fetchAll() ?: [];
} catch (Throwable $e) {
    $categories = [];
    $errors[]   = '无法读取分类列表（可能尚未初始化数据库）。';
}

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

        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;
        }

        .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;
        }

        .errors {
            background: #7f1d1d;
            border: 1px solid #fecaca;
            color: #fee2e2;
            padding: 6px 8px;
            border-radius: 4px;
            font-size: 12px;
            margin-bottom: 10px;
        }

        .icon-preview {
            width: 24px;
            height: 24px;
            border-radius: 4px;
            background: #111827;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
        }

        .icon-preview img {
            max-width: 100%;
            max-height: 100%;
            display: block;
        }
    </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">日志</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="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="分类名称" required>
                    <input type="text" name="slug" placeholder="别名（可选）">
                    <input type="number" name="sort_order" placeholder="排序" value="0">
                </div>
                <div class="form-row">
                    <input type="text" name="description" style="flex:1;" placeholder="描述（可选）">
                </div>
                <button type="submit" class="btn">添加分类</button>
            </form>
        </div>

        <div class="card">
            <div class="card-title">分类列表（可编辑 + 小图标上传）</div>
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>图标</th>
                        <th>名称</th>
                        <th>别名</th>
                        <th>描述</th>
                        <th>排序</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td colspan="7">
                            <form method="post" style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;">
                                <input type="hidden" name="csrf_token" value="<?php echo h(admin_csrf_token()); ?>">
                                <input type="hidden" name="action" value="update_home">
                                <span class="small-text">系统分类</span>
                                <span class="icon-preview" style="width:20px;height:20px;">
                                    <span style="font-size:13px;line-height:1;">&#x1F3E0;</span>
                                </span>
                                <strong>主页分类</strong>
                                <input type="text" name="home_category_name" value="<?php echo h($homeCategoryName); ?>" style="width:160px;">
                                <button type="submit" class="btn">保存</button>
                                <span class="small-text">固定项，可改名，不可删除。</span>
                            </form>
                        </td>
                    </tr>
                    <?php if ($categories): ?>
                        <?php foreach ($categories as $cat): ?>
                            <?php $cid = (int)$cat['id']; ?>
                            <tr>
                                <td><?php echo $cid; ?></td>
                                <td>
                                    <div class="icon-preview">
                                        <?php if (!empty($cat['icon_path'])): ?>
                                            <img src="../<?php echo h($cat['icon_path']); ?>" alt="icon">
                                        <?php else: ?>
                                            <span style="font-size:11px;color:#6b7280;">无</span>
                                        <?php endif; ?>
                                    </div>
                                </td>
                                <td>
                                    <form method="post" enctype="multipart/form-data" id="cat-form-<?php echo $cid; ?>">
                                        <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 $cid; ?>">
                                        <input type="hidden" name="current_icon" value="<?php echo h($cat['icon_path']); ?>">
                                        <input type="text" name="name" value="<?php echo h($cat['name']); ?>" style="width:120px;">
                                </td>
                                <td>
                                        <input type="text" name="slug" value="<?php echo h($cat['slug']); ?>" style="width:100px;">
                                </td>
                                <td>
                                        <input type="text" name="description" value="<?php echo h($cat['description']); ?>" style="width:180px;">
                                </td>
                                <td>
                                        <input type="number" name="sort_order" value="<?php echo (int)$cat['sort_order']; ?>" style="width:60px;">
                                </td>
                                <td>
                                        <div style="margin-bottom:4px;">
                                            <input type="file" name="icon" accept="image/*" style="max-width:210px;">
                                        </div>
                                        <div style="margin-bottom:4px;">
                                            <label style="font-size:12px;color:#9ca3af;">
                                                <input type="checkbox" name="delete_icon" value="1"> 删除图标
                                            </label>
                                        </div>
                                        <button type="submit" class="btn">保存</button>
                                    </form>
                                    <form method="post" style="display:inline;margin-left:4px;">
                                        <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 $cid; ?>">
                                        <button type="submit" class="btn" onclick="return confirm('确定删除该分类？')">删除</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="7" class="small-text">暂无普通分类记录。</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</body>
</html>
