<?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_user') {
        $username = $_POST['username'];
        $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
        $uid = 618120 + $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn() + mt_rand(1, 9);
        $balance = $_POST['balance'] ?? 0;
        $credit_score = $_POST['credit_score'] ?? 80;
        
        $stmt = $pdo->prepare("INSERT INTO users (uid, username, password, balance, credit_score, status) VALUES (?, ?, ?, ?, ?, 'active')");
        $stmt->execute([$uid, $username, $password, $balance, $credit_score]);
    } elseif ($action == 'update_user') {
        $id = $_POST['id'];
        $username = $_POST['username'];
        $balance = $_POST['balance'];
        $credit_score = $_POST['credit_score'];
        $win_loss = $_POST['win_loss_control'];
        $status = $_POST['status'];
        
        $sql = "UPDATE users SET username = ?, balance = ?, credit_score = ?, win_loss_control = ?, status = ? WHERE id = ?";
        $params = [$username, $balance, $credit_score, $win_loss, $status, $id];
        
        if (!empty($_POST['password'])) {
            $sql = "UPDATE users SET username = ?, balance = ?, credit_score = ?, win_loss_control = ?, status = ?, password = ? WHERE id = ?";
            $params = [$username, $balance, $credit_score, $win_loss, $status, password_hash($_POST['password'], PASSWORD_DEFAULT), $id];
        }
        $pdo->prepare($sql)->execute($params);
    } elseif ($action == 'adjust_balance') {
        $id = $_POST['id'];
        $type = $_POST['adjustment_type'];
        $amount = (float)$_POST['amount'];
        if ($type == 'up') {
            $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?")->execute([$amount, $id]);
        } else {
            $pdo->prepare("UPDATE users SET balance = balance - ? WHERE id = ?")->execute([$amount, $id]);
        }
    } elseif ($action == 'toggle_status') {
        $id = $_POST['id'];
        $user = $pdo->prepare("SELECT status FROM users WHERE id = ?");
        $user->execute([$id]);
        $new_status = ($user->fetchColumn() == 'active' ? 'disabled' : 'active');
        $pdo->prepare("UPDATE users SET status = ? WHERE id = ?")->execute([$new_status, $id]);
    }
    header("Location: users.php");
    exit;
}

