<?php
require_once 'config.php';

// 定义状态常量
define('STATUS_PENDING', 0); // 待审核
define('STATUS_APPROVED', 1); // 已通过
define('STATUS_REJECTED', 2); // 已拒绝
define('STATUS_RECYCLE', 3);  // 回收站

// 获取分类
$categories = mysqli_query($conn, "SELECT * FROM categories ORDER BY sort_order, name");
$categories_array = [];
if ($categories) while ($c = mysqli_fetch_assoc($categories)) $categories_array[] = $c;

// 获取编辑对象
$edit_app = null;
if (isset($_GET['edit'])) {
    $id = (int)$_GET['edit'];
    $res = mysqli_query($conn, "SELECT a.*, u.username, u.id as uid FROM apps a LEFT JOIN users u ON a.user_id = u.id WHERE a.id = $id");
    if($res) $edit_app = mysqli_fetch_assoc($res);
}

// --- 处理各种操作 ---

// 1. 批量通过
if (isset($_POST['batch_approve'])) {
    if (!empty($_POST['ids'])) {
        foreach ($_POST['ids'] as $id) {
            $id = (int)$id;
            $max_res = mysqli_query($conn, "SELECT MAX(sort_order) as mo FROM apps");
            $next_order = (mysqli_fetch_assoc($max_res)['mo'] ?? 0) + 1;
            mysqli_query($conn, "UPDATE apps SET status = " . STATUS_APPROVED . ", sort_order = $next_order, reject_reason = NULL WHERE id = $id");
        }
        echo "<script>alert('批量通过成功'); location.href='sh.php?tab=0';</script>";
    }
}

// 2. 批量拒绝
if (isset($_POST['batch_reject'])) {
    $reason = mysqli_real_escape_string($conn, $_POST['reject_reason_common'] ?? '内容不符合规范');
    if (!empty($_POST['ids'])) {
        foreach ($_POST['ids'] as $id) {
            mysqli_query($conn, "UPDATE apps SET status = " . STATUS_REJECTED . ", reject_reason = '$reason' WHERE id = " . (int)$id);
        }
        echo "<script>alert('批量拒绝成功'); location.href='sh.php?tab=0';</script>";
    }
}

// 3. 批量重审/批量恢复
if (isset($_POST['batch_retrial'])) {
    $target_status = STATUS_PENDING;
    if(isset($_POST['from_recycle'])) $target_status = STATUS_APPROVED;
    
    if (!empty($_POST['ids'])) {
        foreach ($_POST['ids'] as $id) {
            mysqli_query($conn, "UPDATE apps SET status = $target_status WHERE id = " . (int)$id);
        }
        $msg = isset($_POST['from_recycle']) ? '批量恢复成功' : '批量重审成功';
        $redirect_tab = isset($_POST['from_recycle']) ? 3 : 0;
        echo "<script>alert('$msg'); location.href='sh.php?tab=$redirect_tab';</script>";
    }
}

// 4. 批量移至回收站
if (isset($_POST['batch_delete'])) {
    if (!empty($_POST['ids'])) {
        foreach ($_POST['ids'] as $id) {
            mysqli_query($conn, "UPDATE apps SET status = " . STATUS_RECYCLE . " WHERE id = " . (int)$id);
        }
        echo "<script>alert('已移至回收站'); location.href='sh.php?tab=all';</script>";
    }
}

// 5. 单个操作
if (isset($_GET['action'])) {
    $id = (int)$_GET['id'];
    $action = $_GET['action'];
    $redirect_tab = isset($_GET['tab']) ? $_GET['tab'] : 'all';
    
    switch ($action) {
        case 'approve':
            $max_res = mysqli_query($conn, "SELECT MAX(sort_order) as mo FROM apps");
            $next_order = (mysqli_fetch_assoc($max_res)['mo'] ?? 0) + 1;
            mysqli_query($conn, "UPDATE apps SET status = " . STATUS_APPROVED . ", sort_order = $next_order, reject_reason = NULL WHERE id = $id");
            break;
        case 'reject':
            $reason = isset($_GET['reason']) ? mysqli_real_escape_string($conn, $_GET['reason']) : '内容不符合规范';
            mysqli_query($conn, "UPDATE apps SET status = " . STATUS_REJECTED . ", reject_reason = '$reason' WHERE id = $id");
            break;
        case 'retrial':
            mysqli_query($conn, "UPDATE apps SET status = " . STATUS_PENDING . " WHERE id = $id");
            break;
        case 'delete':
            mysqli_query($conn, "UPDATE apps SET status = " . STATUS_RECYCLE . " WHERE id = $id");
            break;
        case 'restore':
            mysqli_query($conn, "UPDATE apps SET status = " . STATUS_APPROVED . " WHERE id = $id");
            break;
    }
    header("Location: sh.php?tab=$redirect_tab");
    exit;
}

