<?php
ob_start();
requireAdmin();

$page = isset($_GET['p']) ? intval($_GET['p']) : 1;
$perpage = 20;
$status = isset($_GET['status']) ? $_GET['status'] : 'pending';

$where = "ap.status = '$status'";
$total_result = $db->query("SELECT COUNT(*) as cnt FROM agent_products ap WHERE $where");
$total = $total_result->fetch_assoc()['cnt'];
$offset = ($page - 1) * $perpage;

$products = $db->fetchAll("
    SELECT ap.*, u.username as agent_name 
    FROM agent_products ap
    JOIN users u ON ap.agent_id = u.id
    WHERE $where
    ORDER BY ap.id DESC
    LIMIT $offset, $perpage
");

// 统计数据
$stats = [
    'pending' => $db->fetchOne("SELECT COUNT(*) as cnt FROM agent_products WHERE status = 'pending'")['cnt'],
    'approved' => $db->fetchOne("SELECT COUNT(*) as cnt FROM agent_products WHERE status = 'approved'")['cnt'],
    'rejected' => $db->fetchOne("SELECT COUNT(*) as cnt FROM agent_products WHERE status = 'rejected'")['cnt'],
    'total' => $db->fetchOne("SELECT COUNT(*) as cnt FROM agent_products")['cnt'],
];
?>

<div class="agent-products">
    <!-- 页面头部 -->
    <div class="page-header">
        <h2>
            <img src="https://api.iconify.design/mdi:package-check.svg?color=%23667eea" width="26" height="26" style="vertical-align: middle; margin-right: 10px;" alt="">
            代理商产品审核
        </h2>
        <p class="text-muted">审核代理商提交的产品申请</p>
    </div>
    
    <!-- 统计卡片 -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon">
                <img src="https://api.iconify.design/mdi:package-variant.svg?color=%23667eea" width="28" height="28" alt="">
            </div>
            <div class="stat-content">
                <span class="stat-value" id="stat-total"><?php echo $stats['total']; ?></span>
                <span class="stat-label">总申请数</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">
                <img src="https://api.iconify.design/mdi:clock-outline.svg?color=%23f59e0b" width="28" height="28" alt="">
            </div>
            <div class="stat-content">
                <span class="stat-value" id="stat-pending"><?php echo $stats['pending']; ?></span>
                <span class="stat-label">待审核</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">
                <img src="https://api.iconify.design/mdi:check-circle.svg?color=%2310b981" width="28" height="28" alt="">
            </div>
            <div class="stat-content">
                <span class="stat-value" id="stat-approved"><?php echo $stats['approved']; ?></span>
                <span class="stat-label">已通过</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">
                <img src="https://api.iconify.design/mdi:close-circle.svg?color=%23ef4444" width="28" height="28" alt="">
            </div>
            <div class="stat-content">
                <span class="stat-value" id="stat-rejected"><?php echo $stats['rejected']; ?></span>
                <span class="stat-label">已拒绝</span>
            </div>
        </div>
    </div>
    
    <!-- 筛选栏 -->
    <div class="filter-bar">
        <div class="filter-tabs">
            <a href="?page=agent_products&status=pending" class="filter-tab <?php echo $status == 'pending' ? 'active' : ''; ?>">
                <img src="https://api.iconify.design/mdi:clock-outline.svg?color=<?php echo $status == 'pending' ? 'white' : '%23f59e0b'; ?>" width="16" height="16" alt="">
                待审核
                <span class="count"><?php echo $stats['pending']; ?></span>
            </a>
            <a href="?page=agent_products&status=approved" class="filter-tab <?php echo $status == 'approved' ? 'active' : ''; ?>">
                <img src="https://api.iconify.design/mdi:check-circle.svg?color=<?php echo $status == 'approved' ? 'white' : '%2310b981'; ?>" width="16" height="16" alt="">
                已通过
                <span class="count"><?php echo $stats['approved']; ?></span>
            </a>
            <a href="?page=agent_products&status=rejected" class="filter-tab <?php echo $status == 'rejected' ? 'active' : ''; ?>">
                <img src="https://api.iconify.design/mdi:close-circle.svg?color=<?php echo $status == 'rejected' ? 'white' : '%23ef4444'; ?>" width="16" height="16" alt="">
                已拒绝
                <span class="count"><?php echo $stats['rejected']; ?></span>
            </a>
        </div>
    </div>
    
    <!-- 产品列表 -->
    <div class="table-wrapper">
        <table class="data-table" id="productsTable">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>代理商</th>
                    <th>产品名称</th>
                    <th>价格</th>
                    <th>佣金</th>
                    <th>折扣设置</th>
                    <th>状态</th>
                    <th>提交时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($products)): ?>
                    <tr>
                        <td colspan="9">
                            <div class="empty-state">
                                <img src="https://api.iconify.design/mdi:package-variant-closed.svg?color=%239ca3af" width="48" height="48" alt="">
                                <p>暂无产品申请</p>
                            </div>
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($products as $item): ?>
                        <tr id="product-row-<?php echo $item['id']; ?>">
                            <td class="id-cell">#<?php echo $item['id']; ?></td>
                            <td>
                                <div class="user-info">
                                    <img src="https://api.iconify.design/mdi:account.svg?color=%236b7280" width="14" height="14" alt="">
                                    <?php echo htmlspecialchars($item['agent_name']); ?>
                                </div>
                            </td>
                            <td>
                                <div class="product-info">
                                    <strong><?php echo htmlspecialchars($item['name']); ?></strong>
                                    <?php if (!empty($item['description'])): ?>
                                        <span class="product-desc"><?php echo htmlspecialchars(mb_substr($item['description'], 0, 40)); ?><?php echo mb_strlen($item['description']) > 40 ? '...' : ''; ?></span>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td><span class="amount">¥<?php echo number_format($item['price'], 2); ?></span></td>
                            <td><span class="commission"><?php echo $item['commission_rate']; ?>%</span></td>
                            <td>
                                <?php if ($item['discount_enabled']): ?>
                                    <div class="discount-info">
                                        <?php if ($item['discount_type'] == 'percent'): ?>
                                            <span class="discount-badge percent">
                                                <img src="https://api.iconify.design/mdi:percent.svg?color=%238b5cf6" width="12" height="12" alt="">
                                                <?php echo $item['discount_value']; ?>% OFF
                                            </span>
                                        <?php else: ?>
                                            <span class="discount-badge fixed">
                                                <img src="https://api.iconify.design/mdi:cash.svg?color=%238b5cf6" width="12" height="12" alt="">
                                                ¥<?php echo number_format($item['discount_value'], 2); ?> OFF
                                            </span>
                                        <?php endif; ?>
                                        <?php if ($item['stack_discount']): ?>
                                            <span class="stack-badge">
                                                <img src="https://api.iconify.design/mdi:layers.svg?color=%23f59e0b" width="10" height="10" alt="">
                                                可叠加
                                            </span>
                                        <?php endif; ?>
                                    </div>
                                <?php else: ?>
                                    <span class="text-muted">-</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <span class="status-badge status-<?php echo $item['status']; ?>" id="status-badge-<?php echo $item['id']; ?>">
                                    <span class="status-dot"></span>
                                    <?php echo $item['status'] == 'pending' ? '待审核' : ($item['status'] == 'approved' ? '已通过' : '已拒绝'); ?>
                                </span>
                            </td>
                            <td><?php echo date('Y-m-d H:i', strtotime($item['created_at'])); ?></td>
                            <td class="action-buttons" id="action-buttons-<?php echo $item['id']; ?>">
                                <?php if ($item['status'] == 'pending'): ?>
                                    <button class="action-btn approve-btn" onclick="reviewProduct(<?php echo $item['id']; ?>, 'approved')" title="通过">
                                        <img src="https://api.iconify.design/mdi:check.svg?color=%2310b981" width="18" height="18" alt="">
                                    </button>
                                    <button class="action-btn reject-btn" onclick="reviewProduct(<?php echo $item['id']; ?>, 'rejected')" title="拒绝">
                                        <img src="https://api.iconify.design/mdi:close.svg?color=%23ef4444" width="18" height="18" alt="">
                                    </button>
                                <?php else: ?>
                                    <span class="disabled-action">-</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <!-- 分页 -->
    <?php if ($total > $perpage): ?>
        <div class="pagination">
            <?php if ($page > 1): ?>
                <a href="?page=agent_products&p=<?php echo $page - 1; ?>&status=<?php echo $status; ?>" class="page-link page-prev">
                    <img src="https://api.iconify.design/mdi:chevron-left.svg?color=currentColor" width="16" height="16" alt="">
                </a>
            <?php endif; ?>
            
            <?php
            $total_pages = ceil($total / $perpage);
            $start_page = max(1, $page - 2);
            $end_page = min($total_pages, $page + 2);
            
            if ($start_page > 1): ?>
                <a href="?page=agent_products&p=1&status=<?php echo $status; ?>" class="page-link">1</a>
                <?php if ($start_page > 2): ?>
                    <span class="page-ellipsis">...</span>
                <?php endif; ?>
            <?php endif; ?>
            
            <?php for ($i = $start_page; $i <= $end_page; $i++): ?>
                <a href="?page=agent_products&p=<?php echo $i; ?>&status=<?php echo $status; ?>" class="page-link <?php echo $i == $page ? 'active' : ''; ?>">
                    <?php echo $i; ?>
                </a>
            <?php endfor; ?>
            
            <?php if ($end_page < $total_pages): ?>
                <?php if ($end_page < $total_pages - 1): ?>
                    <span class="page-ellipsis">...</span>
                <?php endif; ?>
                <a href="?page=agent_products&p=<?php echo $total_pages; ?>&status=<?php echo $status; ?>" class="page-link"><?php echo $total_pages; ?></a>
            <?php endif; ?>
            
            <?php if ($page < $total_pages): ?>
                <a href="?page=agent_products&p=<?php echo $page + 1; ?>&status=<?php echo $status; ?>" class="page-link page-next">
                    <img src="https://api.iconify.design/mdi:chevron-right.svg?color=currentColor" width="16" height="16" alt="">
                </a>
            <?php endif; ?>
        </div>
    <?php endif; ?>
