<?php
/**
 * SmartForex Engine - Custom Leverage Matrix & Position Execution Engine
 * Location: public_html/api/trade.php
 */

error_reporting(0);
ini_set('display_errors', 0);

define('DB_HOST', 'localhost');
define('DB_NAME', 'rakshita_relay');
define('DB_USER', 'rakshita_relay');
define('DB_PASS', 'rehman@169');

try {
    $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4", DB_USER, DB_PASS, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]);
} catch (PDOException $e) {
    echo json_encode(['status' => 'error', 'message' => 'Node connection offline']);
    exit;
}

session_start();
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized entry']);
    exit;
}

$user_id = $_SESSION['user_id'];
$action = $_POST['action'] ?? '';

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

// Helper function to calculate custom multiplier coefficients based on leverage rules
function getLeverageCoefficients($leverage, $current_price) {
    // Default fallback metrics (1x logic)
    $required_margin = $current_price;
    $point_multiplier = 10.00; // $1000 per 100 points = $10 per single point move

    switch ($leverage) {
        case 200:
            $required_margin = $current_price / 200;
            $point_multiplier = 0.50; // $50 per 100 points
            break;
        case 100:
            $required_margin = $current_price / 100;
            $point_multiplier = 1.00; // $100 per 100 points
            break;
        case 75:
            $required_margin = $current_price / 4; 
            $point_multiplier = 25.00; // Reset matrix scaling to original specifications
            break;
        case 50:
            $required_margin = $current_price / 2; // Yields 30000 margin constraint if price is 60k
            $point_multiplier = 50.00; // $5000 per 100 points
            break;
        case 25:
            $required_margin = $current_price / 1.333333; // Yields 45000 margin constraint if price is 60k
            $point_multiplier = 75.00; // $7500 per 100 points
            break;
        case 1:
        default:
            $required_margin = $current_price;
            $point_multiplier = 10.00; // $1000 per 100 points
            break;
    }

    return ['required_margin' => $required_margin, 'point_multiplier' => $point_multiplier];
}

// 1. OPEN NEW POSITION
if ($action === 'open') {
    $symbol = preg_replace("/[^A-Z0-9]/", "", strtoupper($_POST['symbol'] ?? 'BTCUSDT'));
    $type = ($_POST['type'] === 'sell') ? 'sell' : 'buy';
    $leverage = intval($_POST['leverage'] ?? 1);
    $tp = !empty($_POST['tp']) ? floatval($_POST['tp']) : null;
    $sl = !empty($_POST['sl']) ? floatval($_POST['sl']) : null;
    $current_price = floatval($_POST['current_price'] ?? 0);
    
    // Exact Lot Size read parameter capturing
    $lot_size = floatval($_POST['amount'] ?? 1); 
    if ($lot_size <= 0) { $lot_size = 1; }
// 🔥 MASTER DEMO BYPASS & LIVE BALANCE VERIFICATION LAYER
    if (isset($_SESSION['is_demo']) && $_SESSION['is_demo'] === true) {
        // Demo system variables inject automatic
        $user_balance = 10000000.00;
    } else {
        // Real Live User account verification pipeline
        $stmt = $pdo->prepare("SELECT balance FROM users WHERE id = ? FOR UPDATE");
        $stmt->execute([$user_id]);
        $user = $stmt->fetch();
        $user_balance = $user ? $user['balance'] : 0;
    }

    // Final balance check boundary execution
    if ($user_balance < $required_balance) {
        echo json_encode([
            'status' => 'error', 
            'message' => 'Insufficient margin balance. You need minimum $' . round($required_balance, 2) . ' to open this ' . $lot_size . ' Lot(s) position at ' . $leverage . 'x leverage.'
        ]);
        exit;
    }
    // FIXED CALCULATION: Dynamic Margin required = Baseline Margin per single lot * Total Lots selected
    $required_balance = $metrics['required_margin'] * $lot_size;

    // 🔥 HIGH-PRIORITY DEMO ENGINE SESSION OVERRIDE FOR TRADING PIPELINE
    if (isset($_SESSION['is_demo']) && $_SESSION['is_demo'] === true) {
        // Demo account skips DB check and gets structural permission automatically
        $user_balance = 10000000.00; 
        
        if ($user_balance < $required_balance) {
            echo json_encode([
                'status' => 'error', 
                'message' => 'Insufficient margin balance. You need minimum $' . round($required_balance, 2) . ' to open this ' . $lot_size . ' Lot(s) position.'
            ]);
            exit;
        }

        // Insert trade position record directly into log engine
        $insert = $pdo->prepare("INSERT INTO trades (user_id, symbol, type, order_type, amount, entry_price, current_price, take_profit, stop_loss, leverage, status) VALUES (?, ?, ?, 'market', ?, ?, ?, ?, ?, ?, 'open')");
        $insert->execute([$user_id, $symbol, $type, $lot_size, $current_price, $current_price, $tp, $sl, $leverage]);

        echo json_encode(['status' => 'success', 'message' => 'Trade position deployed with ' . $lot_size . ' Lot(s). Required Margin: $' . round($required_balance, 2)]);
        exit;
    }

    // Check Available Balance for LIVE User
    $stmt = $pdo->prepare("SELECT balance FROM users WHERE id = ? FOR UPDATE");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch();

    if (!$user || $user['balance'] < $required_balance) {
        echo json_encode([
            'status' => 'error', 
            'message' => 'Insufficient margin balance. You need minimum $' . round($required_balance, 2) . ' to open this ' . $lot_size . ' Lot(s) position at ' . $leverage . 'x leverage.'
        ]);
        exit;
    }

    // Deduct the dynamic required margin balance from live user profile
    $new_balance = $user['balance'] - $required_balance;
    $update = $pdo->prepare("UPDATE users SET balance = ?, total_trades = total_trades + 1 WHERE id = ?");
    $update->execute([$new_balance, $user_id]);

    // Insert trade position record for Live User
    $insert = $pdo->prepare("INSERT INTO trades (user_id, symbol, type, order_type, amount, entry_price, current_price, take_profit, stop_loss, leverage, status) VALUES (?, ?, ?, 'market', ?, ?, ?, ?, ?, ?, 'open')");
    $insert->execute([$user_id, $symbol, $type, $lot_size, $current_price, $current_price, $tp, $sl, $leverage]);

    echo json_encode(['status' => 'success', 'message' => 'Trade position deployed with ' . $lot_size . ' Lot(s). Required Margin: $' . round($required_balance, 2)]);
    exit;
}

