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

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

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Please login first.']);
    exit;
}

$userId = $_SESSION['user_id'];
$symbol = $_POST['symbol'] ?? '';
$side = $_POST['side'] ?? ''; // buy/sell
$type = $_POST['type'] ?? 'spot'; // spot/contract
$price = floatval($_POST['price'] ?? 0);
$amount = floatval($_POST['amount'] ?? 0);

if ($amount <= 0 || $price <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid amount or price.']);
    exit;
}

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

    // Fetch user balance
    $stmt = $pdo->prepare("SELECT balance_usdt FROM users WHERE id = ? FOR UPDATE");
    $stmt->execute([$userId]);
    $user = $stmt->fetch();

    $totalCost = $price * $amount;

    if ($type === 'spot') {
        if ($side === 'buy') {
            if ($user['balance_usdt'] < $totalCost) {
                echo json_encode(['success' => false, 'message' => 'Insufficient USDT balance.']);
                $pdo->rollBack();
                exit;
            }
            // Deduct USDT
            $stmt = $pdo->prepare("UPDATE users SET balance_usdt = balance_usdt - ? WHERE id = ?");
            $stmt->execute([$totalCost, $userId]);
            
            // Record Order
            $stmt = $pdo->prepare("INSERT INTO spot_orders (user_id, symbol, side, type, price, amount, status) VALUES (?, ?, 'buy', 'limit', ?, ?, 'filled')");
            $stmt->execute([$userId, $symbol, $price, $amount]);
        } else {
            // Sell logic (simplified: assuming user has enough coin for now)
            $stmt = $pdo->prepare("UPDATE users SET balance_usdt = balance_usdt + ? WHERE id = ?");
            $stmt->execute([$totalCost, $userId]);
            
            $stmt = $pdo->prepare("INSERT INTO spot_orders (user_id, symbol, side, type, price, amount, status) VALUES (?, ?, 'sell', 'limit', ?, ?, 'filled')");
            $stmt->execute([$userId, $symbol, $price, $amount]);
        }
    } else {
        // Contract logic
        $margin = $totalCost / 10; // Assuming 10x leverage for simulation
        if ($side === 'buy') { // Long
             if ($user['balance_usdt'] < $margin) {
                echo json_encode(['success' => false, 'message' => 'Insufficient margin.']);
                $pdo->rollBack();
                exit;
            }
            $stmt = $pdo->prepare("UPDATE users SET balance_usdt = balance_usdt - ? WHERE id = ?");
            $stmt->execute([$margin, $userId]);

            $stmt = $pdo->prepare("INSERT INTO contract_positions (user_id, symbol, side, leverage, entry_price, size, margin, status) VALUES (?, ?, 'long', 10, ?, ?, ?, 'active')");
            $stmt->execute([$userId, $symbol, $price, $amount, $margin]);
        } else { // Short
             if ($user['balance_usdt'] < $margin) {
                echo json_encode(['success' => false, 'message' => 'Insufficient margin.']);
                $pdo->rollBack();
                exit;
            }
            $stmt = $pdo->prepare("UPDATE users SET balance_usdt = balance_usdt - ? WHERE id = ?");
            $stmt->execute([$margin, $userId]);

            $stmt = $pdo->prepare("INSERT INTO contract_positions (user_id, symbol, side, leverage, entry_price, size, margin, status) VALUES (?, ?, 'short', 10, ?, ?, ?, 'active')");
            $stmt->execute([$userId, $symbol, $price, $amount, $margin]);
        }
    }

    $pdo->commit();
    echo json_encode(['success' => true, 'message' => 'Order processed.']);

} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    echo json_encode(['success' => false, 'message' => 'System error: ' . $e->getMessage()]);
}
