<?php
require_once "auth.php";
require_once '../db/config.php';
$pdo = db();

// Handle Actions
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    
    if ($action == 'add_agent') {
        $username = $_POST['username'];
        $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
        $role = 'agent';
        $remark = $_POST['remark'] ?? '';
        $permissions = isset($_POST['perms']) ? json_encode($_POST['perms']) : '[]';
        
        $stmt = $pdo->prepare("INSERT INTO admins (username, password, role, permissions, remark) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([$username, $password, $role, $permissions, $remark]);
    } elseif ($action == 'update_agent') {
        $id = $_POST['id'];
        $username = $_POST['username'];
        $remark = $_POST['remark'] ?? '';
        $permissions = isset($_POST['perms']) ? json_encode($_POST['perms']) : '[]';
        
        $sql = "UPDATE admins SET username = ?, permissions = ?, remark = ? WHERE id = ?";
        $params = [$username, $permissions, $remark, $id];
        
        if (!empty($_POST['password'])) {
            $sql = "UPDATE admins SET username = ?, permissions = ?, remark = ?, password = ? WHERE id = ?";
            $params = [$username, $permissions, $remark, password_hash($_POST['password'], PASSWORD_DEFAULT), $id];
        }
        $pdo->prepare($sql)->execute($params);
    } elseif ($action == 'delete_agent') {
        $id = $_POST['id'];
        $pdo->prepare("DELETE FROM admins WHERE id = ? AND role = 'agent'")->execute([$id]);
    }
    header("Location: agents.php");
    exit;
}

