<?php
require_once __DIR__ . '/layout.php';

$db = db();

// Only super admins can manage agents
if ($admin['is_agent']) {
    echo "权限不足";
    exit;
}

// Handle Delete
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $db->prepare("DELETE FROM admins WHERE id = ? AND is_agent = 1")->execute([$id]);
    header('Location: agents.php?msg=deleted');
    exit;
}

// Handle Add/Edit
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'add') {
        $username = $_POST['username'];
        $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
        $permissions = json_encode($_POST['permissions'] ?? []);
        
        $db->prepare("INSERT INTO admins (username, password_hash, is_agent, permissions, role) VALUES (?, ?, 1, ?, 'agent')")
           ->execute([$username, $password, $permissions]);
        header('Location: agents.php?msg=added');
        exit;
    }
    
    if ($_POST['action'] === 'edit') {
        $id = (int)$_POST['agent_id'];
        $username = $_POST['username'];
        $permissions = json_encode($_POST['permissions'] ?? []);
        
        $db->prepare("UPDATE admins SET username = ?, permissions = ? WHERE id = ? AND is_agent = 1")
           ->execute([$username, $permissions, $id]);
           
        if (!empty($_POST['password'])) {
            $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
            $db->prepare("UPDATE admins SET password_hash = ? WHERE id = ?")->execute([$password, $id]);
        }
        
        header('Location: agents.php?msg=updated');
        exit;
    }
}

$title = '代理管理';
ob_start();
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div class="d-flex align-items-center gap-3">
        <a href="index.php" class="btn btn-outline-secondary btn-sm"><i class="bi bi-arrow-left"></i> 返回</a>
        <h4 class="mb-0">代理商列表</h4>
    </div>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addAgentModal">
        <i class="bi bi-person-plus me-1"></i> 添加代理
    </button>
</div>

<?php if (isset($_GET['msg'])): ?>
    <div class="alert alert-success alert-dismissible fade show mb-4" role="alert">
        操作成功！
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<div class="table-container">
    <table class="table table-hover align-middle">
        <thead>
            <tr class="text-muted small">
                <th>编号</th>
                <th>用户名</th>
                <th>下属用户数</th>
                <th>权限</th>
                <th>创建时间</th>
                <th class="text-end">操作</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $stmt = $db->query("SELECT a.*, (SELECT COUNT(*) FROM users WHERE agent_id = a.id) as user_count FROM admins a WHERE is_agent = 1 ORDER BY created_at DESC");
            while ($a = $stmt->fetch()):
                $perms = json_decode($a['permissions'] ?? '[]', true);
            ?>
            <tr>
                <td><?= $a['id'] ?></td>
                <td>
                    <div class="fw-bold"><?= htmlspecialchars($a['username']) ?></div>
                    <div class="text-muted small">代理商</div>
                </td>
                <td><span class="badge bg-info"><?= $a['user_count'] ?> 人</span></td>
                <td>
                    <?php if (empty($perms)): ?>
                        <span class="text-muted">无特殊权限</span>
                    <?php else: ?>
                        <?php foreach($perms as $p): ?>
                            <span class="badge bg-secondary me-1"><?= $p ?></span>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </td>
                <td><?= $a['created_at'] ?></td>
                <td class="text-end">
                    <div class="btn-group btn-group-sm">
                        <button class="btn btn-outline-primary" onclick="editAgent(<?= htmlspecialchars(json_encode($a)) ?>)">编辑</button>
                        <a href="?delete=<?= $a['id'] ?>" class="btn btn-outline-danger" onclick="return confirm('确定要删除此代理吗？')">删除</a>
                    </div>
                </td>
            </tr>
            <?php endwhile; ?>
        </tbody>
    </table>
</div>

