<?php
requireAdmin();

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

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

$withdrawals = $db->fetchAll("
    SELECT w.*, u.username, u.email, u.agent_total_commission, u.agent_withdrawn
    FROM agent_withdrawals w
    JOIN users u ON w.agent_id = u.id
    WHERE $where
    ORDER BY w.id DESC
    LIMIT $offset, $perpage
");
?>

<div class="agent-withdrawals">
    <div class="page-header">
        <h2>佣金提现审核</h2>
    </div>
    
    <div class="filter-bar">
        <select id="statusFilter" onchange="location.href='?page=agent_withdrawals&status='+this.value">
            <option value="pending" <?php echo $status == 'pending' ? 'selected' : ''; ?>>待处理</option>
            <option value="processing" <?php echo $status == 'processing' ? 'selected' : ''; ?>>处理中</option>
            <option value="completed" <?php echo $status == 'completed' ? '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($withdrawals)): ?>
                    <tr><td colspan="9" style="text-align: center;">暂无提现申请</td></tr>
                <?php else: ?>
                    <?php foreach ($withdrawals as $item): ?>
                        <tr id="withdraw-row-<?php echo $item['id']; ?>">
                            <td><?php echo $item['id']; ?></td>
                            <td>
                                <strong><?php echo htmlspecialchars($item['username']); ?></strong><br>
                                <small><?php echo htmlspecialchars($item['email']); ?></small>
                             </td>
                            <td>¥<?php echo number_format($item['amount'], 2); ?></td>
                            <td>
                                <?php 
                                $method_map = ['alipay' => '支付宝', 'wechat' => '微信支付', 'bank' => '银行卡'];
                                echo $method_map[$item['withdrawal_method']] ?? $item['withdrawal_method'];
                                ?>
                             </td>
                            <td><?php echo htmlspecialchars($item['account']); ?></td>
                            <td><?php echo htmlspecialchars($item['account_name'] ?: '-'); ?></td>
                            <td><?php echo $item['created_at']; ?></td>
                            <td>
                                <span class="status-badge status-<?php echo $item['status']; ?>">
                                    <?php 
                                    $status_map = ['pending' => '待处理', 'processing' => '处理中', 'completed' => '已完成', 'rejected' => '已拒绝'];
                                    echo $status_map[$item['status']] ?? $item['status'];
                                    ?>
                                </span>
                             </td>
                            <td class="action-buttons">
                                <?php if ($item['status'] == 'pending'): ?>
                                    <button class="action-btn" onclick="reviewWithdrawal(<?php echo $item['id']; ?>, 'processing')">⏳ 标记处理中</button>
                                    <button class="action-btn success-btn" onclick="reviewWithdrawal(<?php echo $item['id']; ?>, 'completed')">✓ 确认到账</button>
                                    <button class="action-btn delete-btn" onclick="reviewWithdrawal(<?php echo $item['id']; ?>, 'rejected')">✗ 拒绝</button>
                                <?php elseif ($item['status'] == 'processing'): ?>
                                    <button class="action-btn success-btn" onclick="reviewWithdrawal(<?php echo $item['id']; ?>, 'completed')">✓ 确认到账</button>
                                    <button class="action-btn delete-btn" onclick="reviewWithdrawal(<?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_withdrawals&p=<?php echo $i; ?>&status=<?php echo $status; ?>" class="page-link <?php echo $i == $page ? 'active' : ''; ?>"><?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; }
.status-pending { background: #fef3c7; color: #92400e; }
.status-processing { background: #d1fae5; color: #065f46; }
.status-completed { background: #10b981; color: white; }
.status-rejected { background: #fee2e2; color: #991b1b; }
.action-btn { background: none; border: 1px solid var(--border-color); padding: 4px 12px; border-radius: 6px; cursor: pointer; font-size: 12px; margin: 2px; }
.success-btn:hover { border-color: #10b981; color: #10b981; }
.delete-btn:hover { border-color: var(--danger-color); color: var(--danger-color); }
.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; }
.loading-spinner { display: inline-block; width: 14px; height: 14px; border: 2px solid #fff; border-radius: 50%; border-top-color: transparent; animation: spin 0.6s linear infinite; margin-right: 6px; vertical-align: middle; }
@keyframes spin { to { transform: rotate(360deg); } }
</style>

<script>
const modal = document.getElementById('reviewModal');
const reviewForm = document.getElementById('reviewForm');

function reviewWithdrawal(id, status) {
    document.getElementById('review_id').value = id;
    document.getElementById('review_status').value = status;
    modal.style.display = 'flex';
}

function closeModal() {
    modal.style.display = 'none';
}

document.querySelectorAll('.close, .cancel-btn').forEach(btn => {
    btn.addEventListener('click', closeModal);
});

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_withdraw_review.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `id=${id}&status=${status}&remark=${encodeURIComponent(remark)}`
    })
    .then(response => response.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(error => {
        console.error('错误:', error);
        window.showToast('网络错误', 'error');
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;
        closeModal();
    });
});
</script>