$agents = $pdo->query("SELECT * FROM admins WHERE role = 'agent' ORDER BY id DESC")->fetchAll();
$unread_msgs = $pdo->query("SELECT COUNT(*) FROM messages WHERE sender = 'user' AND is_read = 0")->fetchColumn();
$pending_orders = $pdo->query("SELECT COUNT(*) FROM fiat_orders WHERE status IN ('matching', 'submitting')")->fetchColumn();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>代理管理 - NovaEx 管理后台</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        :root { --primary: #f0b90b; --bg: #ffffff; --text: #1e2329; --border: #eaecef; }
        body { background: #f4f6f9; color: var(--text); font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; margin: 0; }
        .admin-layout { display: flex; min-height: 100vh; }
        .sidebar { width: 250px; background: #ffffff; border-right: 1px solid var(--border); padding: 1.5rem; }
        .main-content { flex: 1; padding: 2rem; background: #ffffff; }
        .menu-item { padding: 12px 15px; color: #474d57; text-decoration: none; display: flex; align-items: center; gap: 12px; border-radius: 8px; margin-bottom: 8px; transition: 0.2s; }
        .menu-item:hover, .menu-item.active { background: #f5f5f5; color: var(--primary); font-weight: bold; }
        .badge { background: #f6465d; color: white; border-radius: 10px; padding: 2px 8px; font-size: 0.7rem; margin-left: auto; }
        
        .card { background: white; border-radius: 12px; border: 1px solid var(--border); padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); }
        .table { width: 100%; border-collapse: collapse; margin-top: 1.5rem; }
        .table th, .table td { padding: 15px; text-align: left; border-bottom: 1px solid var(--border); font-size: 0.9rem; }
        .table th { background: #f9fafb; color: #707a8a; font-weight: 600; text-transform: uppercase; font-size: 0.75rem; }
        
        .btn { padding: 8px 16px; border-radius: 6px; font-size: 0.85rem; border: none; cursor: pointer; font-weight: 500; transition: 0.2s; display: inline-flex; align-items: center; gap: 6px; text-decoration: none; }
        .btn-primary { background: var(--primary); color: black; }
        .btn-danger { background: #f6465d; color: white; }
        
        .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1000; align-items: center; justify-content: center; }
        .modal-content { background: white; width: 600px; padding: 30px; border-radius: 16px; box-shadow: 0 20px 40px rgba(0,0,0,0.2); max-height: 90vh; overflow-y: auto; }
        .form-group { margin-bottom: 20px; }
        .form-group label { display: block; margin-bottom: 8px; font-weight: 600; color: #474d57; }
        .form-group input, .form-group select, .form-group textarea { width: 100%; padding: 10px 12px; border: 1px solid var(--border); border-radius: 8px; font-size: 1rem; outline: none; box-sizing: border-box; }
        
        .perms-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 10px; border: 1px solid var(--border); padding: 15px; border-radius: 8px; }
        .perm-item { display: flex; align-items: center; gap: 8px; font-size: 0.85rem; }
    </style>
</head>
<body>
<div class="admin-layout">
    <div class="sidebar">
        <h2 style="color: var(--primary); margin-bottom: 2rem;">NovaEx Admin</h2>
        <a href="index.php" class="menu-item"><i class="fas fa-home"></i> 仪表盘</a>
        <a href="users.php" class="menu-item"><i class="fas fa-users"></i> 用户管理</a>
        <a href="agents.php" class="menu-item active"><i class="fas fa-user-shield"></i> 代理管理</a>
        <a href="kyc.php" class="menu-item"><i class="fas fa-id-card"></i> KYC 审核</a>
        <a href="chat.php" class="menu-item">
            <i class="fas fa-comments"></i> 客服管理
            <?php if($unread_msgs > 0 || $pending_orders > 0): ?><span class="badge"><?php echo ($unread_msgs + $pending_orders); ?></span><?php endif; ?>
        </a>
        <a href="options_orders.php" class="menu-item"><i class="fas fa-clock"></i> 秒合约</a>
        <a href="spot_orders.php" class="menu-item"><i class="fas fa-exchange-alt"></i> 现货交易</a>
        <a href="futures_orders.php" class="menu-item"><i class="fas fa-file-contract"></i> 合约交易</a>
        <a href="orders.php" class="menu-item"><i class="fas fa-wallet"></i> 充值记录</a>
        <a href="withdrawals.php" class="menu-item"><i class="fas fa-hand-holding-usd"></i> 提现记录</a>
        <a href="settings.php" class="menu-item"><i class="fas fa-cog"></i> 系统设置</a>
        <a href="logout.php" class="menu-item"><i class="fas fa-sign-out-alt"></i> 退出登录</a>
    </div>

    <div class="main-content">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px;">
            <h1>代理管理</h1>
            <button class="btn btn-primary" onclick="showModal('addAgentModal')"><i class="fas fa-plus"></i> 添加子管理员/代理</button>
        </div>

        <div class="card">
            <table class="table">
                <thead>
                    <tr>
                        <th>ID / 账号</th>
                        <th>角色</th>
                        <th>备注</th>
                        <th>权限范围</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($agents as $agent): ?>
                    <tr>
                        <td>
                            <div style="font-weight: bold;"><?php echo $agent['id']; ?></div>
                            <div style="font-size: 0.9rem; color: #474d57;"><?php echo htmlspecialchars($agent['username']); ?></div>
                        </td>
                        <td><span style="background: #eef2f7; padding: 4px 8px; border-radius: 4px; font-size: 0.8rem;">分管理代理</span></td>
                        <td style="color: #707a8a; font-size: 0.85rem;"><?php echo htmlspecialchars($agent['remark'] ?: '-'); ?></td>
                        <td>
                            <?php 
                            $perms = json_decode($agent['permissions'] ?: '[]', true);
                            if(empty($perms)) echo '<span style="color: #ccc;">无权限</span>';
                            else echo '<span style="font-size: 0.75rem; color: #00c087;">' . count($perms) . ' 项权限</span>';
                            ?>
                        </td>
                        <td style="font-size: 0.8rem; color: #848e9c;"><?php echo $agent['created_at']; ?></td>
                        <td>
                            <div style="display: flex; gap: 8px;">
                                <button class="btn btn-primary btn-sm" onclick='editAgent(<?php echo json_encode($agent); ?>)'><i class="fas fa-edit"></i></button>
                                <form method="POST" style="display: inline;" onsubmit="return confirm('确定要删除此代理吗？')">
                                    <input type="hidden" name="id" value="<?php echo $agent['id']; ?>">
                                    <input type="hidden" name="action" value="delete_agent">
                                    <button type="submit" class="btn btn-danger btn-sm"><i class="fas fa-trash"></i></button>
                                </form>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Add Agent Modal -->
<div id="addAgentModal" class="modal">
    <div class="modal-content">
        <div class="modal-header" style="display: flex; justify-content: space-between; margin-bottom: 20px;">
            <h3>添加代理管理员</h3>
            <i class="fas fa-times" onclick="hideModal('addAgentModal')" style="cursor: pointer;"></i>
        </div>
        <form method="POST">
            <input type="hidden" name="action" value="add_agent">
            <div class="form-group">
                <label>登录账号</label>
                <input type="text" name="username" required placeholder="输入代理登录用户名">
            </div>
            <div class="form-group">
                <label>登录密码</label>
                <input type="password" name="password" required placeholder="输入登录密码">
            </div>
            <div class="form-group">
                <label>代理备注</label>
                <textarea name="remark" rows="2" placeholder="备注该代理的线下明确信息..."></textarea>
            </div>
            <div class="form-group">
                <label>设置权限</label>
                <div class="perms-grid">
                    <div class="perm-item"><input type="checkbox" name="perms[]" value="users"> 用户管理</div>
                    <div class="perm-item"><input type="checkbox" name="perms[]" value="kyc"> KYC 审核</div>
                    <div class="perm-item"><input type="checkbox" name="perms[]" value="chat"> 客服管理</div>
                    <div class="perm-item"><input type="checkbox" name="perms[]" value="options"> 秒合约订单</div>
                    <div class="perm-item"><input type="checkbox" name="perms[]" value="spot"> 现货订单</div>
                    <div class="perm-item"><input type="checkbox" name="perms[]" value="futures"> 合约订单</div>
                    <div class="perm-item"><input type="checkbox" name="perms[]" value="orders"> 充值记录</div>
                </div>
            </div>
            <div style="text-align: right; margin-top: 20px;">
                <button type="button" class="btn" onclick="hideModal('addAgentModal')">取消</button>
                <button type="submit" class="btn btn-primary">确认添加</button>
            </div>
        </form>
    </div>
</div>

<!-- Edit Agent Modal -->
<div id="editAgentModal" class="modal">
    <div class="modal-content">
        <div class="modal-header" style="display: flex; justify-content: space-between; margin-bottom: 20px;">
            <h3>编辑代理权限</h3>
            <i class="fas fa-times" onclick="hideModal('editAgentModal')" style="cursor: pointer;"></i>
        </div>
        <form method="POST">
            <input type="hidden" name="action" value="update_agent">
            <input type="hidden" name="id" id="edit_agent_id">
            <div class="form-group">
                <label>登录账号</label>
                <input type="text" name="username" id="edit_agent_username" required>
            </div>
            <div class="form-group">
                <label>修改密码 (不填则不修改)</label>
                <input type="password" name="password" placeholder="留空保持原密码">
            </div>
            <div class="form-group">
                <label>代理备注</label>
                <textarea name="remark" id="edit_agent_remark" rows="2"></textarea>
            </div>
            <div class="form-group">
                <label>权限设置</label>
                <div class="perms-grid" id="edit_perms_grid">
                    <div class="perm-item"><input type="checkbox" name="perms[]" value="users"> 用户管理</div>
                    <div class="perm-item"><input type="checkbox" name="perms[]" value="kyc"> KYC 审核</div>
                    <div class="perm-item"><input type="checkbox" name="perms[]" value="chat"> 客服管理</div>
                    <div class="perm-item"><input type="checkbox" name="perms[]" value="options"> 秒合约订单</div>
                    <div class="perm-item"><input type="checkbox" name="perms[]" value="spot"> 现货订单</div>
                    <div class="perm-item"><input type="checkbox" name="perms[]" value="futures"> 合约订单</div>
                    <div class="perm-item"><input type="checkbox" name="perms[]" value="orders"> 充值记录</div>
                </div>
            </div>
            <div style="text-align: right; margin-top: 20px;">
                <button type="button" class="btn" onclick="hideModal('editAgentModal')">取消</button>
                <button type="submit" class="btn btn-primary">保存修改</button>
            </div>
        </form>
    </div>
</div>

<script>
    function showModal(id) { document.getElementById(id).style.display = 'flex'; }
    function hideModal(id) { document.getElementById(id).style.display = 'none'; }
    
    function editAgent(agent) {
        document.getElementById('edit_agent_id').value = agent.id;
        document.getElementById('edit_agent_username').value = agent.username;
        document.getElementById('edit_agent_remark').value = agent.remark || '';
        
        const perms = JSON.parse(agent.permissions || '[]');
        const checkboxes = document.querySelectorAll('#edit_perms_grid input[type="checkbox"]');
        checkboxes.forEach(cb => {
            cb.checked = perms.includes(cb.value);
        });
        
        showModal('editAgentModal');
    }
</script>
</body>
</html>