</div>

<!-- 审核弹窗 -->
<div id="reviewModal" class="modal" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h3>
                <img src="https://api.iconify.design/mdi:package-check.svg?color=%23667eea" width="20" height="20" style="margin-right: 8px;" alt="">
                审核产品
            </h3>
            <button type="button" class="modal-close" onclick="closeModal()">
                <img src="https://api.iconify.design/mdi:close.svg?color=%239ca3af" width="20" height="20" alt="">
            </button>
        </div>
        <form id="reviewForm">
            <input type="hidden" name="id" id="review_id">
            <input type="hidden" name="status" id="review_status">
            <div class="modal-body">
                <div class="form-group">
                    <label id="remarkLabel">
                        <img src="https://api.iconify.design/mdi:text-box.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">
                        备注
                    </label>
                    <textarea name="remark" id="review_remark" rows="3" placeholder="请填写审核备注..."></textarea>
                    <small id="remarkHint"></small>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary cancel-btn" onclick="closeModal()">
                    <img src="https://api.iconify.design/mdi:close.svg?color=currentColor" width="16" height="16" style="margin-right: 4px;" alt="">
                    取消
                </button>
                <button type="submit" class="btn btn-primary" id="modalSubmitBtn">
                    <img src="https://api.iconify.design/mdi:check.svg?color=white" width="16" height="16" style="margin-right: 4px;" alt="">
                    确认
                </button>
            </div>
        </form>
    </div>