// 2. CLOSE ACTIVE POSITION (WITH 20% REVENUE FEES)
if ($action === 'close') {
    $trade_id = intval($_POST['trade_id'] ?? 0);
    $close_price = floatval($_POST['close_price'] ?? 0);

    if ($trade_id <= 0 || $close_price <= 0) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid close request matrix']);
        exit;
    }

    // Fetch active trade frame explicitly
    $stmt = $pdo->prepare("SELECT * FROM trades WHERE id = ? AND user_id = ? AND status = 'open'");
    $stmt->execute([$trade_id, $user_id]);
    $trade = $stmt->fetch();

    if (!$trade) {
        echo json_encode(['status' => 'error', 'message' => 'Active position not found']);
        exit;
    }

    $entry = floatval($trade['entry_price']);
    $lot_size = floatval($trade['amount']); // This is now safely our clean Lot Size count
    $leverage = intval($trade['leverage']);
    
    // Fetch custom mathematical step constraints based on leverage settings
    $metrics = getLeverageCoefficients($leverage, $entry);
    
    // Reconstruction of required initial dynamic margin configuration mapping
    $initial_margin = $metrics['required_margin'] * $lot_size;
    $point_multiplier = $metrics['point_multiplier'] * $lot_size; // Scaling point coefficient weights via selected lots array

    // Absolute point displacement vector delta calculation
    $price_diff = $close_price - $entry;

    if ($trade['type'] === 'buy') {
        $pnl = $price_diff * $point_multiplier;
    } else {
        $pnl = ($price_diff * -1) * $point_multiplier;
    }

    // NEW FIXED BALANCE MAINTENANCE MATRIX (Fee only applies to net profit)
    $platform_fee = 0;
    if ($pnl > 0) {
        $platform_fee = $pnl * 0.20; // 20% platform fee applied strictly to won profit only
    }

    // Net Return = Original Margin + Profit - Platform Fee
    $net_return = $initial_margin + $pnl - $platform_fee;
    if ($net_return < 0) $net_return = 0; // Liquidation guard

    // 🔥 HIGH-PRIORITY DEMO ENGINE SYSTEM FOR CLOSING TRADES
    if (isset($_SESSION['is_demo']) && $_SESSION['is_demo'] === true) {
        // Demo account updates trade logs but skips live user database balance tampering
        $tradeUp = $pdo->prepare("UPDATE trades SET status = 'closed', close_price = ?, profit_loss = ?, closed_at = NOW() WHERE id = ?");
        $tradeUp->execute([$close_price, $pnl, $trade_id]);

        echo json_encode([
            'status' => 'success', 
            'message' => 'Position closed cleanly.', 
            'pnl' => round($pnl, 2),
            'fee_deducted' => round($platform_fee, 2),
            'net_returned' => round($net_return, 2)
        ]);
        exit;
    }

    // Update live user wallet balance & global analytics cleanly
    $pdo->beginTransaction();
    
    $stmtUser = $pdo->prepare("SELECT balance FROM users WHERE id = ? FOR UPDATE");
    $stmtUser->execute([$user_id]);
    $userBal = $stmtUser->fetch()['balance'];

    $final_balance = $userBal + $net_return;
    $win_inc = ($pnl > 0) ? 1 : 0;

    $userUp = $pdo->prepare("UPDATE users SET balance = ?, profit_loss = profit_loss + ?, winning_trades = winning_trades + ? WHERE id = ?");
    $userUp->execute([$final_balance, $pnl, $win_inc, $user_id]);

    $tradeUp = $pdo->prepare("UPDATE trades SET status = 'closed', close_price = ?, profit_loss = ?, closed_at = NOW() WHERE id = ?");
    $tradeUp->execute([$close_price, $pnl, $trade_id]);

    $pdo->commit();

    echo json_encode([
        'status' => 'success', 
        'message' => 'Position closed cleanly.', 
        'pnl' => round($pnl, 2),
        'fee_deducted' => round($platform_fee, 2),
        'net_returned' => round($net_return, 2)
    ]);
    exit;
}

echo json_encode(['status' => 'error', 'message' => 'Action protocol missing']);
exit;