 
<?php
// 📦 Database Connection (PDO)
include "../includes/db.php";
 
// 🕒 Time Setup
date_default_timezone_set('Asia/Kolkata');
$current_time = date("H:i:s");
$today = date("Y-m-d");

echo "🗓️ Debug Date: Script thinks today is $today<br>";
echo "⏰ Current Time: $current_time<br><br>";

// 🎯 Fetch Active Markets with Auto Guessing Enabled and Not Marked as Holiday, Sorted by time_open
$markets_stmt = $db->query("SELECT * FROM games WHERE is_active = 1 AND auto_gues_status = 1 AND is_holiday = 0 ORDER BY time_open ASC");
$markets = $markets_stmt->fetchAll(PDO::FETCH_ASSOC);

if (count($markets) === 0) {
    echo "❌ No eligible markets to generate.";
    exit;
}

foreach ($markets as $market) {
    echo "<hr>";

    $market_name = $market['title'];
    $market_time = $market['time_open'];
    $market_timestamp = strtotime($market_time);
    $adjusted_market_time = $market_timestamp - 1800; // Subtract 30 mins
    $adjusted_market_time_display = date("h:i:s A", $adjusted_market_time);
    $current_timestamp = strtotime($current_time);
    $time_diff = $adjusted_market_time - $current_timestamp;
    $time_diff_min = round($time_diff / 60);

    echo "🕹️ Market: <strong>$market_name</strong><br>";
    echo "⏰ Market Time: $market_time<br>";
    echo "🕒 Adjusted Time to Post: $adjusted_market_time_display<br>";
    echo "📏 Time Diff: $time_diff_min minute(s)<br>";

    // ✅ Wider window: allow up to 30 mins before and 15 mins after adjusted time
    if ($time_diff > 1800 || $time_diff < -900) {
        echo "⏳ Skipping – I'll post in <strong>$time_diff_min minute(s)</strong> or already passed<br>";
        continue;
    }

    // 🔍 Check if Already Generated Today
    $check_stmt = $db->prepare("SELECT * FROM free_game WHERE market = ? AND date = ?");
    $check_stmt->execute([$market_name, $today]);
    $rows_found = $check_stmt->rowCount();

    echo "🔍 Already generated check for $market_name on $today: Found $rows_found rows<br>";

    if ($rows_found > 0) {
        echo "⚠️ Already generated today. Skipping.<br>";
        continue;
    }

    // 🔢 Generate Unique Open Digits
    $open_digits = range(0, 9);
    shuffle($open_digits);
    $open_digits = array_slice($open_digits, 0, 4);  // 4 unique digits

    // 🔄 Create Jodi Numbers
    $jodi = [
        "{$open_digits[0]}{$open_digits[1]}", "{$open_digits[1]}{$open_digits[0]}",
        "{$open_digits[1]}{$open_digits[2]}", "{$open_digits[2]}{$open_digits[1]}",
        "{$open_digits[2]}{$open_digits[3]}", "{$open_digits[3]}{$open_digits[2]}",
        "{$open_digits[3]}{$open_digits[0]}", "{$open_digits[0]}{$open_digits[3]}"
    ];
  
    // 📥 Fetch Panel Groups from DB
$panel_groups = [];

$stmt = $db->query("SELECT digit, panel_value FROM predefined_panels");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($rows as $row) {
    $digit = (int)$row['digit'];
    $panel_values = explode(",", $row['panel_value']);
    $panel_groups[$digit] = $panel_values;
}

    // 🎲 Generate 4 Unique Panel Numbers
    $panel = [];
    foreach ($open_digits as $digit) {
        do {
            $chosen = $panel_groups[$digit][array_rand($panel_groups[$digit])];
        } while (in_array($chosen, $panel));
        $panel[] = $chosen;
    }

    // 📝 Prepare Data for Insertion
    $open_str = implode(",", $open_digits);
    $jodi_str = implode(",", $jodi);
    $panel_str = implode(",", $panel);
    $generated_at = date("Y-m-d H:i:s");

    $insert_stmt = $db->prepare("INSERT INTO free_game (market, date, open, jodi, panel, generated_at) VALUES (?, ?, ?, ?, ?, ?)");
    $insert_success = $insert_stmt->execute([$market_name, $today, $open_str, $jodi_str, $panel_str, $generated_at]);

    if ($insert_success) {
        echo "✅ Generated for $market_name<br>";
        echo "🔢 Open: $open_str<br>";
        echo "🎯 Jodi: $jodi_str<br>";
        echo "🎰 Panel: $panel_str<br><br>";
    } else {
        $error = $insert_stmt->errorInfo();
        echo "❌ Insert error for $market_name: {$error[2]}<br>";
    }
}
?>
