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

// Handle Actions
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] == 'add_user') {
        $username = $_POST['username'];
        $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
        $uid = str_pad(mt_rand(0, 999999), 6, '0', STR_PAD_LEFT);
        $pdo->prepare("INSERT INTO users (uid, username, password, balance, credit_score) VALUES (?, ?, ?, ?, ?)")
            ->execute([$uid, $username, $password, $_POST['balance'] ?? 0, $_POST['credit_score'] ?? 80]);
    } elseif (isset($_POST['user_id'])) {
        $uid = $_POST['user_id'];
        if ($_POST['action'] == 'update_user') {
            $score = $_POST['score'];
            $balance = $_POST['balance'];
            $win_loss = $_POST['win_loss_control'];
            $status = $_POST['status'];
            
            $sql = "UPDATE users SET credit_score = ?, balance = ?, win_loss_control = ?, status = ? WHERE id = ?";
            $params = [$score, $balance, $win_loss, $status, $uid];
            
            if (!empty($_POST['password'])) {
                $sql = "UPDATE users SET credit_score = ?, balance = ?, win_loss_control = ?, status = ?, password = ? WHERE id = ?";
                $params = [$score, $balance, $win_loss, $status, password_hash($_POST['password'], PASSWORD_DEFAULT), $uid];
            }
            $pdo->prepare($sql)->execute($params);
        } elseif ($_POST['action'] == 'delete_user') {
            $pdo->prepare("DELETE FROM users WHERE id = ?")->execute([$uid]);
        } elseif ($_POST['action'] == 'toggle_status') {
            $user = $pdo->prepare("SELECT status FROM users WHERE id = ?");
            $user->execute([$uid]);
            $new_status = ($user->fetchColumn() == 'active' ? 'disabled' : 'active');
            $pdo->prepare("UPDATE users SET status = ? WHERE id = ?")->execute([$new_status, $uid]);
        }
    }
}

