<?php
// Prevent direct web access
if (php_sapi_name() !== 'cli') {
    http_response_code(403);
    exit('Forbidden');
}

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

$processed = 0;
$wins = 0;
$losses = 0;

// Get trading settings once
$settingsSql = "SELECT setting_name, setting_value FROM trading_settings";
$settingsResult = mysqli_query($conn, $settingsSql);
$settings = [];
while ($row = mysqli_fetch_assoc($settingsResult)) {
    $settings[$row['setting_name']] = $row['setting_value'];
}

// Fetch all expired running trades
$expiredSql = "SELECT t.*, u.balance as user_balance 
    FROM trades t 
    JOIN users u ON t.user_id = u.id 
    WHERE t.status = 'running' 
    AND t.expires_at <= NOW() 
    ORDER BY t.expires_at ASC 
    LIMIT 100";

$expiredResult = mysqli_query($conn, $expiredSql);

if (!$expiredResult) {
    error_log("Settle trades cron error: " . mysqli_error($conn));
    exit(1);
}

while ($trade = mysqli_fetch_assoc($expiredResult)) {
    $tradeId = intval($trade['id']);
    $userId = intval($trade['user_id']);
    $amount = floatval($trade['amount']);
    $entryPrice = floatval($trade['entry_price']);
    
    // Determine outcome
    $isWin = false;
    if (isset($settings['win_rate_enabled']) && $settings['win_rate_enabled'] == '1') {
        $winRate = intval($settings['admin_win_rate'] ?? 20);
        $isWin = mt_rand(1, 100) <= $winRate;
    } else {
        $isWin = mt_rand(1, 100) <= 20;
    }
    
    // Calculate prices and P&L
    $priceMovement = mt_rand(10, 50) / 10000; // 0.1% - 0.5% movement
    $exitPrice = $isWin ? $entryPrice * (1 + $priceMovement) : $entryPrice * (1 - $priceMovement);
    $pnl = $isWin ? ($amount * 0.85) : -$amount;
    $status = $isWin ? 'win' : 'loss';
    
    // Start transaction
    mysqli_begin_transaction($conn);
    
    try {
        // Update trade record
        $updateTrade = "UPDATE trades SET 
            status = '$status',
            exit_price = $exitPrice,
            pnl = $pnl,
            closed_at = NOW()
            WHERE id = $tradeId AND status = 'running'";
        
        if (!mysqli_query($conn, $updateTrade)) {
            throw new Exception("Failed to update trade: " . mysqli_error($conn));
        }
        
        // Update user stats
        $updateStats = "INSERT INTO user_trading_stats 
            (user_id, total_trades, win_count, loss_count, total_pnl) 
            VALUES ($userId, 1, " . ($isWin ? 1 : 0) . ", " . ($isWin ? 0 : 1) . ", $pnl)
            ON DUPLICATE KEY UPDATE 
            total_trades = total_trades + 1,
            win_count = win_count + " . ($isWin ? 1 : 0) . ",
            loss_count = loss_count + " . ($isWin ? 0 : 1) . ",
            total_pnl = total_pnl + $pnl";
        
        if (!mysqli_query($conn, $updateStats)) {
            throw new Exception("Failed to update stats: " . mysqli_error($conn));
        }
        
        // If win, credit balance + profit
        if ($isWin) {
            $returnAmount = $amount + $pnl;
            $updateBalance = "UPDATE users 
                SET balance = balance + $returnAmount, 
                    profit = profit + $pnl 
                WHERE id = $userId";
            
            if (!mysqli_query($conn, $updateBalance)) {
                throw new Exception("Failed to credit balance: " . mysqli_error($conn));
            }
        }
        // If loss, stake already deducted - no action needed
        
        mysqli_commit($conn);
        $processed++;
        
        if ($isWin) {
            $wins++;
        } else {
            $losses++;
        }
        
    } catch (Exception $e) {
        mysqli_rollback($conn);
        error_log("Trade settlement failed for ID $tradeId: " . $e->getMessage());
    }
}

// Log completion
$logMessage = date('Y-m-d H:i:s') . " - Processed: $processed (Wins: $wins, Losses: $losses)";
error_log($logMessage);

// Optional: Write to custom log file
$logFile = __DIR__ . '/settle_trades.log';
file_put_contents($logFile, $logMessage . PHP_EOL, FILE_APPEND | LOCK_EX);

echo $logMessage . PHP_EOL;