</div>

<style>
/* 基础变量 */
:root {
    --primary-color: #667eea;
    --primary-hover: #5a67d8;
    --danger-color: #ef4444;
    --success-color: #10b981;
    --warning-color: #f59e0b;
    --bg-primary: #ffffff;
    --bg-secondary: #f9fafb;
    --text-primary: #1f2937;
    --text-secondary: #6b7280;
    --text-muted: #9ca3af;
    --border-color: #e5e7eb;
    --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
    --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    --radius-sm: 8px;
    --radius-md: 12px;
    --radius-lg: 16px;
}

.agent-products {
    max-width: 100%;
    padding: 4px;
}

/* 页面头部 */
.page-header {
    margin-bottom: 20px;
}
.page-header h2 {
    display: flex;
    align-items: center;
    font-size: 24px;
    font-weight: 600;
    color: var(--text-primary);
    margin: 0 0 6px;
}
.text-muted {
    color: var(--text-muted);
    font-size: 13px;
}

/* 统计卡片 */
.stats-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
    margin-bottom: 24px;
}
.stat-card {
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    padding: 20px;
    border: 1px solid var(--border-color);
    display: flex;
    align-items: center;
    gap: 16px;
    transition: all 0.2s;
    box-shadow: var(--shadow-sm);
}
.stat-card:hover {
    box-shadow: var(--shadow-md);
    transform: translateY(-2px);
}
.stat-icon {
    width: 52px;
    height: 52px;
    border-radius: var(--radius-md);
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(102, 126, 234, 0.05) 100%);
}
.stat-content {
    display: flex;
    flex-direction: column;
}
.stat-value {
    font-size: 26px;
    font-weight: 700;
    color: var(--text-primary);
    line-height: 1.2;
}
.stat-label {
    font-size: 13px;
    color: var(--text-muted);
    margin-top: 4px;
}

