55 lines
1.6 KiB
PHP
55 lines
1.6 KiB
PHP
<?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' => 'Order not found or already processed']);
|
|
exit;
|
|
}
|
|
|
|
// Update status
|
|
$stmt = $db->prepare("UPDATE trading_orders SET status = 'cancelled' WHERE id = ?");
|
|
$stmt->execute([$order_id]);
|
|
|
|
// Refund balance (simplified: return the total/cost to balance)
|
|
$cost = ($order['type'] === 'futures') ? ($order['total'] / $order['leverage']) : ($order['side'] === 'buy' ? $order['total'] : 0);
|
|
|
|
if ($cost > 0) {
|
|
$stmt = $db->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
|
|
$stmt->execute([$cost, $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()]);
|
|
}
|