$users = $pdo->query("SELECT * FROM users 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="icon" type="image/png" href="../assets/pasted-20260211-152742-c4035b1b.png">
    <link rel="stylesheet" href="../assets/css/custom.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .admin-layout { display: flex; min-height: 100vh; }
        .sidebar { width: 250px; background: #1E2329; border-right: 1px solid #2B3139; padding: 1rem; }
        .main-content { flex: 1; padding: 2rem; background: #0B0E11; color: white; }
        .menu-item { padding: 12px; color: #848E9C; text-decoration: none; display: flex; align-items: center; gap: 10px; border-radius: 4px; margin-bottom: 5px; }
        .menu-item:hover, .menu-item.active { background: #2B3139; color: white; }
        .badge { background: var(--danger-color); color: white; border-radius: 10px; padding: 2px 8px; font-size: 0.7rem; margin-left: auto; }
        .table { width: 100%; border-collapse: collapse; margin-top: 1rem; }
        .table th, .table td { padding: 12px; text-align: left; border-bottom: 1px solid #2B3139; font-size: 0.85rem; }
        .btn-sm { padding: 5px 10px; font-size: 0.75rem; border-radius: 4px; cursor: pointer; border: none; text-decoration: none; display: inline-block; }
        .btn-edit { background: #f0b90b; color: #000; }
        .btn-delete { background: #f6465d; color: white; }
        .btn-status { background: #5e6673; color: white; }
        .btn-add { background: #00c087; color: white; padding: 10px 20px; border-radius: 4px; border: none; cursor: pointer; margin-bottom: 20px; }
        
        .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); z-index: 1000; }
        .modal-content { background: #1E2329; width: 500px; margin: 50px auto; padding: 30px; border-radius: 8px; border: 1px solid #2B3139; }
        .form-group { margin-bottom: 15px; }
        .form-group label { display: block; margin-bottom: 5px; color: #848E9C; }
        .form-group input, .form-group select { width: 100%; padding: 8px; background: #0B0E11; border: 1px solid #2B3139; color: white; border-radius: 4px; }
        .modal-footer { margin-top: 20px; text-align: right; }
        
        .header-actions { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
        .back-btn { color: #848E9C; text-decoration: none; font-size: 0.9rem; }
        .back-btn:hover { color: white; }
        .admin-logo { width: 200px; height: 80px; object-fit: contain; }
    </style>
</head>
<body>
<div class="admin-layout">
    <div class="sidebar">
        <div style="display: flex; flex-direction: column; align-items: center; margin-bottom: 2rem; gap: 10px;">
            <img src="../assets/pasted-20260211-152742-c4035b1b.png" alt="Logo" class="admin-logo">
            <div style="color: white; font-weight: bold; font-size: 0.9rem;">NovaEx 管理员</div>
        </div>
        <a href="index.php" class="menu-item"><i class="fas fa-chart-pie"></i> 仪表盘</a>
        <a href="users.php" class="menu-item active"><i class="fas fa-users"></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-headset"></i> 客服管理
            <?php if($unread_msgs > 0 || $pending_orders > 0): ?><span class="badge"><?php echo ($unread_msgs + $pending_orders); ?></span><?php endif; ?>
        </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="settings.php" class="menu-item"><i class="fas fa-cog"></i> 系统设置</a>
    </div>
    <div class="main-content">
        <div class="header-actions">
            <div>
                <a href="index.php" class="back-btn"><i class="fas fa-arrow-left"></i> 返回</a>
                <h2 style="margin-top: 10px;">用户管理</h2>
            </div>
            <button class="btn-add" onclick="showModal('addModal')"><i class="fas fa-user-plus"></i> 添加新用户</button>
        </div>

        <table class="table">
            <thead>
                <tr>
                    <th>UID</th>
                    <th>用户名</th>
                    <th>余额 (USDT)</th>
                    <th>信用分</th>
                    <th>盈亏控制</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($users as $u): ?>
                <tr>
                    <td><?php echo $u['uid']; ?></td>
                    <td><?php echo htmlspecialchars($u['username']); ?></td>
                    <td><b><?php echo number_format($u['balance'], 2); ?></b></td>
                    <td><?php echo $u['credit_score']; ?></td>
                    <td>
                        <?php 
                        if ($u['win_loss_control'] == 'win') echo '<span style="color: #00c087;">强制盈利</span>';
                        elseif ($u['win_loss_control'] == 'loss') echo '<span style="color: #f6465d;">强制亏损</span>';
                        else echo '<span style="color: #848e9c;">默认</span>';
                        ?>
                    </td>
                    <td><?php echo $u['status'] == 'active' ? '<span style="color: #00c087;">正常</span>' : '<span style="color: #f6465d;">已禁用</span>'; ?></td>
                    <td>
                        <button class="btn-sm btn-edit" onclick='editUser(<?php echo json_encode($u); ?>)'>编辑</button>
                        <form method="POST" style="display:inline;" onsubmit="return confirm('确定要删除此用户吗？')">
                            <input type="hidden" name="user_id" value="<?php echo $u['id']; ?>">
                            <input type="hidden" name="action" value="delete_user">
                            <button type="submit" class="btn-sm btn-delete">删除</button>
                        </form>
                        <form method="POST" style="display:inline;">
                            <input type="hidden" name="user_id" value="<?php echo $u['id']; ?>">
                            <input type="hidden" name="action" value="toggle_status">
                            <button type="submit" class="btn-sm btn-status"><?php echo $u['status'] == 'active' ? '禁用' : '启用'; ?></button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Add User Modal -->
<div id="addModal" class="modal">
    <div class="modal-content">
        <h3>添加新用户</h3>
        <form method="POST">
            <input type="hidden" name="action" value="add_user">
            <div class="form-group">
                <label>用户名</label>
                <input type="text" name="username" required>
            </div>
            <div class="form-group">
                <label>初始密码</label>
                <input type="text" name="password" required>
            </div>
            <div class="form-group">
                <label>初始余额 (USDT)</label>
                <input type="number" step="0.01" name="balance" value="0.00">
            </div>
            <div class="form-group">
                <label>信用分</label>
                <input type="number" name="credit_score" value="80">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn-sm btn-status" onclick="hideModal('addModal')">取消</button>
                <button type="submit" class="btn-sm btn-edit">确认添加</button>
            </div>
        </form>
    </div>
</div>

<!-- Edit User Modal -->
<div id="editModal" class="modal">
    <div class="modal-content">
        <h3>编辑用户信息</h3>
        <form method="POST">
            <input type="hidden" name="action" value="update_user">
            <input type="hidden" name="user_id" id="edit_user_id">
            <div class="form-group">
                <label>用户名 (不可更改)</label>
                <input type="text" id="edit_username" readonly style="opacity: 0.6;">
            </div>
            <div class="form-group">
                <label>修改密码 (不改留空)</label>
                <input type="text" name="password" placeholder="留空则不修改">
            </div>
            <div class="form-group">
                <label>余额 (USDT)</label>
                <input type="number" step="0.01" name="balance" id="edit_balance">
            </div>
            <div class="form-group">
                <label>信用分</label>
                <input type="number" name="score" id="edit_score">
            </div>
            <div class="form-group">
                <label>盈亏控制</label>
                <select name="win_loss_control" id="edit_win_loss">
                    <option value="none">正常 (默认)</option>
                    <option value="win">强制盈利 (Win)</option>
                    <option value="loss">强制亏损 (Loss)</option>
                </select>
            </div>
            <div class="form-group">
                <label>用户状态</label>
                <select name="status" id="edit_status">
                    <option value="active">正常 (Active)</option>
                    <option value="disabled">禁用 (Disabled)</option>
                </select>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn-sm btn-status" onclick="hideModal('editModal')">取消</button>
                <button type="submit" class="btn-sm btn-edit">保存修改</button>
            </div>
        </form>
    </div>
</div>

<script>
function showModal(id) { document.getElementById(id).style.display = 'block'; }
function hideModal(id) { document.getElementById(id).style.display = 'none'; }

function editUser(user) {
    document.getElementById('edit_user_id').value = user.id;
    document.getElementById('edit_username').value = user.username;
    document.getElementById('edit_balance').value = user.balance;
    document.getElementById('edit_score').value = user.credit_score;
    document.getElementById('edit_win_loss').value = user.win_loss_control;
    document.getElementById('edit_status').value = user.status;
    showModal('editModal');
}
</script>
</body>
</html>