<?php
require_once '../db/config.php';
session_start();
$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') {
            if ($order['side'] == 'buy') {
                // Buy approved: Add coins to user_assets
                $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 {
                // Sell approved: Add USDT to users balance
                $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' WHERE id = ?")->execute([$oid]);
        } elseif ($action == 'reject') {
            if ($order['side'] == 'buy') {
                // Buy rejected: Refund USDT to users balance
                $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?")->execute([$order['total'], $user_id]);
            } else {
                // Sell rejected: Refund coins to user_assets
                $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']]);
            }
            $pdo->prepare("UPDATE trading_orders SET status = 'cancelled', admin_status = 'rejected' 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: #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; }
        .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; }
    </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 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="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 strtoupper($o['order_type'] == 'limit' ? '限价' : '市价'); ?></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'], 2); ?></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 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']; ?>">
                            <input type="hidden" name="action" value="approve">
                            <button type="submit" class="btn-sm btn-approve">同意并结算</button>
                        </form>
                        <form method="POST" style="display:inline;">
                            <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">拒绝并取消</button>
                        </form>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
</body>
</html>