<?php
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
");

// 处理审核
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['action']) && $_GET['action'] === 'review') {
    header('Content-Type: application/json');
    $id = intval($_POST['id'] ?? 0);
    $status_val = $_POST['status'] ?? '';
    $remark = trim($_POST['remark'] ?? '');
    
    $product = $db->fetchOne("SELECT * FROM agent_products WHERE id = $id");
    if ($product && in_array($status_val, ['approved', 'rejected'])) {
        $db->query("UPDATE agent_products SET status = '$status_val', admin_remark = '$remark' WHERE id = $id");
        
        if ($status_val == 'approved') {
            // 审核通过，将产品添加到应用表
            $name = $db->escape($product['name']);
            $description = $db->escape($product['description']);
            $price = $product['price'];
            $duration_days = $product['duration_days'];
            $db->query("INSERT INTO apps (name, description, price, duration_days, status) 
                        VALUES ('$name', '$description', $price, $duration_days, 1)");
            
            // 同时给代理商分配这个应用，并同步折扣设置
            $new_app_id = $db->insertId();
            $db->query("INSERT INTO agent_apps (agent_id, app_id, agent_price, commission_rate, status, 
                        discount_enabled, discount_type, discount_value, stack_discount) 
                        VALUES ({$product['agent_id']}, $new_app_id, $price, {$product['commission_rate']}, 1,
                        {$product['discount_enabled']}, '{$product['discount_type']}', {$product['discount_value']}, {$product['stack_discount']})");
        }
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'message' => '操作失败']);
    }
    exit;
}
?>

<div class="agent-products">
    <div class="page-header">
        <h2>代理商产品审核</h2>
    </div>
    
    <div class="filter-bar">
        <select id="statusFilter" onchange="location.href='?page=agent_products&status='+this.value">
            <option value="pending" <?php echo $status == 'pending' ? 'selected' : ''; ?>>待审核</option>
            <option value="approved" <?php echo $status == 'approved' ? 'selected' : ''; ?>>已通过</option>
            <option value="rejected" <?php echo $status == 'rejected' ? 'selected' : ''; ?>>已拒绝</option>
        </select>
    </div>
    
    <div class="table-container">
        <table class="data-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>代理商</th>
                    <th>产品名称</th>
                    <th>价格</th>
                    <th>佣金</th>
                    <th>折扣设置</th>
                    <th>状态</th>
                    <th>提交时间</th>
                    <th>操作</th>
                </thead>
            <tbody>
                <?php if (empty($products)): ?>
                    <tr><td colspan="9" style="text-align: center;">暂无产品申请</td></tr>
                <?php else: ?>
                    <?php foreach ($products as $item): ?>
                        <tr id="product-row-<?php echo $item['id']; ?>">
                            <td><?php echo $item['id']; ?></td>
                            <td><?php echo htmlspecialchars($item['agent_name']); ?></td>
                            <td><strong><?php echo htmlspecialchars($item['name']); ?></strong><br><small><?php echo htmlspecialchars(mb_substr($item['description'], 0, 50)); ?></small></td>
                            <td>¥<?php echo number_format($item['price'], 2); ?></td>
                            <td><?php echo $item['commission_rate']; ?>%</td>
                            <td>
                                <?php if ($item['discount_enabled']): ?>
                                    <?php if ($item['discount_type'] == 'percent'): ?>
                                        <?php echo $item['discount_value']; ?>% OFF
                                    <?php else: ?>
                                        ￥<?php echo number_format($item['discount_value'], 2); ?> OFF
                                    <?php endif; ?>
                                    <?php if ($item['stack_discount']): ?>
                                        <br><small class="stack-tip">可叠加</small>
                                    <?php endif; ?>
                                <?php else: ?>
                                    -
                                <?php endif; ?>
                            </td>
                            <td>
                                <span class="status-badge status-<?php echo $item['status']; ?>">
                                    <?php echo $item['status'] == 'pending' ? '待审核' : ($item['status'] == 'approved' ? '已通过' : '已拒绝'); ?>
                                </span>
                            </td>
                            <td><?php echo $item['created_at']; ?></td>
                            <td class="action-buttons">
                                <?php if ($item['status'] == 'pending'): ?>
                                    <button class="action-btn" onclick="reviewProduct(<?php echo $item['id']; ?>, 'approved')">✓ 通过</button>
                                    <button class="action-btn delete-btn" onclick="reviewProduct(<?php echo $item['id']; ?>, 'rejected')">✗ 拒绝</button>
                                <?php else: ?>
                                    -
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <?php if ($total > $perpage): ?>
        <div class="pagination">
            <?php for ($i = 1; $i <= ceil($total / $perpage); $i++): ?>
                <a href="?page=agent_products&p=<?php echo $i; ?>&status=<?php echo $status; ?>" class="page-link"><?php echo $i; ?></a>
            <?php endfor; ?>
        </div>
    <?php endif; ?>
</div>

<!-- 审核弹窗 -->
<div id="reviewModal" class="modal" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h3>审核产品</h3>
            <span class="close">&times;</span>
        </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>备注（拒绝时必填）</label>
                    <textarea name="remark" rows="3" placeholder="请填写拒绝原因..."></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary cancel-btn">取消</button>
                <button type="submit" class="btn btn-primary">确认</button>
            </div>
        </form>
    </div>
</div>

<style>
.filter-bar { margin-bottom: 20px; }
.action-btn { background: none; border: 1px solid var(--border-color); padding: 4px 12px; border-radius: 6px; cursor: pointer; margin: 2px; }
.delete-btn:hover { border-color: var(--danger-color); color: var(--danger-color); }
.status-pending { background: #fef3c7; color: #92400e; }
.status-approved { background: #d1fae5; color: #065f46; }
.status-rejected { background: #fee2e2; color: #991b1b; }
.stack-tip { color: #f59e0b; }
.modal { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 10000; }
.modal-content { background: var(--bg-primary); border-radius: 12px; width: 90%; max-width: 450px; }
.modal-header { padding: 15px 20px; border-bottom: 1px solid var(--border-color); display: flex; justify-content: space-between; }
.modal-body { padding: 20px; }
.modal-footer { padding: 15px 20px; border-top: 1px solid var(--border-color); display: flex; gap: 10px; justify-content: flex-end; }
</style>

<script>
function reviewProduct(id, status) {
    document.getElementById('review_id').value = id;
    document.getElementById('review_status').value = status;
    document.getElementById('reviewModal').style.display = 'flex';
}

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

document.querySelectorAll('.close, .cancel-btn').forEach(btn => {
    btn.addEventListener('click', 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');
    
    const submitBtn = this.querySelector('button[type="submit"]');
    const originalText = 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) {
            window.showToast('审核成功', 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            window.showToast(data.message || '操作失败', 'error');
        }
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;
        closeModal();
    })
    .catch(err => {
        console.error('错误:', err);
        window.showToast('网络错误', 'error');
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;
        closeModal();
    });
});
</script>