<?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);
$order_id = $data['order_id'] ?? null;

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

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

    // Check if order exists and belongs to user and is open
    $stmt = $db->prepare("SELECT * FROM trading_orders WHERE id = ? AND user_id = ? AND status = 'open' FOR UPDATE");
    $stmt->execute([$order_id, $user_id]);
    $order = $stmt->fetch();

    if (!$order) {
        $db->rollBack();
        echo json_encode(['success' => false, 'error' => '订单未找到或已处理']);
        exit;
    }

    // Update status
    $stmt = $db->prepare("UPDATE trading_orders SET status = 'cancelled' WHERE id = ?");
    $stmt->execute([$order_id]);

    if ($order['type'] === 'spot') {
        if ($order['side'] === 'buy') {
            // Refund USDT
            $stmt = $db->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
            $stmt->execute([$order['total'], $user_id]);
        } else {
            // Refund coins
            $coin_symbol = str_replace('USDT', '', $order['symbol']);
            $stmt = $db->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 {
        // Futures: Refund margin
        $margin = $order['total'] / $order['leverage'];
        $stmt = $db->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
        $stmt->execute([$margin, $user_id]);
    }

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

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