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

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

$user_id = $_SESSION['user_id'];
$data = json_decode(file_get_contents('php://input'), true);

if (!$data) {
    echo json_encode(['success' => false, 'error' => 'Invalid data']);
    exit;
}

$symbol = $data['symbol']; // e.g., BTCUSDT
$type = $data['type']; // spot or futures
$side = $data['side']; // buy or sell
$order_type = $data['order_type']; // limit or market
$price = (float)$data['price'];
$amount = (float)$data['amount'];
$total = (float)$data['total'];
$leverage = (int)($data['leverage'] ?? 1);
$tp_price = isset($data['tp_price']) ? (float)$data['tp_price'] : null;
$sl_price = isset($data['sl_price']) ? (float)$data['sl_price'] : null;

try {
    $db = db();
    $db->beginTransaction();

    if ($type === 'spot') {
        if ($side === 'buy') {
            // Check USDT balance
            $stmt = $db->prepare("SELECT balance FROM users WHERE id = ? FOR UPDATE");
            $stmt->execute([$user_id]);
            $balance = (float)$stmt->fetchColumn();
            
            if ($balance < $total) {
                $db->rollBack();
                echo json_encode(['success' => false, 'error' => '余额不足 (USDT)']);
                exit;
            }
            
            // Deduct USDT
            $stmt = $db->prepare("UPDATE users SET balance = balance - ? WHERE id = ?");
            $stmt->execute([$total, $user_id]);
        } else {
            // Spot Sell: Check coin balance
            $coin_symbol = str_replace('USDT', '', $symbol);
            $stmt = $db->prepare("SELECT amount FROM user_assets WHERE user_id = ? AND symbol = ? FOR UPDATE");
            $stmt->execute([$user_id, $coin_symbol]);
            $asset_amount = (float)$stmt->fetchColumn();
            
            if ($asset_amount < $amount) {
                $db->rollBack();
                echo json_encode(['success' => false, 'error' => '资产余额不足 (' . $coin_symbol . ')']);
                exit;
            }
            
            // Deduct coin
            $stmt = $db->prepare("UPDATE user_assets SET amount = amount - ? WHERE user_id = ? AND symbol = ?");
            $stmt->execute([$amount, $user_id, $coin_symbol]);
        }
    } else {
        // Futures: Deduct margin (USDT)
        $margin = $total / $leverage;
        $stmt = $db->prepare("SELECT balance FROM users WHERE id = ? FOR UPDATE");
        $stmt->execute([$user_id]);
        $balance = (float)$stmt->fetchColumn();
        
        if ($balance < $margin) {
            $db->rollBack();
            echo json_encode(['success' => false, 'error' => '余额不足 (USDT)']);
            exit;
        }
        
        $stmt = $db->prepare("UPDATE users SET balance = balance - ? WHERE id = ?");
        $stmt->execute([$margin, $user_id]);
    }

    // Insert order
    $stmt = $db->prepare("INSERT INTO trading_orders (user_id, symbol, type, side, order_type, price, amount, total, leverage, tp_price, sl_price, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'open')");
    $stmt->execute([$user_id, $symbol, $type, $side, $order_type, $price, $amount, $total, $leverage, $tp_price, $sl_price]);

    $db->commit();
    echo json_encode(['success' => true]);

} catch (Exception $e) {
    if (isset($db)) $db->rollBack();
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}