// 6. 置顶开关
if (isset($_GET['toggle_sticky'])) {
    $id = (int)$_GET['toggle_sticky'];
    $current = mysqli_query($conn, "SELECT is_sticky FROM apps WHERE id = $id");
    if ($current && $row = mysqli_fetch_assoc($current)) {
        $new_sticky = $row['is_sticky'] ? 0 : 1;
        $sticky_time = $new_sticky ? date('Y-m-d H:i:s') : 'NULL';
        mysqli_query($conn, "UPDATE apps SET is_sticky = $new_sticky, sticky_time = " . ($new_sticky ? "'$sticky_time'" : "NULL") . " WHERE id = $id");
    }
    header("Location: sh.php?tab=all");
    exit;
}

// 7. 保存排序
if (isset($_POST['save_app_order'])) {
    foreach($_POST['app_order'] as $id => $new_order) {
        $id = (int)$id; $new_order = (int)$new_order;
        mysqli_query($conn, "UPDATE apps SET sort_order = $new_order WHERE id = $id");
    }
    echo "<script>alert('排序已保存，请切回默认排序查看效果'); location.href='sh.php?tab=all';</script>";
    exit;
}

// 8. 编辑保存
if (isset($_POST['edit_save'])) {
    $id = (int)$_POST['id'];
    $name = mysqli_real_escape_string($conn, $_POST['name']);
    $download_url = mysqli_real_escape_string($conn, $_POST['download_url']);
    $category = mysqli_real_escape_string($conn, $_POST['category']);
    $coin_price = (int)$_POST['coin_price'];
    $disk_code = mysqli_real_escape_string($conn, $_POST['disk_code']);
    
    $is_official = isset($_POST['is_official']) ? 1 : 0;
    $download_count = (int)($_POST['download_count'] ?? 0);
    $download_people = (int)($_POST['download_people'] ?? 0);
    $virtual_downloads = (int)($_POST['virtual_downloads'] ?? 0);
    
    $sql = "UPDATE apps SET name='$name', download_url='$download_url', category='$category', coin_price='$coin_price', disk_code='$disk_code', is_official='$is_official', download_count='$download_count', download_people='$download_people', virtual_downloads='$virtual_downloads' WHERE id = $id";
    
    if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
        $upload_dir = "uploads/";
        if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
        $pic_name = uniqid() . "_" . basename($_FILES['image']['name']);
        $dst = $upload_dir . $pic_name;
        if (move_uploaded_file($_FILES['image']['tmp_name'], $dst)) {
            $old = mysqli_query($conn, "SELECT image FROM apps WHERE id = $id");
            if ($old && $old_row = mysqli_fetch_assoc($old)) {
                if (file_exists($old_row['image'])) unlink($old_row['image']);
            }
            $sql .= ", image='$dst'";
        }
    }
    mysqli_query($conn, $sql);
    header("Location: sh.php?tab=" . $_POST['current_tab']);
    exit;
}

// 获取当前标签
$current_tab = isset($_GET['tab']) ? $_GET['tab'] : 'all';

// 获取排序参数
$order_by = isset($_GET['sort']) ? $_GET['sort'] : 'default';
$order_dir = isset($_GET['dir']) ? $_GET['dir'] : 'ASC';

// 构建排序SQL
$order_sql = "a.is_sticky DESC, a.sort_order ASC, a.id DESC"; // 默认排序

if ($current_tab == 'all') {
    switch ($order_by) {
        case 'time':
            $order_sql = "a.created_at " . ($order_dir == 'ASC' ? 'ASC' : 'DESC');
            break;
        case 'click':
            $order_sql = "a.download_count " . ($order_dir == 'ASC' ? 'ASC' : 'DESC');
            break;
        case 'people':
            $order_sql = "a.download_people " . ($order_dir == 'ASC' ? 'ASC' : 'DESC');
            break;
        case 'virtual':
            $order_sql = "(a.download_count + a.virtual_downloads) " . ($order_dir == 'ASC' ? 'ASC' : 'DESC');
            break;
    }
}