$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();
$pending_kyc = $pdo->query("SELECT COUNT(*) FROM users WHERE kyc_status = 1")->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; }
        .btn-info { background: #2f80ed; color: white; }
        .btn-success { background: #00c087; color: white; }
        
        .status-badge { padding: 4px 8px; border-radius: 4px; font-size: 0.75rem; font-weight: bold; }
        .status-active { background: #e6fcf5; color: #00c087; }
        .status-disabled { background: #fff5f5; color: #f6465d; }
        
        .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: 550px; padding: 30px; border-radius: 16px; box-shadow: 0 20px 40px rgba(0,0,0,0.2); }
        .form-group { margin-bottom: 20px; }
        .form-group label { display: block; margin-bottom: 8px; font-weight: 600; color: #474d57; }
        .form-group input, .form-group select { width: 100%; padding: 10px 12px; border: 1px solid var(--border); border-radius: 8px; font-size: 1rem; outline: none; box-sizing: border-box; }
    </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 active"><i class="fas fa-users"></i> 用户管理</a>
        <a href="agents.php" class="menu-item"><i class="fas fa-user-shield"></i> 代理管理</a>
        <a href="kyc.php" class="menu-item"><i class="fas fa-id-card"></i> KYC 审核
            <?php if($pending_kyc > 0): ?><span class="badge"><?php echo $pending_kyc; ?></span><?php endif; ?>
        </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('addModal')"><i class="fas fa-user-plus"></i> 添加新用户</button>
        </div>

        <div class="card">
            <table class="table">
                <thead>
                    <tr>
                        <th>UID / 用户名</th>
                        <th>余额 (USDT)</th>
                        <th>信用分</th>
                        <th>输赢控制</th>
                        <th>状态</th>
                        <th>注册时间 / IP</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($users as $user): ?>
                    <tr>
                        <td>
                            <div style="font-weight: bold;"><?php echo $user['uid']; ?></div>
                            <div style="font-size: 0.8rem; color: #707a8a;"><?php echo htmlspecialchars($user['username']); ?></div>
                        </td>
                        <td><div style="color: #00c087; font-weight: bold;"><?php echo number_format($user['balance'], 2); ?></div></td>
                        <td><?php echo $user['credit_score']; ?></td>
                        <td>
                            <?php 
                            $wc = $user['win_loss_control'];
                            $labels = ['none' => '正常', 'win' => '起盈', 'loss' => '起亏'];
                            $colors = ['none' => '#474d57', 'win' => '#00c087', 'loss' => '#f6465d'];
                            echo "<span style='color: {$colors[$wc]}; font-weight: bold;'>{$labels[$wc]}</span>";
                            ?>
                        </td>
                        <td>
                            <span class="status-badge <?php echo $user['status'] == 'active' ? 'status-active' : 'status-disabled'; ?>">
                                <?php echo $user['status'] == 'active' ? '正常' : '已冻结'; ?>
                            </span>
                        </td>
                        <td>
                            <div style="font-size: 0.8rem;"><?php echo $user['created_at']; ?></div>
                            <div style="font-size: 0.75rem; color: #848e9c;"><?php echo $user['last_ip'] ?: '127.0.0.1'; ?></div>
                        </td>
                        <td>
                            <div style="display: flex; gap: 5px;">
                                <button class="btn btn-info btn-sm" onclick='editUser(<?php echo json_encode($user); ?>)'><i class="fas fa-edit"></i></button>
                                <button class="btn btn-success btn-sm" onclick="adjustBalance(<?php echo $user['id']; ?>, '<?php echo $user['username']; ?>')"><i class="fas fa-wallet"></i></button>
                                <form method="POST" style="display: inline;" onsubmit="return confirm('确定要执行此操作吗？')">
                                    <input type="hidden" name="id" value="<?php echo $user['id']; ?>">
                                    <input type="hidden" name="action" value="toggle_status">
                                    <button type="submit" class="btn btn-info btn-sm" title="锁定/解锁"><i class="fas fa-ban"></i></button>
                                </form>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Add User Modal -->
<div id="addModal" class="modal">
    <div class="modal-content">
        <h2>添加新用户</h2>
        <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="password" name="password" required>
            </div>
            <div class="form-group">
                <label>初始余额</label>
                <input type="number" name="balance" step="0.01" value="0.00">
            </div>
            <div style="display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px;">
                <button type="button" class="btn" onclick="hideModal('addModal')" style="background: #eee;">取消</button>
                <button type="submit" class="btn btn-primary">确定添加</button>
            </div>
        </form>
    </div>
</div>

<!-- Edit User Modal -->
<div id="editModal" class="modal">
    <div class="modal-content">
        <h2>编辑用户信息</h2>
        <form method="POST">
            <input type="hidden" name="action" value="update_user">
            <input type="hidden" name="id" id="edit-id">
            <div class="form-group">
                <label>用户名</label>
                <input type="text" name="username" id="edit-username" required>
            </div>
            <div class="form-group">
                <label>修改密码 (留空则不修改)</label>
                <input type="password" name="password" placeholder="******">
            </div>
            <div class="form-row" style="display: flex; gap: 15px;">
                <div class="form-group" style="flex: 1;">
                    <label>余额</label>
                    <input type="number" name="balance" id="edit-balance" step="0.01">
                </div>
                <div class="form-group" style="flex: 1;">
                    <label>信用分</label>
                    <input type="number" name="credit_score" id="edit-credit">
                </div>
            </div>
            <div class="form-row" style="display: flex; gap: 15px;">
                <div class="form-group" style="flex: 1;">
                    <label>输赢控制</label>
                    <select name="win_loss_control" id="edit-win-loss">
                        <option value="none">正常</option>
                        <option value="win">起盈</option>
                        <option value="loss">起亏</option>
                    </select>
                </div>
                <div class="form-group" style="flex: 1;">
                    <label>状态</label>
                    <select name="status" id="edit-status">
                        <option value="active">正常</option>
                        <option value="disabled">冻结</option>
                    </select>
                </div>
            </div>
            <div style="display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px;">
                <button type="button" class="btn" onclick="hideModal('editModal')" style="background: #eee;">取消</button>
                <button type="submit" class="btn btn-primary">保存修改</button>
            </div>
        </form>
    </div>
</div>

<!-- Adjust Balance Modal -->
<div id="balanceModal" class="modal">
    <div class="modal-content">
        <h2>资金调整 - <span id="adj-name"></span></h2>
        <form method="POST">
            <input type="hidden" name="action" value="adjust_balance">
            <input type="hidden" name="id" id="adj-id">
            <div class="form-group">
                <label>调整类型</label>
                <select name="adjustment_type">
                    <option value="up">增加余额 (+)</option>
                    <option value="down">减少余额 (-)</option>
                </select>
            </div>
            <div class="form-group">
                <label>调整金额 (USDT)</label>
                <input type="number" name="amount" step="0.01" required placeholder="0.00">
            </div>
            <div style="display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px;">
                <button type="button" class="btn" onclick="hideModal('balanceModal')" style="background: #eee;">取消</button>
                <button type="submit" class="btn btn-success">确认调整</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 editUser(user) {
        document.getElementById('edit-id').value = user.id;
        document.getElementById('edit-username').value = user.username;
        document.getElementById('edit-balance').value = user.balance;
        document.getElementById('edit-credit').value = user.credit_score;
        document.getElementById('edit-win-loss').value = user.win_loss_control;
        document.getElementById('edit-status').value = user.status;
        showModal('editModal');
    }
    
    function adjustBalance(id, name) {
        document.getElementById('adj-id').value = id;
        document.getElementById('adj-name').innerText = name;
        showModal('balanceModal');
    }
    
    window.onclick = function(event) {
        if (event.target.className === 'modal') {
            event.target.style.display = "none";
        }
    }
</script>
</body>
</html>