/* 筛选标签 */
.filter-bar {
    margin-bottom: 24px;
}
.filter-tabs {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}
.filter-tab {
    display: inline-flex;
    align-items: center;
    padding: 10px 18px;
    background: var(--bg-primary);
    border: 1px solid var(--border-color);
    border-radius: 30px;
    font-size: 14px;
    font-weight: 500;
    color: var(--text-secondary);
    text-decoration: none;
    transition: all 0.2s;
}
.filter-tab:hover {
    border-color: var(--primary-color);
    color: var(--primary-color);
    background: rgba(102, 126, 234, 0.05);
}
.filter-tab.active {
    background: var(--primary-color);
    color: white;
    border-color: var(--primary-color);
}
.filter-tab .count {
    margin-left: 6px;
    padding: 2px 8px;
    background: rgba(0, 0, 0, 0.1);
    border-radius: 20px;
    font-size: 12px;
}
.filter-tab.active .count {
    background: rgba(255, 255, 255, 0.2);
}

/* 表格 */
.table-wrapper {
    overflow-x: auto;
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    border: 1px solid var(--border-color);
    box-shadow: var(--shadow-sm);
}
.data-table {
    width: 100%;
    border-collapse: collapse;
    min-width: 1000px;
}
.data-table th {
    padding: 16px 16px;
    text-align: left;
    font-weight: 600;
    font-size: 13px;
    color: var(--text-secondary);
    background: var(--bg-secondary);
    border-bottom: 1px solid var(--border-color);
    white-space: nowrap;
    text-transform: uppercase;
    letter-spacing: 0.3px;
}
.data-table td {
    padding: 16px;
    border-bottom: 1px solid var(--border-color);
    font-size: 14px;
    vertical-align: middle;
}
.data-table tbody tr {
    transition: background 0.2s;
}
.data-table tbody tr:hover {
    background: var(--bg-secondary);
}
.data-table tbody tr:last-child td {
    border-bottom: none;
}

