<?php


require_once "include/db.php";
mysqli_set_charset($conn, "utf8mb4");

$log = function($msg) {
    echo "[" . date('Y-m-d H:i:s') . "] " . $msg . "\n";
};

$log("=== AI BOT CRON STARTED ===");

// ==========================================
// FETCH ALL ACTIVE RUNNING BOTS
// ==========================================
$botsQuery = mysqli_query($conn, "SELECT bs.`id` as subscription_id, bs.`user_id`, bs.`bot_id`, bs.`allocated_balance`, 
                                   bs.`total_profit`, bs.`total_trades`, bs.`win_count`, bs.`config_json`,
                                   ab.`name` as bot_name, ab.`monthly_return`, ab.`win_rate`, ab.`risk_level`, ab.`trades_per_day`
                                   FROM `bot_subscriptions` bs
                                   JOIN `ai_trading_bots` ab ON bs.`bot_id` = ab.`id`
                                   WHERE bs.`status` = 'active' AND bs.`is_running` = 1");

if (!$botsQuery || mysqli_num_rows($botsQuery) === 0) {
    $log("No active bots found.");
    exit;
}

$activeBots = [];
while ($row = mysqli_fetch_assoc($botsQuery)) {
    $activeBots[] = [
        'subscription_id' => (int)$row['subscription_id'],
        'user_id' => (int)$row['user_id'],
        'bot_id' => (int)$row['bot_id'],
        'allocated_balance' => (float)$row['allocated_balance'],
        'total_profit' => (float)$row['total_profit'],
        'total_trades' => (int)$row['total_trades'],
        'win_count' => (int)$row['win_count'],
        'config_json' => json_decode($row['config_json'] ?? '{}', true),
        'bot_name' => $row['bot_name'],
        'monthly_return' => (float)$row['monthly_return'],
        'win_rate' => (int)$row['win_rate'],
        'risk_level' => $row['risk_level'],
        'trades_per_day' => (int)$row['trades_per_day']
    ];
}

$log("Found " . count($activeBots) . " active bot(s).");

// ==========================================
// SIMULATE TRADING FOR EACH BOT
// ==========================================
foreach ($activeBots as $bot) {
    $subId = $bot['subscription_id'];
    $userId = $bot['user_id'];
    
    // Determine number of trades for this cycle (based on trades_per_day / 288 = 5min intervals)
    $tradesPerCycle = max(1, ceil($bot['trades_per_day'] / 288));
    
    $cycleProfit = 0.00;
    $cycleWins = 0;
    $cycleTrades = 0;
    
    for ($i = 0; $i < $tradesPerCycle; $i++) {
        // Simulate trade outcome based on win rate
        $isWin = (mt_rand(1, 100) <= $bot['win_rate']);
        
        // Calculate profit/loss (0.1% to 0.8% per trade based on risk)
        $riskMultiplier = [
            'low' => 0.003,
            'moderate' => 0.005,
            'high' => 0.008
        ][$bot['risk_level']] ?? 0.005;
        
        $tradePercent = $riskMultiplier * (mt_rand(50, 150) / 100);
        $tradeAmount = $bot['allocated_balance'] * $tradePercent;
        
        if ($isWin) {
            $tradeProfit = $tradeAmount * (mt_rand(120, 180) / 100);
            $cycleProfit += $tradeProfit;
            $cycleWins++;
            $log("  [WIN] Bot #{$subId} | Profit: +$" . round($tradeProfit, 2));
        } else {
            $tradeLoss = $tradeAmount * (mt_rand(60, 100) / 100);
            $cycleProfit -= $tradeLoss;
            $log("  [LOSS] Bot #{$subId} | Loss: -$" . round($tradeLoss, 2));
        }
        
        $cycleTrades++;
        
        // Insert trade log
        $tradeLogStmt = mysqli_prepare($conn, "INSERT INTO `bot_trade_logs` 
            (`subscription_id`, `user_id`, `bot_id`, `trade_type`, `amount`, `profit_loss`, `status`, `created_at`) 
            VALUES (?, ?, ?, ?, ?, ?, ?, NOW())");
        
        $tradeType = $isWin ? 'win' : 'loss';
        mysqli_stmt_bind_param($tradeLogStmt, "iiiddds", $subId, $userId, $bot['bot_id'], $tradeAmount, 
                              ($isWin ? $tradeProfit : -$tradeLoss), $tradeType);
        mysqli_stmt_execute($tradeLogStmt);
        mysqli_stmt_close($tradeLogStmt);
    }
    
    // Update subscription stats
    $newTotalProfit = $bot['total_profit'] + $cycleProfit;
    $newTotalTrades = $bot['total_trades'] + $cycleTrades;
    $newWinCount = $bot['win_count'] + $cycleWins;
    
    $updateStmt = mysqli_prepare($conn, "UPDATE `bot_subscriptions` 
        SET `total_profit` = ?, `total_trades` = ?, `win_count` = ?, `last_trade_at` = NOW() 
        WHERE `id` = ?");
    mysqli_stmt_bind_param($updateStmt, "diii", $newTotalProfit, $newTotalTrades, $newWinCount, $subId);
    mysqli_stmt_execute($updateStmt);
    mysqli_stmt_close($updateStmt);
    
    // Update user balance if profit is positive and auto-compound is enabled
    $config = $bot['config_json'];
    if ($cycleProfit > 0 && isset($config['auto_compound']) && $config['auto_compound']) {
        $userBalanceStmt = mysqli_prepare($conn, "UPDATE `users` SET `balance` = `balance` + ? WHERE `id` = ?");
        mysqli_stmt_bind_param($userBalanceStmt, "di", $cycleProfit, $userId);
        mysqli_stmt_execute($userBalanceStmt);
        mysqli_stmt_close($userBalanceStmt);
        $log("  [COMPOUND] User #{$userId} credited $" . round($cycleProfit, 2));
    }
    
    $log("Bot #{$subId} ({$bot['bot_name']}) cycle complete. Net: $" . round($cycleProfit, 2));
}

$log("=== AI BOT CRON COMPLETED ===");
?>