<?php
/**
 * ============================================================
 * CRON JOB: Trade Settlement Engine
 * Run every minute via: * * * * * /usr/bin/php /home/theinter/public_html/app/account/cron_settle_trades.php
 * ============================================================
 */

// Adjust path to your db.php - go up one level if it's in app/include/
require_once __DIR__ . "include/db.php";

// Fetch admin win/loss probability settings
$settingsQuery = mysqli_query($conn, "SELECT `setting_key`, `setting_value` FROM `admin_settings` WHERE `setting_key` IN ('win_probability', 'loss_probability')");
$adminSettings = [];
while ($sRow = mysqli_fetch_assoc($settingsQuery)) {
    $adminSettings[$sRow['setting_key']] = (int)$sRow['setting_value'];
}
$winProbability = $adminSettings['win_probability'] ?? 30;
$lossProbability = $adminSettings['loss_probability'] ?? 70;

// Normalize probabilities
$totalProb = $winProbability + $lossProbability;
if ($totalProb != 100) {
    $winProbability = 30;
    $lossProbability = 70;
}

// Fetch expired open trades
$now = date('Y-m-d H:i:s');
$expiredQuery = mysqli_query($conn, "
    SELECT t.*, a.price as current_price 
    FROM `trades` t 
    LEFT JOIN `assets` a ON t.asset = a.symbol 
    WHERE t.status = 'open' 
    AND t.expires_at <= '$now'
    LIMIT 100
");

if (!$expiredQuery || mysqli_num_rows($expiredQuery) === 0) {
    exit;
}

while ($trade = mysqli_fetch_assoc($expiredQuery)) {
    $tradeId = (int)$trade['id'];
    $userId = (int)$trade['user_id'];
    $amount = (float)$trade['amount'];
    $entryPrice = (float)$trade['entry_price'];
    $currentPrice = (float)($trade['current_price'] ?? $entryPrice);
    $tradeType = strtolower($trade['trade_type']);
    $market = $trade['market'];
    
    // Admin-controlled win/loss determination
    $randomOutcome = mt_rand(1, 100);
    $isWin = ($randomOutcome <= $winProbability);
    
    $payoutRate = 0.85;
    
    if ($isWin) {
        $priceMovement = mt_rand(10, 50) / 10000;
        $status = 'won';
        
        if ($tradeType === 'buy') {
            $exitPrice = $entryPrice + $priceMovement;
        } else {
            $exitPrice = $entryPrice - $priceMovement;
        }
        
        $pnl = $amount * $payoutRate;
        
        if ($market === 'real') {
            $totalReturn = $amount + $pnl;
            mysqli_query($conn, "UPDATE `users` SET `balance` = `balance` + $totalReturn WHERE `id` = $userId");
        }
    } else {
        $priceMovement = mt_rand(10, 50) / 10000;
        $status = 'lost';
        
        if ($tradeType === 'buy') {
            $exitPrice = $entryPrice - $priceMovement;
        } else {
            $exitPrice = $entryPrice + $priceMovement;
        }
        
        $pnl = -$amount;
    }
    
    $exitPrice = round($exitPrice, 4);
    $pnl = round($pnl, 2);
    $closedAt = date('Y-m-d H:i:s');
    
    $updateStmt = mysqli_prepare($conn, "
        UPDATE `trades` 
        SET `exit_price` = ?, 
            `pnl` = ?, 
            `status` = ?, 
            `closed_at` = ? 
        WHERE `id` = ?
    ");
    mysqli_stmt_bind_param($updateStmt, "ddssi", $exitPrice, $pnl, $status, $closedAt, $tradeId);
    mysqli_stmt_execute($updateStmt);
    mysqli_stmt_close($updateStmt);
}

mysqli_close($conn);
?>