/* 单元格样式 */
.id-cell {
    font-family: 'Monaco', 'Menlo', monospace;
    font-size: 12px;
    color: var(--text-muted);
    font-weight: 500;
}
.user-info {
    display: flex;
    align-items: center;
    gap: 6px;
}
.product-info {
    display: flex;
    flex-direction: column;
    gap: 4px;
}
.product-desc {
    font-size: 12px;
    color: var(--text-muted);
}
.amount {
    font-weight: 600;
    color: var(--success-color);
}
.commission {
    font-weight: 600;
    color: var(--primary-color);
}
.discount-info {
    display: flex;
    flex-direction: column;
    gap: 6px;
}
.discount-badge {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 4px 10px;
    border-radius: 30px;
    font-size: 12px;
    font-weight: 500;
    background: #ede9fe;
    color: #6d28d9;
}
.stack-badge {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 2px 8px;
    border-radius: 30px;
    font-size: 11px;
    background: #fef3c7;
    color: #92400e;
}

/* 状态徽章 */
.status-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 5px 12px;
    border-radius: 30px;
    font-size: 12px;
    font-weight: 500;
    white-space: nowrap;
}
.status-dot {
    width: 6px;
    height: 6px;
    border-radius: 50%;
}
.status-pending {
    background: #fef3c7;
    color: #92400e;
}
.status-pending .status-dot {
    background: #f59e0b;
    box-shadow: 0 0 0 2px rgba(245, 158, 11, 0.2);
}
.status-approved {
    background: #d1fae5;
    color: #065f46;
}
.status-approved .status-dot {
    background: #10b981;
    box-shadow: 0 0 0 2px rgba(16, 185, 129, 0.2);
}
.status-rejected {
    background: #fee2e2;
    color: #991b1b;
}
.status-rejected .status-dot {
    background: #ef4444;
    box-shadow: 0 0 0 2px rgba(239, 68, 68, 0.2);
}

/* 操作按钮 */
.action-buttons {
    display: flex;
    gap: 8px;
}
.action-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 34px;
    height: 34px;
    background: var(--bg-secondary);
    border: 1px solid var(--border-color);
    border-radius: var(--radius-sm);
    cursor: pointer;
    transition: all 0.2s;
}
.action-btn:hover {
    background: var(--bg-primary);
    transform: translateY(-1px);
    box-shadow: var(--shadow-sm);
}
.approve-btn:hover {
    border-color: var(--success-color);
    background: #d1fae5;
}
.reject-btn:hover {
    border-color: var(--danger-color);
    background: #fee2e2;
}
.disabled-action {
    color: var(--text-muted);
    font-size: 12px;
}

/* 空状态 */
.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 20px;
    text-align: center;
}
.empty-state img {
    opacity: 0.4;
    margin-bottom: 16px;
}
.empty-state p {
    color: var(--text-muted);
    font-size: 15px;
    margin: 0;
}

/* 分页 */
.pagination {
    display: flex;
    gap: 6px;
    justify-content: center;
    margin-top: 28px;
}
.page-link {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 38px;
    height: 38px;
    padding: 0 8px;
    border: 1px solid var(--border-color);
    border-radius: var(--radius-sm);
    text-decoration: none;
    color: var(--text-primary);
    font-size: 14px;
    font-weight: 500;
    background: var(--bg-primary);
    transition: all 0.2s;
}
.page-link:hover {
    border-color: var(--primary-color);
    color: var(--primary-color);
    background: rgba(102, 126, 234, 0.05);
}
.page-link.active {
    background: var(--primary-color);
    color: white;
    border-color: var(--primary-color);
}
.page-ellipsis {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 38px;
    height: 38px;
    color: var(--text-muted);
}

