<?php
ob_start();
requireAdmin();

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

// 获取代理商列表
$agents = $db->fetchAll("SELECT id, username, email, agent_level FROM users WHERE is_agent = 1 ORDER BY id DESC");

// 获取代理商的可销售应用
$where = "1=1";
if ($agent_id > 0) {
    $where .= " AND aa.agent_id = $agent_id";
}

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

$agent_apps = $db->fetchAll("
    SELECT aa.*, a.name as app_name, u.username as agent_name
    FROM agent_apps aa
    JOIN apps a ON aa.app_id = a.id
    JOIN users u ON aa.agent_id = u.id
    WHERE $where
    ORDER BY aa.id DESC
    LIMIT $offset, $perpage
");

// 获取所有应用（用于分配）
$all_apps = $db->fetchAll("SELECT id, name, price FROM apps WHERE status = 1");

// 处理分配应用
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['action']) && $_GET['action'] === 'assign') {
    header('Content-Type: application/json');
    $agent_id = intval($_POST['agent_id'] ?? 0);
    $app_id = intval($_POST['app_id'] ?? 0);
    $agent_price = floatval($_POST['agent_price'] ?? 0);
    $commission_rate = floatval($_POST['commission_rate'] ?? 0);
    
    if ($agent_id > 0 && $app_id > 0 && $agent_price > 0) {
        // 检查是否已存在
        $check = $db->fetchOne("SELECT id FROM agent_apps WHERE agent_id = $agent_id AND app_id = $app_id");
        if ($check) {
            echo json_encode(['success' => false, 'message' => '该应用已分配给此代理商']);
            exit;
        }
        
        $db->query("INSERT INTO agent_apps (agent_id, app_id, agent_price, commission_rate, status) 
                    VALUES ($agent_id, $app_id, $agent_price, $commission_rate, 1)");
        echo json_encode(['success' => true, 'message' => '分配成功']);
    } else {
        echo json_encode(['success' => false, 'message' => '参数错误']);
    }
    exit;
}

// 处理删除
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['action']) && $_GET['action'] === 'delete') {
    header('Content-Type: application/json');
    $id = intval($_POST['id'] ?? 0);
    $db->query("DELETE FROM agent_apps WHERE id = $id");
    echo json_encode(['success' => true]);
    exit;
}

// 处理更新
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['action']) && $_GET['action'] === 'update') {
    header('Content-Type: application/json');
    $id = intval($_POST['id'] ?? 0);
    $agent_price = floatval($_POST['agent_price'] ?? 0);
    $commission_rate = floatval($_POST['commission_rate'] ?? 0);
    $status = intval($_POST['status'] ?? 1);
    
    $db->query("UPDATE agent_apps SET agent_price = $agent_price, commission_rate = $commission_rate, status = $status WHERE id = $id");
    echo json_encode(['success' => true]);
    exit;
}
?>

<div class="agent-apps-manager">
    <div class="page-header">
        <h2>代理商应用管理</h2>
        <button class="btn btn-primary" id="showAssignModalBtn">+ 分配应用</button>
    </div>
    
    <!-- 筛选栏 -->
    <div class="filter-bar">
        <select id="agentFilter" onchange="location.href='?page=agent_apps&agent_id='+this.value">
            <option value="0">全部代理商</option>
            <?php foreach ($agents as $agent): ?>
                <option value="<?php echo $agent['id']; ?>" <?php echo $agent_id == $agent['id'] ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($agent['username']); ?> (等级<?php echo $agent['agent_level']; ?>)
                </option>
            <?php endforeach; ?>
        </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($agent_apps)): ?>
                    <tr><td colspan="8" style="text-align: center;">暂无分配记录</td></tr>
                <?php else: ?>
                    <?php foreach ($agent_apps as $item): ?>
                        <tr id="app-row-<?php echo $item['id']; ?>">
                            <td><?php echo $item['id']; ?></td>
                            <td><?php echo htmlspecialchars($item['agent_name']); ?></td>
                            <td><?php echo htmlspecialchars($item['app_name']); ?></td>
                            <td class="price-cell">
                                ¥<span class="price-value"><?php echo number_format($item['agent_price'], 2); ?></span>
                                <input type="number" class="edit-price" value="<?php echo $item['agent_price']; ?>" step="0.01" style="display:none; width:80px;">
                            </td>
                            <td class="commission-cell">
                                <span class="commission-value"><?php echo $item['commission_rate']; ?></span>%
                                <input type="number" class="edit-commission" value="<?php echo $item['commission_rate']; ?>" step="0.01" style="display:none; width:60px;">
                            </td>
                            <td class="status-cell">
                                <span class="status-badge status-<?php echo $item['status'] ? 'active' : 'inactive'; ?>" data-status="<?php echo $item['status']; ?>">
                                    <?php echo $item['status'] ? '启用' : '禁用'; ?>
                                </span>
                                <select class="edit-status" style="display:none;">
                                    <option value="1" <?php echo $item['status'] == 1 ? 'selected' : ''; ?>>启用</option>
                                    <option value="0" <?php echo $item['status'] == 0 ? 'selected' : ''; ?>>禁用</option>
                                </select>
                            </td>
                            <td><?php echo $item['created_at']; ?></td>
                            <td class="action-buttons">
                                <button class="action-btn edit-btn" data-id="<?php echo $item['id']; ?>">✏️ 编辑</button>
                                <button class="action-btn save-btn" data-id="<?php echo $item['id']; ?>" style="display:none;">💾 保存</button>
                                <button class="action-btn delete-btn" data-id="<?php echo $item['id']; ?>">🗑️ 删除</button>
                            </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_apps&p=<?php echo $i; ?>&agent_id=<?php echo $agent_id; ?>" class="page-link <?php echo $i == $page ? 'active' : ''; ?>"><?php echo $i; ?></a>
            <?php endfor; ?>
        </div>
    <?php endif; ?>