// 获取列表数据
$where = "";
if($current_tab === 'all') {
    $where = "WHERE a.status != " . STATUS_RECYCLE;
} else {
    $tab_int = (int)$current_tab;
    $where = "WHERE a.status = $tab_int";
}

$apps = mysqli_query($conn, "SELECT a.*, u.username FROM apps a LEFT JOIN users u ON a.user_id = u.id $where ORDER BY $order_sql");

// 统计数量
$counts = [
    'all' => mysqli_num_rows(mysqli_query($conn, "SELECT id FROM apps WHERE status != " . STATUS_RECYCLE)),
    0 => mysqli_num_rows(mysqli_query($conn, "SELECT id FROM apps WHERE status=0")),
    1 => mysqli_num_rows(mysqli_query($conn, "SELECT id FROM apps WHERE status=1")),
    2 => mysqli_num_rows(mysqli_query($conn, "SELECT id FROM apps WHERE status=2")),
    3 => mysqli_num_rows(mysqli_query($conn, "SELECT id FROM apps WHERE status=3"))
];
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>投稿审核 - WC软件</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { background: #f0f2f5; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; padding: 20px; font-size: 14px; }
        .container { max-width: 1400px; margin: 0 auto; }
        
        .tabs { display: flex; gap: 10px; margin-bottom: 20px; flex-wrap: wrap; }
        .tab-btn { padding: 10px 20px; background: #fff; border: none; border-radius: 8px; cursor: pointer; font-size: 15px; text-decoration: none; color: #333; display: flex; align-items: center; gap: 5px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); }
        .tab-btn.active { background: #007bff; color: white; }
        .tab-btn .badge { background: rgba(0,0,0,0.1); padding: 2px 6px; border-radius: 10px; font-size: 12px; }
        .tab-btn.active .badge { background: rgba(255,255,255,0.2); }
        .tab-btn.recycle { background: #dc3545; color: white; }
        
        /* 排序工具栏样式 */
        .sort-toolbar { display: flex; gap: 10px; margin-bottom: 15px; align-items: center; flex-wrap: wrap; }
        .sort-btn { padding: 5px 12px; background: #e9ecef; border-radius: 15px; font-size: 13px; color: #495057; text-decoration: none; transition: all 0.2s; }
        .sort-btn:hover { background: #dee2e6; }
        .sort-btn.active { background: #007bff; color: white; }
        .sort-btn-desc.active { background: #dc3545; color: white; }
        
        .card { background: #fff; border-radius: 12px; padding: 20px; margin-bottom: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); }
        
        .form-group { margin-bottom: 15px; }
        .form-group label { display: block; font-size: 13px; color: #666; margin-bottom: 5px; font-weight: bold; }
        input, select, textarea { width: 100%; height: 40px; border: 1px solid #ddd; border-radius: 6px; padding: 0 10px; font-size: 14px; background: #fff; }
        textarea { height: auto; padding: 10px; }
        
        .btn { padding: 6px 12px; background: #007bff; color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 13px; text-decoration: none; display: inline-block; margin: 2px; }
        .btn-danger { background: #dc3545; }
        .btn-success { background: #28a745; }
        .btn-secondary { background: #6c757d; }
        .btn-warning { background: #ffc107; color:#333; }
        .btn-info { background: #17a2b8; }
        
        /* 表格样式 */
        .app-table { width: 100%; border-collapse: collapse; margin-top: 15px; }
        .app-table th { text-align: left; padding: 12px 8px; background: #f8f9fa; border-bottom: 2px solid #eee; white-space: nowrap; position: sticky; top: 0; }
        .app-table td { padding: 12px 8px; border-bottom: 1px solid #eee; vertical-align: middle; }
        .app-table img { width: 50px; height: 50px; border-radius: 6px; object-fit: cover; border:1px solid #eee; }
        
        .checkbox-cell { width: 40px; }
        .info-tag { display: inline-block; padding: 2px 6px; border-radius: 4px; font-size: 12px; margin-right: 3px; margin-bottom: 2px; }
        .tag-price { background: #fff3cd; color: #856404; border: 1px solid #ffeeba; }
        .tag-code { background: #e2e3e5; color: #383d41; border: 1px solid #d6d8db; }
        .tag-disk { background: #d1ecf1; color: #0c5460; border: 1px solid #bee5eb; }
        .tag-official { background: #9c27b0; color: white; border: 1px solid #7b1fa2; font-weight: bold; }
        
        .edit-form { border: 2px solid #007bff; border-radius: 12px; padding: 20px; margin-bottom: 20px; background: #f8faff; }
        .edit-grid { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 15px; }
        .btn-group { margin-top: 15px; display: flex; gap: 10px; flex-wrap: wrap; }
        
        .reject-box { margin-top: 10px; display: none; background: #fff0f0; padding: 10px; border-radius: 6px; border: 1px solid #ffcccc; }
        .reject-box input { background: #fff; }
        
        .checkbox-label { display: flex; align-items: center; gap: 8px; cursor: pointer; font-size: 14px; color: #333; height: 40px; }
        .checkbox-label input { width: 18px; height: 18px; margin: 0; }
        
        /* 统计数据输入框 */
        .stat-input { width: 70px; height: 30px; text-align: center; font-size: 13px; border: 1px solid #ddd; border-radius: 4px; }
        
        /* 排序输入框 */
        .order-input { width: 60px; height: 30px; text-align: center; font-size: 13px; border: 1px solid #ccc; border-radius: 4px; }
        
        /* 自然序号样式 */
        .natural-index { font-weight: bold; color: #333; font-size: 14px; }

        .sticky-badge { background: #ff4444; color: white; padding: 2px 8px; border-radius: 12px; font-size: 11px; margin-left: 5px; white-space: nowrap; }

        @media (max-width: 768px) {
            .edit-grid { grid-template-columns: 1fr; }
            .app-table { display: block; overflow-x: auto; }
        }
    </style>
</head>
<body>
<div class="container">
    <h1 style="margin-bottom: 20px; font-size: 24px;">投稿审核中心</h1>

    <div class="tabs">
        <a href="?tab=all" class="tab-btn <?= $current_tab == 'all' ? 'active' : '' ?>">全部 <span class="badge"><?= $counts['all'] ?></span></a>
        <a href="?tab=0" class="tab-btn <?= $current_tab == 0 ? 'active' : '' ?>">待审核 <span class="badge"><?= $counts[0] ?></span></a>
        <a href="?tab=1" class="tab-btn <?= $current_tab == 1 ? 'active' : '' ?>">已通过 <span class="badge"><?= $counts[1] ?></span></a>
        <a href="?tab=2" class="tab-btn <?= $current_tab == 2 ? 'active' : '' ?>">已拒绝 <span class="badge"><?= $counts[2] ?></span></a>
        <a href="?tab=3" class="tab-btn recycle <?= $current_tab == 3 ? 'active' : '' ?>" style="<?= $current_tab == 3 ? '' : 'background:#fff; color:#dc3545;' ?>">回收站 <span class="badge"><?= $counts[3] ?></span></a>
        <a href="admin.php" class="tab-btn" style="background: #17a2b8; color: white;">返回添加</a>
    </div>
    
    <!-- 编辑表单 -->
    <?php if($edit_app): ?>
    <div class="edit-form">
        <h3 style="margin-bottom: 15px;">正在编辑: <?= htmlspecialchars($edit_app['name']) ?></h3>
        <div style="background:#e9ecef; padding:8px; border-radius:4px; margin-bottom:15px; font-size:13px;">
            投稿者：<?= htmlspecialchars($edit_app['username'] ?? '无') ?> (ID: <?= $edit_app['user_id'] ?? 0 ?>) | 
            投稿时间：<?= $edit_app['created_at'] ?>
        </div>
        <form method="post" enctype="multipart/form-data">
            <input type="hidden" name="id" value="<?= $edit_app['id'] ?>">
            <input type="hidden" name="current_tab" value="<?= $current_tab ?>">
            
            <div class="edit-grid">
                <div class="form-group">
                    <label>软件名称</label>
                    <input type="text" name="name" value="<?= htmlspecialchars($edit_app['name']) ?>" required>
                </div>
                <div class="form-group">
                    <label>所属分类</label>
                    <select name="category" required>
                        <?php foreach($categories_array as $cat): ?>
                        <option value="<?= htmlspecialchars($cat['name']) ?>" <?= $edit_app['category'] == $cat['name'] ? 'selected' : '' ?>><?= htmlspecialchars($cat['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>下载价格 (小马币)</label>
                    <input type="number" name="coin_price" value="<?= $edit_app['coin_price'] ?>" min="0">
                </div>
            </div>
            
            <div class="form-group">
                <label>下载链接</label>
                <input type="url" name="download_url" value="<?= htmlspecialchars($edit_app['download_url']) ?>" required>
            </div>
            
            <div class="edit-grid">
                 <div class="form-group">
                    <label>提取码</label>
                    <input type="text" name="disk_code" value="<?= htmlspecialchars($edit_app['disk_code']) ?>" placeholder="无则留空">
                </div>
                <div class="form-group">
                    <label>网盘类型 (自动识别)</label>
                    <input type="text" value="<?= htmlspecialchars($edit_app['disk_type']) ?>" disabled style="background:#eee;">
                </div>
                <div class="form-group">
                    <label>特殊属性</label>
                    <label class="checkbox-label">
                        <input type="checkbox" name="is_official" value="1" <?= ($edit_app['is_official'] ?? 0) ? 'checked' : '' ?>>
                        <span>设为官方应用 (显示紫色官方标签)</span>
                    </label>
                </div>
            </div>
            
            <!-- 数据统计修改区 -->
            <div style="background:#f8f9fa; padding:15px; border-radius:8px; margin-bottom:15px;">
                <div style="display:flex; gap:20px; flex-wrap:wrap;">
                    <div style="text-align:center;">
                        <div style="font-size:12px; color:#666; margin-bottom:5px;">点击次数</div>
                        <input type="number" name="download_count" value="<?= $edit_app['download_count'] ?>" class="stat-input">
                    </div>
                    <div style="text-align:center;">
                        <div style="font-size:12px; color:#666; margin-bottom:5px;">下载人数</div>
                        <input type="number" name="download_people" value="<?= $edit_app['download_people'] ?>" class="stat-input">
                    </div>
                    <div style="text-align:center;">
                        <div style="font-size:12px; color:#666; margin-bottom:5px;">虚拟下载</div>
                        <input type="number" name="virtual_downloads" value="<?= $edit_app['virtual_downloads'] ?>" class="stat-input">
                    </div>
                </div>
            </div>
            
            <div class="form-group">
                <label>软件图标 (不选则不修改)</label>
                <input type="file" name="image" accept="image/*">
            </div>
            
            <div class="btn-group">
                <button type="submit" name="edit_save" class="btn btn-success">保存修改</button>
                <a href="sh.php?tab=<?= $current_tab ?>" class="btn btn-secondary">取消编辑</a>
            </div>
        </form>
    </div>
    <?php endif; ?>

    <!-- 列表 -->
    <div class="card">
        <form method="post" id="listForm">
            <!-- 批量操作区 -->
            <div style="margin-bottom: 15px; display: flex; gap: 10px; align-items: center; flex-wrap: wrap;">
                <!-- 这里修复了全选按钮的 ID 和事件 -->
                <input type="checkbox" id="selectAllBtn" onclick="toggleAll(this)" style="width:18px; height:18px;"> <label for="selectAllBtn" style="font-size:14px; cursor:pointer;">全选</label>
                
                <?php if($current_tab == 0): ?>
                    <button type="submit" name="batch_approve" class="btn btn-success">批量通过</button>
                    <button type="button" class="btn btn-danger" onclick="toggleRejectBox()">批量拒绝</button>
                    <div id="rejectBox" class="reject-box" style="width:100%; display:none;">
                        <div style="display:flex; gap:10px; align-items:center;">
                            <span style="white-space:nowrap; font-weight:bold;">拒绝原因：</span>
                            <input type="text" name="reject_reason_common" placeholder="请输入拒绝原因" style="flex:1;">
                            <button type="submit" name="batch_reject" class="btn btn-danger">确认拒绝</button>
                        </div>
                    </div>
                    
                <?php elseif($current_tab == 1 || $current_tab == 2): ?>
                    <button type="submit" name="batch_retrial" class="btn btn-warning">批量重审</button>
                
                <?php elseif($current_tab == 'all'): ?>
                    <button type="submit" name="batch_delete" class="btn btn-danger">批量删除</button>
                    <button type="submit" name="save_app_order" class="btn btn-success" onclick="return confirm('确定保存排序吗？仅对默认排序下的手动修改有效。')">保存排序</button>
                    
                    <!-- 排序工具栏 -->
                    <div class="sort-toolbar" style="margin-left: auto;">
                        <span style="font-size:12px; color:#666;">排序:</span>
                        <a href="?tab=all&sort=time&dir=ASC" class="sort-btn <?= ($order_by=='time' && $order_dir=='ASC') ? 'active' : '' ?>">时间 ↑</a>
                        <a href="?tab=all&sort=time&dir=DESC" class="sort-btn sort-btn-desc <?= ($order_by=='time' && $order_dir=='DESC') ? 'active' : '' ?>">时间 ↓</a>
                        
                        <a href="?tab=all&sort=click&dir=DESC" class="sort-btn <?= ($order_by=='click') ? 'active' : '' ?>">点击量</a>
                        <a href="?tab=all&sort=people&dir=DESC" class="sort-btn <?= ($order_by=='people') ? 'active' : '' ?>">下载人数</a>
                        
                        <a href="?tab=all&sort=virtual&dir=DESC" class="sort-btn <?= ($order_by=='virtual') ? 'active' : '' ?>">虚拟数据</a>
                        
                        <?php if($order_by != 'default'): ?>
                        <a href="?tab=all" class="sort-btn">重置排序</a>
                        <?php endif; ?>
                    </div>
                
                <?php elseif($current_tab == 3): ?>
                    <input type="hidden" name="from_recycle" value="1">
                    <button type="submit" name="batch_retrial" class="btn btn-success">批量恢复</button>
                <?php endif; ?>
            </div>
            
            <?php if($apps && mysqli_num_rows($apps) > 0): ?>
            <div style="overflow-x:auto;">
            <table class="app-table">
                <thead>
                    <tr>
                        <th style="width:70px;">序号</th>
                        <th>图标</th>
                        <th>名称</th>
                        <th>投稿者</th>
                        <th>详情</th>
                        <?php if($current_tab == 'all'): ?>
                        <th>状态</th>
                        <th>下载统计</th>
                        <?php endif; ?>
                        <th>时间</th>
                        <?php if($current_tab == 2): ?><th>拒绝原因</th><?php endif; ?>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    // 初始化自然序号计数器
                    $row_index = 1; 
                    while($a = mysqli_fetch_assoc($apps)): 
                    ?>
                    <tr style="<?= $a['is_sticky'] ? 'background: #fff3f3;' : '' ?>">
                        <td>
                            <?php if($current_tab == 'all' && $order_by == 'default'): ?>
                                <!-- 只有在默认排序下才能修改序号 -->
                                <input type="number" name="app_order[<?= $a['id'] ?>]" value="<?= $a['sort_order'] ?>" class="order-input">
                            <?php else: ?>
                                <!-- 其他排序下显示固定的自然序号 1, 2, 3... -->
                                <span class="natural-index"><?= $row_index ?></span>
                            <?php endif; ?>
                        </td>
                        
                        <td>
                            <!-- 【关键修复】这里添加了 name="ids[]" 和 value，这样全选才能生效 -->
                            <input type="checkbox" name="ids[]" value="<?= $a['id'] ?>" style="width:18px; height:18px;">
                        </td>
                        
                        <td><img src="<?= htmlspecialchars($a['image']) ?>" onerror="this.src='https://via.placeholder.com/50'"></td>
                        <td>
                            <div style="font-weight:bold; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; max-width:150px;" title="<?= htmlspecialchars($a['name']) ?>">
                                <?= htmlspecialchars($a['name']) ?>
                                <?php if($a['is_sticky']): ?><span class="sticky-badge">置顶</span><?php endif; ?>
                            </div>
                            <div style="font-size:12px; color:#666; margin-top:2px;"><?= htmlspecialchars($a['category']) ?></div>
                        </td>
                        <td>
                            <div><?= htmlspecialchars($a['username']) ?></div>
                            <div style="font-size:12px; color:#999;">ID: <?= $a['user_id'] ?></div>
                        </td>
                        <td>
                            <?php if($a['is_official'] ?? 0): ?>
                            <span class="info-tag tag-official">官方</span>
                            <?php endif; ?>
                            <span class="info-tag tag-price">💰 <?= $a['coin_price'] ?>币</span>
                            <span class="info-tag tag-disk">💾 <?= htmlspecialchars($a['disk_type']) ?></span>
                            <?php if(!empty($a['disk_code'])): ?>
                            <span class="info-tag tag-code">🔑 <?= htmlspecialchars($a['disk_code']) ?></span>
                            <?php endif; ?>
                        </td>
                        
                        <?php if($current_tab == 'all'): ?>
                        <td>
                             <a href="?toggle_sticky=<?= $a['id'] ?>&tab=all" class="btn <?= $a['is_sticky'] ? 'btn-danger' : 'btn-secondary' ?>" style="padding: 4px 8px; font-size: 11px;">
                                <?= $a['is_sticky'] ? '取消置顶' : '置顶' ?>
                            </a>
                        </td>
                        <td style="font-size:12px; line-height:1.6;">
                            点击: <strong style="color:#28a745;"><?= intval($a['download_count']) ?></strong><br>
                            人数: <strong style="color:#17a2b8;"><?= intval($a['download_people']) ?></strong><br>
                            虚拟: <strong style="color:#ffc107;"><?= intval($a['virtual_downloads']) ?></strong>
                        </td>
                        <?php endif; ?>
                        
                        <td style="font-size:12px; color:#666;"><?= date('m-d H:i', strtotime($a['created_at'])) ?></td>
                        
                        <?php if($current_tab == 2): ?>
                        <td style="color:#dc3545; font-size:12px; max-width:100px; word-break:break-all;"><?= htmlspecialchars($a['reject_reason']) ?></td>
                        <?php endif; ?>
                        
                        <td style="min-width: 100px;">
                            <?php if($current_tab == 0): ?>
                                <a href="?action=approve&id=<?= $a['id'] ?>&tab=0" class="btn btn-success" onclick="return confirm('确认通过?')">通过</a>
                                <a href="javascript:void(0)" onclick="rejectSingle(<?= $a['id'] ?>)" class="btn btn-danger">拒绝</a>
                            <?php elseif($current_tab == 1 || $current_tab == 2): ?>
                                <a href="?action=retrial&id=<?= $a['id'] ?>&tab=<?= $current_tab ?>" class="btn btn-warning">重审</a>
                            <?php elseif($current_tab == 3): ?>
                                <a href="?action=restore&id=<?= $a['id'] ?>&tab=3" class="btn btn-success">恢复</a>
                            <?php elseif($current_tab == 'all'): ?>
                                <a href="?action=delete&id=<?= $a['id'] ?>&tab=all" class="btn btn-danger" onclick="return confirm('确定移至回收站?')">删除</a>
                            <?php endif; ?>
                            
                            <a href="?edit=<?= $a['id'] ?>&tab=<?= $current_tab ?>" class="btn btn-info">编辑</a>
                        </td>
                    </tr>
                    <?php 
                    // 循环结束，序号+1
                    $row_index++; 
                    endwhile; 
                    ?>
                </tbody>
            </table>
            </div>
            <?php else: ?>
            <p style="color: #999; text-align: center; padding: 40px;">暂无数据</p>
            <?php endif; ?>
        </form>
    </div>
</div>

<script>
    // 【关键修复】重写了全选函数，确保能找到所有 name="ids[]" 的复选框
    function toggleAll(source) {
        var checkboxes = document.querySelectorAll('input[name="ids[]"]');
        for(var i=0; i<checkboxes.length; i++) {
            checkboxes[i].checked = source.checked;
        }
    }
    
    function toggleRejectBox() {
        var box = document.getElementById('rejectBox');
        box.style.display = box.style.display === 'none' ? 'block' : 'none';
    }
    
    function rejectSingle(id) {
        var reason = prompt("请输入拒绝原因：", "内容不符合规范");
        if (reason !== null) {
            window.location.href = '?action=reject&id=' + id + '&tab=0&reason=' + encodeURIComponent(reason);
        }
    }
</script>
</body>
</html>
