<?php
session_start();
header('Content-Type: application/json');

require_once "../include/db.php";

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

$data = json_decode(file_get_contents('php://input'), true);
$userId = intval($_SESSION['user_id']);
$asset = mysqli_real_escape_string($conn, $data['asset'] ?? 'BTC/USD');
$amount = floatval($data['amount'] ?? 0);
$type = in_array($data['type'] ?? '', ['BUY', 'SELL']) ? $data['type'] : 'BUY';
$duration = intval($data['duration'] ?? 5);
$market = mysqli_real_escape_string($conn, $data['market'] ?? 'crypto');

// Validation based on market
$marketLimits = [
    'crypto' => ['min' => 10, 'max' => 50000],
    'forex' => ['min' => 10, 'max' => 100000],
    'stocks' => ['min' => 50, 'max' => 100000],
    'commodities' => ['min' => 25, 'max' => 50000]
];

$limits = $marketLimits[$market] ?? $marketLimits['crypto'];

if ($amount < $limits['min'] || $amount > $limits['max']) {
    echo json_encode(['success' => false, 'message' => "Amount must be between \${$limits['min']} and \${$limits['max']}"]);
    exit;
}

if (!in_array($duration, [1, 3, 5, 15, 30, 60, 120, 240, 480])) {
    echo json_encode(['success' => false, 'message' => 'Invalid duration']);
    exit;
}

// Check balance
$balSql = "SELECT balance FROM users WHERE id = $userId LIMIT 1";
$balResult = mysqli_query($conn, $balSql);
$user = mysqli_fetch_assoc($balResult);

if (!$user || $user['balance'] < $amount) {
    echo json_encode(['success' => false, 'message' => 'Insufficient balance']);
    exit;
}

// Get current simulated market price
$basePrices = [
    'BTC/USD' => 78814, 'ETH/USD' => 2346, 'SOL/USD' => 142.30, 'XRP/USD' => 0.62, 'ADA/USD' => 0.45, 'DOT/USD' => 7.20,
    'EUR/USD' => 1.0845, 'GBP/USD' => 1.2730, 'USD/JPY' => 151.45, 'AUD/USD' => 0.6520, 'USD/CHF' => 0.9050, 'EUR/GBP' => 0.8520,
    'AAPL' => 173.50, 'TSLA' => 175.20, 'GOOGL' => 165.80, 'MSFT' => 420.15, 'AMZN' => 180.30, 'NVDA' => 880.50,
    'GOLD' => 2325.40, 'SILVER' => 27.15, 'OIL' => 78.90, 'NATGAS' => 2.15, 'COPPER' => 4.55, 'PLATINUM' => 950.20
];

$basePrice = $basePrices[$asset] ?? 100;
// Add small randomization to simulate real market price at execution
$entryPrice = $basePrice * (0.9995 + mt_rand(0, 10) / 10000);

// Deduct amount from balance immediately (hold the stake)
$newBalance = $user['balance'] - $amount;
mysqli_query($conn, "UPDATE users SET balance = $newBalance WHERE id = $userId");

// Insert trade with status 'pending' - it will become 'running' after a brief delay
$tradeSql = "INSERT INTO trades 
    (user_id, asset, trade_type, amount, entry_price, market, duration, status, created_at, expires_at) 
    VALUES 
    ($userId, '$asset', '$type', $amount, $entryPrice, '$market', $duration, 'pending', NOW(), DATE_ADD(NOW(), INTERVAL $duration MINUTE))";

if (!mysqli_query($conn, $tradeSql)) {
    // Rollback balance if insert fails
    mysqli_query($conn, "UPDATE users SET balance = balance + $amount WHERE id = $userId");
    echo json_encode(['success' => false, 'message' => 'Trade execution failed']);
    exit;
}

$tradeId = mysqli_insert_id($conn);

// Return trade info - result will be determined at expiry
echo json_encode([
    'success' => true,
    'trade' => [
        'id' => $tradeId,
        'asset' => $asset,
        'trade_type' => $type,
        'amount' => $amount,
        'entry_price' => $entryPrice,
        'duration' => $duration,
        'market' => $market,
        'status' => 'pending',
        'created_at' => date('Y-m-d H:i:s')
    ],
    'new_balance' => $newBalance,
    'message' => "Trade placed! Expires in {$duration} minutes"
]);