<?php
requireAdmin();

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

// 修复：指定表名 agent_applications.status
$where = "aa.status = '$status'";
$total_result = $db->query("SELECT COUNT(*) as cnt FROM agent_applications aa WHERE $where");
$total = $total_result->fetch_assoc()['cnt'];
$offset = ($page - 1) * $perpage;

$applications = $db->fetchAll("
    SELECT aa.*, u.username, u.email 
    FROM agent_applications aa
    JOIN users u ON aa.user_id = u.id
    WHERE $where
    ORDER BY aa.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'] ?? '');
    
    $application = $db->fetchOne("SELECT * FROM agent_applications WHERE id = $id");
    if ($application && in_array($status_val, ['approved', 'rejected'])) {
        $db->query("UPDATE agent_applications SET status = '$status_val', admin_remark = '$remark', processed_at = NOW() WHERE id = $id");
        
        if ($status_val == 'approved') {
            // 更新用户为代理商
            $db->query("UPDATE users SET is_agent = 1, agent_level = 1 WHERE id = {$application['user_id']}");
        }
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'message' => '操作失败']);
    }
    exit;
}
?>

<div class="agent-applications">
    <div class="page-header">
        <h2>代理商申请审核</h2>
    </div>
    
    <div class="filter-bar">
        <select id="statusFilter" onchange="location.href='?page=agent_applications&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>
                </thead>
            <tbody>
                <?php if (empty($applications)): ?>
                    <tr><td colspan="8" style="text-align: center;">暂无申请</td></tr>
                <?php else: ?>
                    <?php foreach ($applications as $app): ?>
                        <tr id="app-row-<?php echo $app['id']; ?>">
                            <td><?php echo $app['id']; ?></td>
                            <td><?php echo htmlspecialchars($app['username']); ?><br><small><?php echo htmlspecialchars($app['email']); ?></small></td>
                            <td><strong><?php echo htmlspecialchars($app['agent_name']); ?></strong></td>
                            <td>
                                电话: <?php echo $app['contact_phone'] ?: '-'; ?><br>
                                QQ: <?php echo $app['contact_qq'] ?: '-'; ?><br>
                                微信: <?php echo $app['contact_wechat'] ?: '-'; ?>
                            </td>
                            <td><?php echo nl2br(htmlspecialchars($app['reason'] ?: '-')); ?></td>
                            <td><?php echo $app['created_at']; ?></td>
                            <td>
                                <span class="status-badge status-<?php echo $app['status']; ?>">
                                    <?php echo $app['status'] == 'pending' ? '待审核' : ($app['status'] == 'approved' ? '已通过' : '已拒绝'); ?>
                                </span>
                            </td>
                            <td>
                                <?php if ($app['status'] == 'pending'): ?>
                                    <button class="action-btn" onclick="reviewApplication(<?php echo $app['id']; ?>, 'approved')">✓ 通过</button>
                                    <button class="action-btn delete-btn" onclick="reviewApplication(<?php echo $app['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_applications&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-approved {
    background: #d1fae5;
    color: #065f46;
}
.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;
}
.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;
}
</style>

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

function reviewApplication(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');
    
    fetch('?page=agent_applications&action=review', {
        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');
        }
        closeModal();
    })
    .catch(() => {
        window.showToast('网络错误', 'error');
        closeModal();
    });
});
</script>