</div>

<!-- 分配应用弹窗 -->
<div id="assignModal" class="modal" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h3>分配应用给代理商</h3>
            <span class="close">&times;</span>
        </div>
        <form id="assignForm">
            <div class="modal-body">
                <div class="form-group">
                    <label>选择代理商</label>
                    <select name="agent_id" required>
                        <option value="">请选择</option>
                        <?php foreach ($agents as $agent): ?>
                            <option value="<?php echo $agent['id']; ?>"><?php echo htmlspecialchars($agent['username']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>选择应用</label>
                    <select name="app_id" required>
                        <option value="">请选择</option>
                        <?php foreach ($all_apps as $app): ?>
                            <option value="<?php echo $app['id']; ?>"><?php echo htmlspecialchars($app['name']); ?> (¥<?php echo $app['price']; ?>)</option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>代理商售价</label>
                    <input type="number" name="agent_price" step="0.01" required placeholder="请输入售价">
                </div>
                <div class="form-group">
                    <label>佣金比例 (%)</label>
                    <input type="number" name="commission_rate" step="0.01" required placeholder="例如：20">
                </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-buttons {
    display: flex;
    gap: 5px;
    flex-wrap: wrap;
}
.action-btn {
    background: none;
    border: 1px solid var(--border-color);
    padding: 4px 10px;
    border-radius: 6px;
    cursor: pointer;
    font-size: 12px;
}
.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;
}
@keyframes spin {
    to { transform: rotate(360deg); }
}
</style>

<script>
// 分配弹窗
const assignModal = document.getElementById('assignModal');
document.getElementById('showAssignModalBtn')?.addEventListener('click', () => {
    assignModal.style.display = 'flex';
});

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

// 分配表单提交
document.getElementById('assignForm')?.addEventListener('submit', function(e) {
    e.preventDefault();
    const formData = new FormData(this);
    const submitBtn = this.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;
    submitBtn.innerHTML = '<span class="loading-spinner"></span> 分配中...';
    submitBtn.disabled = true;
    
    fetch('?page=agent_apps&action=assign', {
        method: 'POST',
        body: formData
    })
    .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(() => {
        window.showToast('网络错误', 'error');
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;
    });
});

// 编辑功能
document.querySelectorAll('.edit-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        const row = this.closest('tr');
        const priceSpan = row.querySelector('.price-value');
        const priceInput = row.querySelector('.edit-price');
        const commissionSpan = row.querySelector('.commission-value');
        const commissionInput = row.querySelector('.edit-commission');
        const statusSpan = row.querySelector('.status-badge');
        const statusSelect = row.querySelector('.edit-status');
        const editBtn = row.querySelector('.edit-btn');
        const saveBtn = row.querySelector('.save-btn');
        
        priceSpan.style.display = 'none';
        priceInput.style.display = 'inline-block';
        commissionSpan.style.display = 'none';
        commissionInput.style.display = 'inline-block';
        statusSpan.style.display = 'none';
        statusSelect.style.display = 'inline-block';
        editBtn.style.display = 'none';
        saveBtn.style.display = 'inline-block';
    });
});

// 保存编辑
document.querySelectorAll('.save-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        const row = this.closest('tr');
        const id = this.dataset.id;
        const priceInput = row.querySelector('.edit-price');
        const commissionInput = row.querySelector('.edit-commission');
        const statusSelect = row.querySelector('.edit-status');
        const agentPrice = priceInput.value;
        const commissionRate = commissionInput.value;
        const status = statusSelect.value;
        
        fetch('?page=agent_apps&action=update', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `id=${id}&agent_price=${agentPrice}&commission_rate=${commissionRate}&status=${status}`
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                window.showToast('更新成功', 'success');
                location.reload();
            } else {
                window.showToast('更新失败', 'error');
            }
        })
        .catch(() => window.showToast('网络错误', 'error'));
    });
});

// 删除
document.querySelectorAll('.delete-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        if (!confirm('确定要删除此分配吗？')) return;
        const id = this.dataset.id;
        fetch('?page=agent_apps&action=delete', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `id=${id}`
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                window.showToast('删除成功', 'success');
                setTimeout(() => location.reload(), 1000);
            } else {
                window.showToast('删除失败', 'error');
            }
        });
    });
});
</script>