<?php
// wingo_cron.php - Supports all modes simultaneously
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/config.php';

function getPeriodForTime($timestamp, $inv) {
    $total_seconds = (date('H', $timestamp) * 3600) + (date('i', $timestamp) * 60) + date('s', $timestamp);
    $issue_num = floor($total_seconds / $inv) + 1;
    return date('Ymd', $timestamp) . str_pad($issue_num, 4, '0', STR_PAD_LEFT);
}

function calculatePotentialPayout($num, $bet_map) {
    $payout = 0;
    $win_color = ($num == 0 || $num == 5) ? 'violet' : (($num % 2 == 0) ? 'red' : 'green');
    $win_size = ($num <= 4) ? 'small' : 'big';

    foreach ($bet_map as $bet_on => $total_amt) {
        if ((string)$bet_on === (string)$num) $payout += ($total_amt * 9); 
        if ($bet_on === 'big' && $win_size === 'big') $payout += ($total_amt * 2);
        if ($bet_on === 'small' && $win_size === 'small') $payout += ($total_amt * 2);
        if ($bet_on === 'violet' && $win_color === 'violet') $payout += ($total_amt * 4.5);
        if ($bet_on === 'red') {
            if (in_array($num, [2,4,6,8])) $payout += ($total_amt * 2);
            if ($num == 0) $payout += ($total_amt * 1.5);
        }
        if ($bet_on === 'green') {
            if (in_array($num, [1,3,7,9])) $payout += ($total_amt * 2);
            if ($num == 5) $payout += ($total_amt * 1.5);
        }
    }
    return $payout;
}

function checkBetWin($bet_on, $win_num, $win_color, $win_size) {
    if ((string)$bet_on === (string)$win_num) return true;
    if ($bet_on === 'big' && $win_size === 'big') return true;
    if ($bet_on === 'small' && $win_size === 'small') return true;
    if ($bet_on === 'green' && ($win_num % 2 != 0 || $win_num == 5)) return true;
    if ($bet_on === 'red' && ($win_num % 2 == 0 || $win_num == 0)) return true;
    if ($bet_on === 'violet' && ($win_num == 0 || $win_num == 5)) return true;
    return false;
}

// ── MODE DETECTION ──────────────────────────────────────────────────────────
// If ?mode= is specified, run just that mode. Otherwise, run all 4 modes.
$modes_to_process = isset($_GET['mode']) ? [$_GET['mode']] : ['30s', '1min', '3min', '5min'];