<!-- Add Agent Modal -->
<div class="modal fade" id="addAgentModal" tabindex="-1">
    <div class="modal-dialog">
        <form class="modal-content" method="POST">
            <input type="hidden" name="action" value="add">
            <div class="modal-header">
                <h5 class="modal-title">添加新代理</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">代理用户名</label>
                    <input type="text" name="username" class="form-control" required>
                </div>
                <div class="mb-3">
                    <label class="form-label">登录密码</label>
                    <input type="password" name="password" class="form-control" required>
                </div>
                <div class="mb-3">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <label class="form-label mb-0">权限设置</label>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="selectAllAdd">
                            <label class="form-check-label small" for="selectAllAdd">全选</label>
                        </div>
                    </div>
                    <div class="d-flex flex-wrap gap-2 p-3 bg-light rounded border" id="add_permissions_container">
                        <?php
                        $available_perms = [
                            'manage_users' => '用户管理',
                            'audit_finance' => '财务管理',
                            'manage_kyc' => '实名认证',
                            'view_orders' => '订单查看',
                            'manage_spot' => '币币交易',
                            'manage_contract' => '合约交易',
                            'manage_mining' => '矿机管理',
                            'manage_exchange' => '兑换管理',
                            'manage_binary' => '秒合约',
                            'manage_ai' => 'AI控制',
                            'manage_chat' => '客服系统',
                            'manage_settings' => '系统设置',
                            'view_stats' => '数据统计'
                        ];
                        foreach ($available_perms as $val => $label):
                        ?>
                        <div class="form-check" style="min-width: 100px;">
                            <input class="form-check-input add-p-checkbox" type="checkbox" name="permissions[]" value="<?= $val ?>" id="p_<?= $val ?>">
                            <label class="form-check-label" for="p_<?= $val ?>"><?= $label ?></label>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="submit" class="btn btn-primary">创建代理</button>
            </div>
        </form>
    </div>
</div>

<!-- Edit Agent Modal -->
<div class="modal fade" id="editAgentModal" tabindex="-1">
    <div class="modal-dialog">
        <form class="modal-content" method="POST">
            <input type="hidden" name="action" value="edit">
            <input type="hidden" name="agent_id" id="edit_agent_id">
            <div class="modal-header">
                <h5 class="modal-title">编辑代理 - <span id="edit_agent_name"></span></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">代理用户名</label>
                    <input type="text" name="username" id="edit_username" class="form-control" required>
                </div>
                <div class="mb-3">
                    <label class="form-label">修改密码 (留空不改)</label>
                    <input type="text" name="password" class="form-control">
                </div>
                <div class="mb-3">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <label class="form-label mb-0">权限设置</label>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="selectAllEdit">
                            <label class="form-check-label small" for="selectAllEdit">全选</label>
                        </div>
                    </div>
                    <div class="d-flex flex-wrap gap-2 p-3 bg-light rounded border" id="edit_permissions_container">
                        <?php foreach ($available_perms as $val => $label): ?>
                        <div class="form-check" style="min-width: 100px;">
                            <input class="form-check-input edit-p-checkbox" type="checkbox" name="permissions[]" value="<?= $val ?>" id="ep_<?= $val ?>">
                            <label class="form-check-label" for="ep_<?= $val ?>"><?= $label ?></label>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="submit" class="btn btn-primary">保存修改</button>
            </div>
        </form>
    </div>
</div>

<script>
function editAgent(agent) {
    document.getElementById('edit_agent_id').value = agent.id;
    document.getElementById('edit_agent_name').innerText = agent.username;
    document.getElementById('edit_username').value = agent.username;
    
    // Clear checkboxes
    document.querySelectorAll('.edit-p-checkbox').forEach(cb => cb.checked = false);
    document.getElementById('selectAllEdit').checked = false;
    
    // Set checkboxes
    if (agent.permissions) {
        const perms = JSON.parse(agent.permissions);
        perms.forEach(p => {
            const cb = document.querySelector(`.edit-p-checkbox[value="${p}"]`);
            if (cb) cb.checked = true;
        });
        
        // Check if all are checked
        const allChecked = Array.from(document.querySelectorAll('.edit-p-checkbox')).every(cb => cb.checked);
        document.getElementById('selectAllEdit').checked = allChecked;
    }
    
    var modal = new bootstrap.Modal(document.getElementById('editAgentModal'));
    modal.show();
}

// Select All logic
document.getElementById('selectAllAdd').addEventListener('change', function() {
    document.querySelectorAll('.add-p-checkbox').forEach(cb => cb.checked = this.checked);
});

document.getElementById('selectAllEdit').addEventListener('change', function() {
    document.querySelectorAll('.edit-p-checkbox').forEach(cb => cb.checked = this.checked);
});
</script>

<?php
$content = ob_get_clean();
renderAdminPage($content, $title);
?>
