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

$faceValue = 10;

if (isset($_POST['action']) && isset($_POST['order_id'])) {
    $oid = $_POST['order_id'];
    $action = $_POST['action'];
    
    $orderStmt = $pdo->prepare("SELECT o.*, u.balance FROM trading_orders o JOIN users u ON o.user_id = u.id WHERE o.id = ?");
    $orderStmt->execute([$oid]);
    $order = $orderStmt->fetch();
    
    if ($order && $order['status'] == 'open') {
        $user_id = $order['user_id'];
        $margin = $order['total'] / $order['leverage'];
        
        if ($action == 'approve') {
            // Settle at TP price (or current price if tp not set, but here we assume admin uses the TP field as exit price)
            $exit_price = (float)($order['tp_price'] ?: $order['price']); 
            $entry_price = (float)$order['price'];
            $nominal = (float)$order['amount'] * $faceValue;
            
            $profit = 0;
            if ($order['side'] == 'buy') {
                $profit = ($exit_price / $entry_price - 1) * $nominal;
            } else {
                $profit = (1 - $exit_price / $entry_price) * $nominal;
            }
            
            $payout = $margin + $profit;
            if ($payout < 0) $payout = 0; // Negative equity handled as 0 payout (liquidation)
            
            $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?")->execute([$payout, $user_id]);
            $pdo->prepare("UPDATE trading_orders SET status = 'closed', admin_status = 'approved', win_loss = 'win' WHERE id = ?")->execute([$oid]);
        } elseif ($action == 'reject') {
            // Reject usually means loss/liquidation. No payout.
            $pdo->prepare("UPDATE trading_orders SET status = 'cancelled', admin_status = 'rejected', win_loss = 'loss' WHERE id = ?")->execute([$oid]);
        } elseif ($action == 'set_win_loss') {
            $win_loss = $_POST['win_loss'];
            $pdo->prepare("UPDATE trading_orders SET win_loss = ? WHERE id = ?")->execute([$win_loss, $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 = 'futures' 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: #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.8rem; }
        .btn-sm { padding: 5px 10px; font-size: 0.75rem; border-radius: 4px; cursor: pointer; border: none; }
        .btn-approve { background: #00c087; color: white; }
        .btn-reject { background: #f6465d; color: white; }
        .back-btn { color: #848E9C; text-decoration: none; font-size: 0.9rem; margin-bottom: 20px; display: inline-block; }
        .admin-logo { width: 200px; height: 80px; object-fit: contain; }
        select { background: #1e2329; border: 1px solid #2b3139; color: white; padding: 5px; border-radius: 4px; font-size: 0.75rem; }
    </style>
</head>
<body>
<div class="admin-layout">
    <div class="sidebar">
        <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 2rem;">
            <img src="../assets/pasted-20260211-152742-c4035b1b.png" alt="Logo" class="admin-logo">
            <h3 style="color: white; margin: 0;">NovaEx 管理员</h3>
        </div>
        <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="spot_orders.php" class="menu-item"><i class="fas fa-exchange-alt"></i> 现货交易</a>
        <a href="futures_orders.php" class="menu-item active"><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">
        <a href="index.php" class="back-btn"><i class="fas fa-arrow-left"></i> 返回</a>
        <h2>合约交易详情</h2>
        
        <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>
                </tr>
            </thead>
            <tbody>
                <?php foreach($orders as $o): ?>
                <tr>
                    <td>#<?php echo $o['id']; ?></td>
                    <td><?php echo htmlspecialchars($o['username']); ?></td>
                    <td><?php echo $o['symbol']; ?></td>
                    <td><span style="color: <?php echo $o['side'] == 'buy' ? '#00c087' : '#f6465d'; ?>"><?php echo strtoupper($o['side'] == 'buy' ? '做多' : '做空'); ?></span></td>
                    <td><?php echo $o['leverage']; ?>x</td>
                    <td><?php echo number_format($o['price'], 4); ?></td>
                    <td><?php echo number_format($o['tp_price'], 4); ?></td>
                    <td><?php echo number_format($o['total'] / $o['leverage'], 2); ?></td>
                    <td>
                        <form method="POST" style="display: flex; gap: 5px;">
                            <input type="hidden" name="order_id" value="<?php echo $o['id']; ?>">
                            <input type="hidden" name="action" value="set_win_loss">
                            <select name="win_loss" onchange="this.form.submit()">
                                <option value="none" <?php echo $o['win_loss'] == 'none' ? 'selected' : ''; ?>>正常</option>
                                <option value="win" <?php echo $o['win_loss'] == 'win' ? 'selected' : ''; ?>>控盈</option>
                                <option value="loss" <?php echo $o['win_loss'] == 'loss' ? 'selected' : ''; ?>>控亏</option>
                            </select>
                        </form>
                    </td>
                    <td>
                        <?php 
                        if ($o['status'] == 'open') echo '<span style="color: #f0b90b;">持有中</span>';
                        elseif ($o['status'] == 'closed') echo '<span style="color: #00c087;">已平仓</span>';
                        else echo '<span style="color: #848e9c;">已撤销</span>';
                        ?>
                    </td>
                    <td>
                        <?php if($o['status'] == 'open'): ?>
                        <div style="display: flex; gap: 5px;">
                            <form method="POST">
                                <input type="hidden" name="order_id" value="<?php echo $o['id']; ?>">
                                <input type="hidden" name="action" value="approve">
                                <button type="submit" class="btn-sm btn-approve" title="按退出价结算">同意结算</button>
                            </form>
                            <form method="POST">
                                <input type="hidden" name="order_id" value="<?php echo $o['id']; ?>">
                                <input type="hidden" name="action" value="reject">
                                <button type="submit" class="btn-sm btn-reject" title="按亏损处理">拒绝结算</button>
                            </form>
                        </div>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
</body>
</html>