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

if (isset($_POST['action']) && isset($_POST['order_id'])) {
    $oid = $_POST['order_id'];
    $action = $_POST['action'];
    
    $orderStmt = $pdo->prepare("SELECT * FROM trading_orders WHERE id = ?");
    $orderStmt->execute([$oid]);
    $order = $orderStmt->fetch();
    
    if ($order && $order['status'] == 'open') {
        $user_id = $order['user_id'];
        $symbol = $order['symbol'];
        $coin_symbol = str_replace('USDT', '', $symbol);
        
        if ($action == 'approve') {
            // "WIN": Approve and settle
            if ($order['side'] == 'buy') {
                $stmt = $pdo->prepare("INSERT INTO user_assets (user_id, symbol, amount) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE amount = amount + ?");
                $stmt->execute([$user_id, $coin_symbol, $order['amount'], $order['amount']]);
            } else {
                $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?")->execute([$order['total'], $user_id]);
            }
            $pdo->prepare("UPDATE trading_orders SET status = 'closed', admin_status = 'approved', win_loss = 'win' WHERE id = ?")->execute([$oid]);
        } elseif ($action == 'reject') {
            // "LOSS": Reject. No assets returned.
            $pdo->prepare("UPDATE trading_orders SET status = 'cancelled', admin_status = 'rejected', win_loss = 'loss' WHERE id = ?")->execute([$oid]);
        }
    }
}

$orders = $pdo->query("SELECT o.*, u.username, u.uid FROM trading_orders o JOIN users u ON o.user_id = u.id WHERE o.type = 'spot' ORDER BY o.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="../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: #FFFFFF; border-right: 1px solid #EAECEF; padding: 1rem; }
        .main-content { flex: 1; padding: 2rem; background: #FFFFFF; color: #1E2329; }
        .menu-item { padding: 12px; color: #474D57; text-decoration: none; display: flex; align-items: center; gap: 10px; border-radius: 4px; margin-bottom: 5px; }
        .menu-item:hover, .menu-item.active { background: #F5F5F5; color: #F0B90B; }
        .badge { background: #F6465D; 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 #EAECEF; font-size: 0.85rem; color: #1E2329; }
        .btn-sm { padding: 5px 10px; font-size: 0.75rem; border-radius: 4px; cursor: pointer; border: none; margin-right: 5px; }
        .btn-approve { background: #00c087; color: white; }
        .btn-reject { background: #f6465d; color: white; }
        .back-btn { color: #707A8A; text-decoration: none; font-size: 0.9rem; margin-bottom: 20px; display: inline-block; }
        .status-badge { padding: 2px 6px; border-radius: 4px; font-size: 0.75rem; }
        .status-open { background: #fff3cd; color: #856404; }
        .status-closed { background: #d4edda; color: #155724; }
        .status-cancelled { background: #f8d7da; color: #721c24; }
    </style>
</head>
<body style="background: white;">
<div class="admin-layout">
    <div class="sidebar">
        <h3 style="color: #1E2329; margin-bottom: 2rem;">NovaEx 管理员</h3>
        <a href="index.php" class="menu-item"><i class="fas fa-chart-pie"></i> 仪表盘</a>
        <a href="users.php" class="menu-item"><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="options_orders.php" class="menu-item"><i class="fas fa-clock"></i> 秒合约</a>
        <a href="spot_orders.php" class="menu-item active"><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">
        <a href="index.php" class="back-btn"><i class="fas fa-arrow-left"></i> 返回</a>
        <h2 style="color: #1E2329;">现货交易管理 (后台控赢/亏)</h2>
        <p style="color: #707A8A; font-size: 0.9rem;">提示：同意即为用户盈（得币/得USDT）；拒绝即为用户亏（资产不退）。</p>
        
        <table class="table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>用户</th>
                    <th>币对</th>
                    <th>方向</th>
                    <th>类型</th>
                    <th>价格</th>
                    <th>数量</th>
                    <th>总额</th>
                    <th>状态</th>
                    <th>结果</th>
                    <th>时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($orders as $o): ?>
                <tr>
                    <td><?php echo $o['id']; ?></td>
                    <td><?php echo htmlspecialchars($o['username']); ?> (<?php echo $o['uid']; ?>)</td>
                    <td><?php echo $o['symbol']; ?></td>
                    <td style="color: <?php echo $o['side'] == 'buy' ? '#00c087' : '#f6465d'; ?>">
                        <?php echo $o['side'] == 'buy' ? '买入' : '卖出'; ?>
                    </td>
                    <td><?php echo $o['order_type'] == 'market' ? '市价' : '限价'; ?></td>
                    <td><?php echo number_format($o['price'], 4); ?></td>
                    <td><?php echo number_format($o['amount'], 4); ?></td>
                    <td><?php echo number_format($o['total'], 4); ?> USDT</td>
                    <td>
                        <span class="status-badge status-<?php echo $o['status']; ?>">
                            <?php echo $o['status'] == 'open' ? '进行中' : ($o['status'] == 'closed' ? '已完成' : '已取消'); ?>
                        </span>
                    </td>
                    <td>
                        <?php if($o['win_loss'] == 'win'): ?>
                            <span style="color: #00c087;">盈利</span>
                        <?php elseif($o['win_loss'] == 'loss'): ?>
                            <span style="color: #f6465d;">亏损</span>
                        <?php else: ?>
                            --
                        <?php endif; ?>
                    </td>
                    <td><?php echo $o['created_at']; ?></td>
                    <td>
                        <?php if($o['status'] == 'open'): ?>
                        <form method="POST" style="display: inline;">
                            <input type="hidden" name="order_id" value="<?php echo $o['id']; ?>">
                            <button type="submit" name="action" value="approve" class="btn-sm btn-approve">控赢</button>
                            <button type="submit" name="action" value="reject" class="btn-sm btn-reject">控亏</button>
                        </form>
                        <?php else: ?>
                            --
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
</body>
</html>