/* 弹窗 */
.modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    backdrop-filter: blur(4px);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10000;
    animation: fadeIn 0.2s ease;
}
@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}
.modal-content {
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    width: 90%;
    max-width: 450px;
    box-shadow: var(--shadow-lg);
    animation: slideUp 0.3s ease;
}
@keyframes slideUp {
    from { opacity: 0; transform: translateY(20px); }
    to { opacity: 1; transform: translateY(0); }
}
.modal-header {
    padding: 20px 24px;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.modal-header h3 {
    display: flex;
    align-items: center;
    font-size: 18px;
    font-weight: 600;
    margin: 0;
}
.modal-close {
    background: none;
    border: none;
    cursor: pointer;
    padding: 4px;
    border-radius: var(--radius-sm);
    transition: background 0.2s;
    display: flex;
}
.modal-close:hover {
    background: var(--bg-secondary);
}
.modal-body {
    padding: 24px;
}
.modal-footer {
    padding: 16px 24px 24px;
    display: flex;
    gap: 12px;
    justify-content: flex-end;
}
.form-group {
    margin-bottom: 20px;
}
.form-group label {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    font-weight: 500;
    font-size: 14px;
    color: var(--text-primary);
}
.form-group textarea {
    width: 100%;
    padding: 12px 16px;
    border: 1.5px solid var(--border-color);
    border-radius: var(--radius-md);
    font-size: 14px;
    background: var(--bg-primary);
    resize: vertical;
    transition: all 0.2s;
}
.form-group textarea:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.form-group small {
    display: block;
    margin-top: 6px;
    font-size: 12px;
    color: var(--text-muted);
}

/* 按钮 */
.btn {
    display: inline-flex;
    align-items: center;
    padding: 10px 20px;
    border-radius: var(--radius-md);
    font-size: 14px;
    font-weight: 500;
    text-decoration: none;
    cursor: pointer;
    transition: all 0.2s;
    border: 1px solid transparent;
}
.btn-primary {
    background: var(--primary-color);
    color: white;
    box-shadow: 0 2px 4px rgba(102, 126, 234, 0.2);
}
.btn-primary:hover {
    background: var(--primary-hover);
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(102, 126, 234, 0.3);
}
.btn-secondary {
    background: var(--bg-primary);
    color: var(--text-primary);
    border-color: var(--border-color);
}
.btn-secondary:hover {
    background: var(--bg-secondary);
    border-color: var(--text-muted);
}

/* 加载动画 */
.loading-spinner {
    display: inline-block;
    width: 16px;
    height: 16px;
    border: 2px solid rgba(102, 126, 234, 0.3);
    border-radius: 50%;
    border-top-color: var(--primary-color);
    animation: spin 0.6s linear infinite;
}
@keyframes spin {
    to { transform: rotate(360deg); }
}

/* 响应式 */
@media (max-width: 1024px) {
    .stats-grid {
        grid-template-columns: repeat(2, 1fr);
    }
}
@media (max-width: 768px) {
    .stats-grid {
        grid-template-columns: 1fr;
    }
    .filter-tabs {
        flex-direction: column;
    }
    .filter-tab {
        justify-content: center;
    }
}
</style>

<script>
// 更新统计卡片
function updateStatsDisplay(newStatus) {
    const statTotal = document.getElementById('stat-total');
    const statPending = document.getElementById('stat-pending');
    const statApproved = document.getElementById('stat-approved');
    const statRejected = document.getElementById('stat-rejected');
    
    // 总数不变
    if (statPending) {
        let pendingCount = parseInt(statPending.innerText) || 0;
        statPending.innerText = Math.max(0, pendingCount - 1);
    }
    if (newStatus === 'approved' && statApproved) {
        let approvedCount = parseInt(statApproved.innerText) || 0;
        statApproved.innerText = approvedCount + 1;
    }
    if (newStatus === 'rejected' && statRejected) {
        let rejectedCount = parseInt(statRejected.innerText) || 0;
        statRejected.innerText = rejectedCount + 1;
    }
    
    // 更新筛选标签上的数量
    document.querySelectorAll('.filter-tab .count').forEach((el, index) => {
        if (index === 0 && statPending) {
            el.innerText = statPending.innerText;
        } else if (index === 1 && statApproved) {
            el.innerText = statApproved.innerText;
        } else if (index === 2 && statRejected) {
            el.innerText = statRejected.innerText;
        }
    });
}

function reviewProduct(id, status) {
    const modal = document.getElementById('reviewModal');
    const remarkLabel = document.getElementById('remarkLabel');
    const remarkHint = document.getElementById('remarkHint');
    const remarkTextarea = document.getElementById('review_remark');
    const modalSubmitBtn = document.getElementById('modalSubmitBtn');
    
    document.getElementById('review_id').value = id;
    document.getElementById('review_status').value = status;
    
    if (status === 'rejected') {
        remarkLabel.innerHTML = '<img src="https://api.iconify.design/mdi:text-box.svg?color=%23ef4444" width="16" height="16" style="margin-right: 6px;" alt="">拒绝原因 <span style="color: #ef4444;">*</span>';
        remarkHint.innerText = '拒绝时必须填写原因';
        remarkTextarea.required = true;
        modalSubmitBtn.innerHTML = '<img src="https://api.iconify.design/mdi:close.svg?color=white" width="16" height="16" style="margin-right: 4px;" alt="">确认拒绝';
    } else {
        remarkLabel.innerHTML = '<img src="https://api.iconify.design/mdi:text-box.svg?color=%23667eea" width="16" height="16" style="margin-right: 6px;" alt="">备注';
        remarkHint.innerText = '选填';
        remarkTextarea.required = false;
        modalSubmitBtn.innerHTML = '<img src="https://api.iconify.design/mdi:check.svg?color=white" width="16" height="16" style="margin-right: 4px;" alt="">确认通过';
    }
    
    remarkTextarea.value = '';
    modal.style.display = 'flex';
}

function closeModal() {
    document.getElementById('reviewModal').style.display = 'none';
    document.getElementById('reviewForm')?.reset();
}

document.addEventListener('DOMContentLoaded', function() {
    // 关闭弹窗
    document.querySelectorAll('.modal-close, .cancel-btn').forEach(btn => {
        btn.addEventListener('click', closeModal);
    });
    
    // 点击背景关闭弹窗
    const modal = document.getElementById('reviewModal');
    if (modal) {
        modal.addEventListener('click', function(e) {
            if (e.target === modal) closeModal();
        });
    }
    
    // ESC 关闭弹窗
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') closeModal();
    });
    
    // 审核表单提交
    document.getElementById('reviewForm')?.addEventListener('submit', function(e) {
        e.preventDefault();
        const formData = new FormData(this);
        const id = formData.get('id');
        const status = formData.get('status');
        const remark = formData.get('remark');
        
        if (status === 'rejected' && !remark.trim()) {
            window.showToast && window.showToast('拒绝时必须填写原因', 'error');
            return;
        }
        
        const submitBtn = this.querySelector('button[type="submit"]');
        const originalHtml = submitBtn.innerHTML;
        submitBtn.innerHTML = '<span class="loading-spinner"></span> 处理中...';
        submitBtn.disabled = true;
        
        fetch('/api/agent_product_review.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `id=${id}&status=${status}&remark=${encodeURIComponent(remark)}`
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                // 更新统计卡片
                updateStatsDisplay(status);
                
                // 更新行状态
                const row = document.getElementById('product-row-' + id);
                const statusBadge = document.getElementById('status-badge-' + id);
                const actionButtons = document.getElementById('action-buttons-' + id);
                
                if (statusBadge) {
                    if (status === 'approved') {
                        statusBadge.className = 'status-badge status-approved';
                        statusBadge.innerHTML = '<span class="status-dot"></span>已通过';
                    } else {
                        statusBadge.className = 'status-badge status-rejected';
                        statusBadge.innerHTML = '<span class="status-dot"></span>已拒绝';
                    }
                }
                
                if (actionButtons) {
                    actionButtons.innerHTML = '<span class="disabled-action">-</span>';
                }
                
                window.showToast && window.showToast(status === 'approved' ? '审核通过' : '已拒绝', 'success');
                closeModal();
            } else {
                window.showToast && window.showToast(data.message || '操作失败', 'error');
                submitBtn.innerHTML = originalHtml;
                submitBtn.disabled = false;
            }
        })
        .catch(err => {
            console.error('错误:', err);
            window.showToast && window.showToast('网络错误', 'error');
            submitBtn.innerHTML = originalHtml;
            submitBtn.disabled = false;
        });
    });
});
</script>