foreach ($modes_to_process as $mode) {
    if (!in_array($mode, ['30s', '1min', '3min', '5min'])) continue;

    if ($mode === '1min') {
        $interval = 60; $bets_table = 'wingo_bets_1min'; $results_table = 'wingo_results_1min';
    } elseif ($mode === '3min') {
        $interval = 180; $bets_table = 'wingo_bets_3min'; $results_table = 'wingo_results_3min';
    } elseif ($mode === '5min') {
        $interval = 300; $bets_table = 'wingo_bets_5min'; $results_table = 'wingo_results_5min';
    } else {
        $interval = 30; $bets_table = 'wingo_bets'; $results_table = 'wingo_results';
    }

    // Robust previous period calculation
    $timestamp = time();
    $seconds_into_period = $timestamp % $interval;
    $prev_period_time = $timestamp - $seconds_into_period - 1; 
    $prev_period = getPeriodForTime($prev_period_time, $interval);

    // Check if result already exists
    $check = $pdo->prepare("SELECT id FROM {$results_table} WHERE period = ?");
    $check->execute([$prev_period]);
    if ($check->fetch()) {
        echo "[{$mode}] Period {$prev_period} already processed.<br>\n";
        continue;
    }

    // 1. Get Bets & Calculate Total Wagered Amount
    $bets = $pdo->prepare("SELECT bet_on, SUM(amount) as total FROM {$bets_table} WHERE period = ? GROUP BY bet_on");
    $bets->execute([$prev_period]);
    $bet_map = [];
    $total_bet_amount = 0;
    
    foreach($bets->fetchAll() as $b) { 
        $bet_map[$b['bet_on']] = (float)$b['total']; 
        $total_bet_amount += (float)$b['total'];
    }

    // 2. Shared Pool
    $pool_st = $pdo->query("SELECT balance FROM wingo_pool ORDER BY id ASC LIMIT 1");
    $pool = $pool_st ? (float)$pool_st->fetchColumn() : 0;

    // ---> NEW TIERED SPLIT PROBABILITY LOGIC <---
    // Default (> 20 bets)
    $effective_pool = $pool;
    $force_loss_chance = 15; 
    $random_chance = 10;     

    if ($total_bet_amount > 0 && $total_bet_amount < 10) {
        $effective_pool = $pool / 2;
        $force_loss_chance = 20;
        $random_chance = 15;
    } elseif ($total_bet_amount >= 10 && $total_bet_amount <= 20) {
        $effective_pool = $pool / 1.5;
        $force_loss_chance = 20;
        $random_chance = 10;
    }

    $win_number = -1;

    // ─── ADMIN FORCE CHECK ─────────────────────────────────────────────────────
    $force_chk = $pdo->prepare("SELECT force_type, force_value FROM wingo_admin_force WHERE period = ?");
    $force_chk->execute([$prev_period]);
    $admin_force = $force_chk->fetch(PDO::FETCH_ASSOC);

    if ($admin_force) {
        $ft = strtolower($admin_force['force_type']);
        $fv = strtolower($admin_force['force_value']);

        if ($ft === 'number' && is_numeric($fv) && $fv >= 0 && $fv <= 9) {
            $win_number = (int)$fv;
        } elseif ($ft === 'size') {
            $fpool = ($fv === 'big') ? [5,6,7,8,9] : [0,1,2,3,4];
            $win_number = $fpool[array_rand($fpool)];
        } elseif ($ft === 'color') {
            if ($fv === 'red') $fpool = [2,4,6,8];
            elseif ($fv === 'green') $fpool = [1,3,7,9];
            elseif ($fv === 'violet') $fpool = [0,5];
            if (isset($fpool)) $win_number = $fpool[array_rand($fpool)];
        }
    }
    // ───────────────────────────────────────────────────────────────────────────

    if ($win_number === -1) {
        if (empty($bet_map)) {
            $win_number = rand(0, 9);
        } else {
            
            // Roll a number between 1 and 100 to determine the path
            $roll = rand(1, 100);
            
            // PATH 1: FORCE LOWEST PAYOUT
            if ($roll <= $force_loss_chance) {
                $min_cost = 999999999;
                $lowest_candidates = [];
                
                for ($n = 0; $n <= 9; $n++) {
                    $payout = calculatePotentialPayout($n, $bet_map);
                    if ($payout < $min_cost) {
                        $min_cost = $payout;
                        $lowest_candidates = [$n];
                    } elseif ($payout == $min_cost) {
                        $lowest_candidates[] = $n;
                    }
                }
                $win_number = $lowest_candidates[array_rand($lowest_candidates)];
                
            // PATH 2: PURE RANDOMNESS (Ignores bets and pool entirely)
            } elseif ($roll <= ($force_loss_chance + $random_chance)) {
                $win_number = rand(0, 9);
                
            // PATH 3: STANDARD LOGIC (70% Pool Algorithm)
            } else {
                $max_allowed_payout = $effective_pool * 0.70;
                $affordable_candidates = [];
                
                for ($n = 0; $n <= 9; $n++) {
                    $payout = calculatePotentialPayout($n, $bet_map);
                    if ($payout <= $max_allowed_payout) {
                        $affordable_candidates[] = ['num' => $n, 'payout' => $payout];
                    }
                }

                if (!empty($affordable_candidates)) {
                    usort($affordable_candidates, function($a, $b) {
                        return $b['payout'] <=> $a['payout'];
                    });
                    
                    $top_payout = $affordable_candidates[0]['payout'];
                    $winners = [];
                    foreach($affordable_candidates as $c) {
                        if ($c['payout'] == $top_payout) $winners[] = $c['num'];
                    }
                    $win_number = $winners[array_rand($winners)];
                } else {
                    // Fallback if nothing is affordable under the new limits
                    $min_cost = 999999999;
                    $fallback_num = rand(0,9);
                    for($n = 0; $n <= 9; $n++){
                        $p = calculatePotentialPayout($n, $bet_map);
                        if($p < $min_cost){ $min_cost = $p; $fallback_num = $n; }
                    }
                    $win_number = $fallback_num;
                }
            }
        }
    }

    $color = ($win_number == 0) ? 'red-violet' : (($win_number == 5) ? 'green-violet' : (in_array($win_number, [1,3,7,9]) ? 'green' : 'red'));
    $size = ($win_number <= 4) ? 'small' : 'big';

    try {
        $pdo->beginTransaction();
        
        $pdo->prepare("INSERT INTO {$results_table} (period, number, color, size) VALUES (?,?,?,?)")
            ->execute([$prev_period, $win_number, $color, $size]);

        // Cleanup force entry so it doesn't pile up endlessly
        $pdo->prepare("DELETE FROM wingo_admin_force WHERE period = ?")->execute([$prev_period]);

        $all_bets_st = $pdo->prepare("SELECT * FROM {$bets_table} WHERE period = ? AND status='pending'");
        $all_bets_st->execute([$prev_period]);
        
        foreach($all_bets_st->fetchAll() as $bet) {
            if (checkBetWin($bet['bet_on'], $win_number, $color, $size)) {
                $multiplier = 1.97;
                if (is_numeric($bet['bet_on'])) $multiplier = 8.82;
                if ($bet['bet_on'] == 'violet') $multiplier = 4.41;
                if (($bet['bet_on'] == 'red' && $win_number == 0) || ($bet['bet_on'] == 'green' && $win_number == 5)) $multiplier = 1.47;
                
                $win_amt = $bet['amount'] * $multiplier;
                $pdo->prepare("UPDATE {$bets_table} SET status='win', payout=? WHERE id=?")->execute([$win_amt, $bet['id']]);
                $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id=?")->execute([$win_amt, $bet['user_id']]);
                $pdo->prepare("UPDATE wingo_pool SET balance = GREATEST(0, balance - ?) WHERE id=1")->execute([$win_amt]);
            } else {
                $pdo->prepare("UPDATE {$bets_table} SET status='loss' WHERE id=?")->execute([$bet['id']]);
            }
        }
        
        $pdo->commit();
        echo "[{$mode}] Processed Period {$prev_period}. Winning Number: {$win_number}<br>\n";
    } catch (Exception $e) {
        if($pdo->inTransaction()) $pdo->rollBack();
        echo "[{$mode}] Error: " . $e->getMessage() . "<br>\n";
    }
}