<section>

<?php
date_default_timezone_set('Asia/Kolkata');

// =========================
// 🌅 TIME BASED GREETING 
// =========================
$hour = date('H');
if ($hour >= 5 && $hour < 12) { $greeting = "🌅 Good Morning!"; }
elseif ($hour >= 12 && $hour < 17) { $greeting = "☀️ Good Afternoon!"; }
elseif ($hour >= 17 && $hour < 21) { $greeting = "🌇 Good Evening!"; }
else { $greeting = "🌙 Good Night!"; }
?>

<div style="text-align: center; font-size: 18px; font-weight: bold; margin-bottom: 10px; color: #1976d2;">
    <?= $greeting ?> Welcome to Today's Game!
</div>

<div style="text-align:center; margin-bottom:15px; color:#d32f2f; font-weight:bold; font-size: 16px; background: #ffebee; padding: 5px; border-radius: 5px;">
    🔴 Live Users Watching: <span id="live-users" style="color: #000;">Loading...</span>
</div>

<h3 class="contener box t24 bg-head text">Today Live Matka Results Games Updates</h3>
<p>Yaha aapko daily updated Satta Matka results, jodi, panel aur market timing milta hai. Aap Sridevi, Time Bazar, Milan, Rajdhani, Supreme, Kalyan, Madhur Day/Night, Main Bazar aur other famous matka markets ke latest results niche dekh sakte hain. Har market ke fresh result yaha live update ho rahe hain.</p>
<?php
// =========================
// 🚀 NEW FUNCTION: Fix Random Text & Like/Dislike Count
// =========================
if (!function_exists('get_fixed_random_msg')) {
    function get_fixed_random_msg($messages, $game_id, $date, $type, $number) {
        $seed = $game_id . '-' . $date . '-' . $type . '-' . $number;
        $index = hexdec(substr(md5($seed), -5)) % count($messages);
        return $messages[$index];
    }
}
if (!function_exists('get_fixed_count')) {
    function get_fixed_count($game_id, $date, $type) {
        $seed = $game_id . '-' . $date . '-' . $type;
        return hexdec(substr(md5($seed), -4)) % 500 + 100; 
    }
}

$current_time = new DateTime();

// =========================
// 1. FETCH ACTIVE MARKETS
// =========================
$active_markets = $db->query("
SELECT title, game_id, time_open 
FROM games 
WHERE is_active=1 AND guess_status=1 
ORDER BY time_open ASC
")->fetchAll(PDO::FETCH_ASSOC);

// =========================
// 2. DYNAMIC PREDEFINED PANELS (FROM DB)
// =========================
$predefined_panel = [];
$panel_query = $db->query("SELECT digit, panel_value FROM predefined_panels");
$panel_data = $panel_query->fetchAll(PDO::FETCH_ASSOC);

foreach ($panel_data as $row) {
    $digit = $row['digit'];
    $panel_val = trim($row['panel_value']);

    if (!isset($predefined_panel[$digit])) {
        $predefined_panel[$digit] = [];
    }

    if (strpos($panel_val, ',') !== false) {
        $predefined_panel[$digit] = array_filter(array_map('trim', explode(',', $panel_val)), 'strlen');
    } else {
        $predefined_panel[$digit][] = $panel_val;
    }
}

// =========================
// 3. MAIN LOOP
// =========================
foreach ($active_markets as $game) {

    $market = trim($game['title']);
    $game_id = $game['game_id'];

    $today = date('Y-m-d');
    $draw_date = new DateTime($today.' '.$game['time_open']);

    // =========================
    // 🟢 EXACT TIME LOGIC 🟢
    // =========================
    $adjusted_time = (clone $draw_date)->modify('-30 minutes'); 
    $waiting_start = (clone $draw_date)->modify('-50 minutes'); 
    $post_time     = (clone $draw_date)->modify('-40 minutes'); 

    // =========================
    // 📏 TIME DIFF CALCULATION (FIXED)
    // =========================
    if ($post_time > $current_time) {
        $interval = $current_time->diff($post_time);
        $hours = $interval->h + ($interval->days * 24); 
        $minutes = $interval->i;
        $time_diff_text = "{$hours} hour(s) {$minutes} minute(s)";
    } else {
        $time_diff_text = "Time Over / Posted"; 
    }

    // =========================
    // 🎯 FREE GAME (LATEST FIXED)
    // =========================
    $free = $db->prepare("
    SELECT * FROM free_game 
    WHERE market=? 
    ORDER BY STR_TO_DATE(date, '%Y-%m-%d') DESC 
    LIMIT 1
    ");
    $free->execute([$market]);
    $data = $free->fetch(PDO::FETCH_ASSOC);

    // =========================
    // 🔴 NEW SECURITY UPDATE: Samay se pehle game leak hone se roke
    // =========================
    if ($data && $data['date'] == $today && $current_time < $post_time) {
        $free_yest = $db->prepare("
        SELECT * FROM free_game 
        WHERE market=? AND date < ? 
        ORDER BY STR_TO_DATE(date, '%Y-%m-%d') DESC 
        LIMIT 1
        ");
        $free_yest->execute([$market, $today]);
        $data = $free_yest->fetch(PDO::FETCH_ASSOC);
    }

    // Date Logic Setup
    $label = '';
    $formatted_date = '';
    if ($data) {
        $raw_date = $data['date'];
        $timestamp = strtotime($raw_date);
        $formatted_date = date('d-m-Y', $timestamp);
        
        $today_date = date('Y-m-d');
        $yesterday_date = date('Y-m-d', strtotime('-1 day'));
        $check_date = date('Y-m-d', $timestamp);

        if ($check_date == $today_date) $label = ' (Today)';
        elseif ($check_date == $yesterday_date) $label = ' (Yesterday)';
    }

    // =========================
    // ⏳ WAITING (TIME BASED) SHOW
    // =========================
    if ($current_time >= $waiting_start && $current_time < $post_time) {
        echo "<article class='contener box bg-w'>
        
        <div style='text-align: center; margin-bottom: 10px; font-size: 14px; color: #555;'>
             🕒 Market Time: " . $adjusted_time->format('h:i:s A') . "<br>
            📏 Time Diff: $time_diff_text
        </div>

        <span class='bg-main'>Date: " . ($formatted_date ? $formatted_date . $label : date('d-m-Y') . ' (Today)') . "</span>
        <div class='t24 res-color'>$market</div>

        <div class='progress-box'><div class='progress-bar'></div></div>

        <div class='t20 blue'>→ ☞ Otc - ⌛ <span class='countdown' data-time='".$post_time->getTimestamp()."'></span></div>
        <div class='t20 blue'>→ ☞ Jodi - ⌛ <span class='countdown' data-time='".$post_time->getTimestamp()."'></span></div>
        <div class='t20 blue'>→ ☞ Panel - ⌛ <span class='countdown' data-time='".$post_time->getTimestamp()."'></span></div>

        <div class='time-color t15'>!! Best Of Luck All !!</div>
        </article>";
        continue; 
    }

    if(!$data) continue;

    // =========================
    // 📥 DATA PROCESS
    // =========================
    $open = array_filter(array_map('trim', explode(",",$data['open'])), 'strlen');
    $jodi = array_filter(array_map('trim', explode(",",$data['jodi'])), 'strlen');
    $panel = array_filter(array_map('trim', explode(",",$data['panel'])), 'strlen');

    // =========================
    // 🔍 PASSING & RESULT CHECK LOGIC
    // =========================
    $resQ = $db->prepare("SELECT * FROM results WHERE game_id=? AND draw_date=?");
    $resQ->execute([$game_id, $data['date']]);
    $res = $resQ->fetch(PDO::FETCH_ASSOC);

    $open_res = $res['open_digits'] ?? '';
    $close_res = $res['close_digits'] ?? '';

    $is_result_declared = ($open_res !== '' || $close_res !== ''); 

    $ho=[]; $hc=[]; $pm_open=[]; $pm_close=[]; $hj=[];

    foreach ($predefined_panel as $d=>$arr){
        if(in_array($open_res,$arr) && in_array($d,$open)) $ho[]=$d;
        if(in_array($close_res,$arr) && in_array($d,$open)) $hc[]=$d;
    }

    foreach($panel as $p){
        if($p==$open_res) $pm_open[]=$p;
        if($p==$close_res) $pm_close[]=$p;
    }

    foreach($jodi as $j){
        if(isset($j[0]) && isset($j[1])) {
            if(in_array($j[0],$ho) && in_array($j[1],$hc)) {
                $hj[]=$j;
            }
        }
    }

    $is_passed = count($ho) + count($hc) + count($hj) + count($pm_open) + count($pm_close) > 0;

    // =========================
    // ✨ BRACKET (QUOTE) LOGIC 
    // =========================
    $display_open = [];
    foreach($open as $o) {
        if(in_array($o, $ho) || in_array($o, $hc)) {
            $display_open[] = "((".$o."))";
        } else {
            $display_open[] = $o;
        }
    }

    $display_jodi = [];
    foreach($jodi as $j) {
        if(in_array($j, $hj)) {
            $display_jodi[] = "(".$j.")";
        } else {
            $display_jodi[] = $j;
        }
    }

    $display_panel = [];
    foreach($panel as $p) {
        if(in_array($p, $pm_open) || in_array($p, $pm_close)) {
            $display_panel[] = "(".$p.")";
        } else {
            $display_panel[] = $p;
        }
    }

    // =========================
    // 💬 RANDOM USER ENGAGEMENT TEXT (PASS)
    // =========================
    $msg_open = ['Dhamaka Open', 'Superb Open', 'Solid Open']; 
    $msg_close = ['Solid Close', 'Dhamaka Close', 'Superb Close', 'Blast Close']; 
    $msg_jodi = ['Super Jodi', 'Jackpot Jodi', 'Dhamaka Jodi', 'Solid Jodi']; 
    $msg_open_panel = ['Open Panel', 'Solid Open Panel', 'Superb Open Panel'];
    $msg_close_panel = ['Close Panel', 'Solid Close Panel', 'Superb Close Panel'];


    // =========================
    // 💬 ADVANCE MESSAGES ARRAYS (PRE-RESULT) - BOOSTED
    // =========================

    $msg_adv_open = [
        '🔥 Aaj ka Open Fix Game', '🎯 Open Number Strong Lag raha hai', '💎 Lucky Open Matka Number', '🚀 Open Result Blast Aaj',
        '⚡ Fast Open Winning Chance', '🏆 Aaj ka Open King', '💰 Paisa Banane wala Open', '🎲 Open Guess High Chance',
        '🔥 Open Prediction Expert Pick', '💥 Aaj ka Open Jackpot', '🎯 Satta Open Number Today', '🔥 Matka Open Game Fix Trick',
        '💎 Open Lucky Number Satta', '🚀 Open Result Live Update', '⚡ Strong Open Single', '🏆 Open Game King Choice',
        '💰 Open Profit Trick', '🎲 Open Game Winning Idea', '🔥 Open Sure Shot Try', '💥 Open Game Special Today',
        '🔥 Aaj ka Open Daba ke Kehlo', '🎯 Open 100% Try Game', '💎 Aaj ka Best Open Number', '🚀 Open Full Confidence Game',
        '⚡ Aaj Open Me Paisa Banega', '🏆 Open King Fix Lag raha hai', '💰 Aaj ka Open Solid Chance', '🎲 Open Double Chance',
        '🔥 Open Risk le sakte ho', '💥 Open Super Hit Game'
    ];

    $msg_adv_close = [
        '🔥 Close Game Fix Aaj', '🎯 Close Number Strong Hai', '💎 Lucky Close Number', '🚀 Close Result Blast',
        '⚡ Close Winning Chance High', '🏆 Aaj ka Close King', '💰 Close Me Paisa Double', '🎲 Close Guess Strong',
        '🔥 Close Expert Trick', '💥 Close Jackpot Chance', '🎯 Satta Close Number Today', '🔥 Close Fix Game Matka',
        '💎 Close Lucky Satta Number', '🚀 Close Result Live', '⚡ Strong Close Single', '🏆 Close Game King',
        '💰 Close Profit Idea', '🎲 Close Game Prediction', '🔥 Close Sure Shot', '💥 Close Special Today',
        '🔥 Aaj ka Super Close', '🎯 Close Daba ke Kehlo', '💎 Aaj ka Best Close Number', '🚀 Close Full Confidence',
        '⚡ Close Me High Chance Hai', '🏆 Close King Fix Game', '💰 Close Paisa Vasool Game', '🎲 Close Double Chance',
        '🔥 Close Risk Worth Hai', '💥 Close Super Hit Today'
    ];

    $msg_adv_jodi = [
        '🔥 Jodi Fix Game Today', '🎯 Strong Jodi Lag rahi hai', '💎 Lucky Jodi Number', '🚀 Jodi Blast Aaj',
        '⚡ Fast Jodi Win Chance', '🏆 Aaj ki Jodi King', '💰 Jodi Profit Trick', '🎲 Jodi Guess High Chance',
        '🔥 Jodi Expert Prediction', '💥 Jodi Jackpot Today', '🎯 Satta Jodi Today', '🔥 Jodi Fix Trick Matka',
        '💎 Lucky Jodi Satta', '🚀 Jodi Result Update', '⚡ Strong Jodi Pair', '🏆 Jodi King Choice',
        '💰 Jodi Profit Idea', '🎲 Jodi Game Prediction', '🔥 Jodi Sure Shot', '💥 Jodi Special Today',
        '🔥 Aaj ki Best Jodi', '🎯 Jodi Daba ke Kehlo', '💎 Jodi 100% Try', '🚀 Jodi Full Confidence Game',
        '⚡ Jodi High Winning Chance', '🏆 Jodi King Fix', '💰 Jodi Paisa Banane wali', '🎲 Jodi Double Chance',
        '🔥 Jodi Risk le sakte ho', '💥 Jodi Super Hit Today'
    ];

    $msg_adv_open_panel = [
        '🔥 Open Panel Fix Today', '🎯 Strong Open Panel', '💎 Lucky Open Panel', '🚀 Open Panel Blast',
        '⚡ Panel Winning Chance', '🏆 Open Panel King', '💰 Panel Profit Trick', '🎲 Open Panel Guess',
        '🔥 Panel Expert Pick', '💥 Open Panel Jackpot', '🎯 Satta Open Panel Today', '🔥 Open Panel Fix Trick',
        '💎 Lucky Panel Number', '🚀 Panel Result Update', '⚡ Strong Panel Game', '🏆 Panel King Choice',
        '💰 Panel Profit Idea', '🎲 Panel Prediction', '🔥 Panel Sure Shot', '💥 Panel Special Today',
        '🔥 Aaj ka Open Panel King', '🎯 Panel Daba ke Kehlo', '💎 Panel 100% Try', '🚀 Panel Full Confidence',
        '⚡ Panel High Chance Game', '🏆 Panel Fix Lag raha hai', '💰 Panel Paisa Banega', '🎲 Panel Double Chance',
        '🔥 Panel Risk Worth Hai', '💥 Panel Super Hit'
    ];

    $msg_adv_close_panel = [
        '🔥 Close Panel Fix Today', '🎯 Strong Close Panel', '💎 Lucky Close Panel', '🚀 Close Panel Blast',
        '⚡ Panel Winning Chance', '🏆 Close Panel King', '💰 Panel Profit Trick', '🎲 Close Panel Guess',
        '🔥 Panel Expert Pick', '💥 Close Panel Jackpot', '🎯 Satta Close Panel Today', '🔥 Close Panel Fix Trick',
        '💎 Lucky Close Panel Number', '🚀 Panel Result Live', '⚡ Strong Panel Close', '🏆 Panel King Choice',
        '💰 Panel Profit Idea', '🎲 Panel Prediction Close', '🔥 Panel Sure Shot Close', '💥 Panel Special Close',
        '🔥 Aaj ka Close Panel King', '🎯 Close Panel Daba ke Kehlo', '💎 Close Panel 100% Try', '🚀 Panel Full Confidence Close',
        '⚡ Close Panel High Chance', '🏆 Panel Fix Close', '💰 Panel Paisa Double Close', '🎲 Panel Double Chance Close',
        '🔥 Panel Risk le sakte ho Close', '💥 Panel Super Hit Close'
    ];

    $base_likes = get_fixed_count($game_id, $data['date'], 'like');
    $base_dislikes = get_fixed_count($game_id, $data['date'], 'dislike');
?>

<article class="contener box">
 
<div style="text-align: center; margin-bottom: 10px; font-size: 14px; color: #555; background: #f9f9f9; padding: 8px; border-radius: 5px;">
    <span style="color: #d32f2f;">⏳ Waiting Start: <?= $waiting_start->format('h:i:s A') ?></span><br>
    <span style="color: #1976d2;">📏 Time Diff: <?= $time_diff_text ?></span>
</div>
 
<span class="bg-main">Date: <?= $formatted_date . $label ?></span>

<div class="t24 res-color"><?= $market ?></div>

 

<?php 
// 🔥 Market ke naam ko URL slug me convert karne ka logic (e.g., "KALYAN" -> "kalyan")
$dynamic_slug = strtolower(str_replace(' ', '-', trim($market))); 
?>
<div class="center-btn-box" style="margin: 10px 0;">
    <a href="https://satta4umatka.live/passing-record/all/<?= $dynamic_slug ?>" style="background: #1976d2; color: #fff; padding: 5px 15px; text-decoration: none; border-radius: 5px; font-weight: bold; font-size: 14px;">
        (<?= $market ?>) पुराना पासिंग रिकॉर्ड देखें
    </a>
</div> 

 


<div class="bg-headd">
<?php
// AUTO HIDE / SHOW UI LOGIC
if (!$is_result_declared) {
    
    // Sab arrays me se 1-1 pick karke master array banaya
    $all_adv = [
        get_fixed_random_msg($msg_adv_open, $game_id, $data['date'], 'adv_o', 1),
        get_fixed_random_msg($msg_adv_close, $game_id, $data['date'], 'adv_c', 1),
        get_fixed_random_msg($msg_adv_jodi, $game_id, $data['date'], 'adv_j', 1),
        get_fixed_random_msg($msg_adv_open_panel, $game_id, $data['date'], 'adv_op', 1),
        get_fixed_random_msg($msg_adv_close_panel, $game_id, $data['date'], 'adv_cp', 1)
    ];

    // Seed logic tak har market ka random fixed rahe (refresh pe change na ho)
    $seed = hexdec(substr(md5($game_id . $data['date']), -4));
    
    // Sirf 2 ya 3 lines dikhane ka logic
    $num_lines = ($seed % 2 == 0) ? 2 : 3; 

    // Bina duplicate ke randomly lines shuffle karna
    $indices = [0, 1, 2, 3, 4];
    for ($i = 0; $i < 5; $i++) {
        $swap_idx = ($seed + $i * 7) % 5;
        $temp = $indices[$i];
        $indices[$i] = $indices[$swap_idx];
        $indices[$swap_idx] = $temp;
    }

    // Print only selected 2 or 3 lines
    for ($i = 0; $i < $num_lines; $i++) {
        echo '<div class="yellow" style="color:#007BFF; font-weight:bold;">⏳ ' . $all_adv[$indices[$i]] . '</div>';
    }

} else {
    // Is market ka result insert ho gaya hai, Pass/Fail dikhao (Advance auto-hide)
    if ($is_passed) {
        foreach($ho as $o) { 
            $txt = get_fixed_random_msg($msg_open, $game_id, $data['date'], 'open', $o);
            echo '<div class="yellow">✅🔥 ' . $txt . ' Pass - ' . $o . '</div>'; 
        }
        foreach($hc as $c) { 
            $txt = get_fixed_random_msg($msg_close, $game_id, $data['date'], 'close', $c);
            echo '<div class="yellow">✅💥 ' . $txt . ' Pass - ' . $c . '</div>'; 
        }
        foreach($hj as $j) { 
            $txt = get_fixed_random_msg($msg_jodi, $game_id, $data['date'], 'jodi', $j);
            echo '<div class="yellow">✅🚀 ' . $txt . ' Pass - ' . $j . '</div>'; 
        }
        foreach($pm_open as $p) { 
            $txt = get_fixed_random_msg($msg_open_panel, $game_id, $data['date'], 'opanel', $p);
            echo '<div class="yellow">✅🎯 ' . $txt . ' Pass - ' . $p . '</div>'; 
        }
        foreach($pm_close as $p) { 
            $txt = get_fixed_random_msg($msg_close_panel, $game_id, $data['date'], 'cpanel', $p);
            echo '<div class="yellow">✅🎯 ' . $txt . ' Pass - ' . $p . '</div>'; 
        }
    } else {
        echo '<div style="color: #d32f2f; font-weight: bold; background: #ffebee; padding: 5px; border-radius: 4px; margin-bottom: 5px;">❌ Game Failed (Bad Luck 💔)</div>';
    }
}
?>
</div>

<?php if(count($display_open) > 0): ?>
<div class="t20"><span class="blue">OTC: </span> → <?= implode('-', $display_open) ?></div>
<?php endif; ?>

<?php if(count($display_jodi) > 0): ?>
<div class="t20"><span class="blue">Jodi: </span> → <?= implode('-', $display_jodi) ?></div>
<?php endif; ?>

<?php if(count($display_panel) > 0): ?>
<div class="t20"><span class="blue">Panel: </span> → <?= implode('-', $display_panel) ?></div>
<?php endif; ?>

<div class="like-dislike-box" data-game="<?= $game_id ?>" data-date="<?= $data['date'] ?>">
    <button class="action-btn btn-like" onclick="handleVote(this, 'like')">👍 <span class="cnt"><?= $base_likes ?></span></button>
    <button class="action-btn btn-dislike" onclick="handleVote(this, 'dislike')">👎 <span class="cnt"><?= $base_dislikes ?></span></button>
</div>

</article>

<?php } $db=null; ?>

</section> 
 
<style>
.countdown{font-weight:bold;animation:blink 1s infinite}
@keyframes blink{50%{opacity:.3}}
.progress-box{height:6px;background:#ddd;border-radius:10px;margin-top:5px;overflow:hidden}
.progress-bar{height:100%;width:100%;background:linear-gradient(90deg,red,orange,green)}

/* Action Buttons Style */
.like-dislike-box { margin-top: 15px; display: flex; justify-content: center; gap: 15px; }
.action-btn { border: 1px solid #ccc; background: #b50085; padding: 5px 15px; border-radius: 20px; font-size: 16px; cursor: pointer; font-weight: bold; transition: 0.3s; }
.action-btn:hover { background: #f0f0f0; }
.btn-like.active { background: #d4edda; border-color: #c3e6cb; color: #155724; }
.btn-dislike.active { background: #f8d7da; border-color: #f5c6cb; color: #721c24; }
.cnt {color: #fff; }
</style>

<script>
// 🕒 Wait time Countdown Script (Updated)
// Server ka current time la rahe hain taaki device time se fark na pade
let serverTime = <?= $current_time->getTimestamp() * 1000 ?>; 
let localStartTime = Date.now();

document.querySelectorAll('.countdown').forEach((el, i) => {
    let targetTime = parseInt(el.dataset.time) * 1000; // PHP timestamp ko JS ms me badla
    let bar = document.querySelectorAll('.progress-bar')[i];
    let totalTime = targetTime - serverTime; 

    let timerInterval = setInterval(() => {
        let elapsed = Date.now() - localStartTime;
        let currentServerTime = serverTime + elapsed; 
        let d = targetTime - currentServerTime;

        if (d <= 0) {
            clearInterval(timerInterval);
            el.innerHTML = "Result Loading...";
            try { new Audio('/sound/beep.mp3').play(); } catch(e) {}
            setTimeout(() => location.reload(), 2000);
            return;
        }

        let m = Math.floor(d / 60000);
        let sec = Math.floor((d % 60000) / 1000);
        el.innerHTML = m + "m " + sec + "s";

        // Progress bar smooth update logic
        if (bar && totalTime > 0) {
            let p = ((totalTime - d) / totalTime) * 100;
            bar.style.width = (p > 100 ? 100 : p) + "%";
        }
    }, 1000);
});

// 🔴 REALISTIC FAKE LIVE USERS SCRIPT
let baseUsers = Math.floor(Math.random() * (1500 - 600 + 1)) + 600; 
let liveSpan = document.getElementById('live-users');

function updateLiveUsers() {
    if (!liveSpan) return;
    
    let diff = Math.floor(Math.random() * 18) - 5; 
    baseUsers += diff;
    
    if (baseUsers < 350) baseUsers += 150; 
    
    liveSpan.innerText = baseUsers;
    
    let nextUpdate = Math.floor(Math.random() * 4500) + 1500;
    setTimeout(updateLiveUsers, nextUpdate);
}

if(liveSpan) {
    liveSpan.innerText = baseUsers;
    setTimeout(updateLiveUsers, 2000); 
}

// 👍👎 Like/Dislike Reset on Next Day Logic
function handleVote(btn, type) {
    let parentBox = btn.closest('.like-dislike-box');
    let gameId = parentBox.dataset.game;
    let gameDate = parentBox.dataset.date;
    
    let storageKey = 'vote_' + gameId + '_' + gameDate; 
    
    if (localStorage.getItem(storageKey)) {
        alert("Aapne is game ke is result par pehle hi vote kar diya hai!");
        return;
    }
    
    localStorage.setItem(storageKey, type);
    
    let span = btn.querySelector('.cnt');
    span.innerText = parseInt(span.innerText) + 1;
    btn.classList.add('active');
}

// On Page Load
document.querySelectorAll('.like-dislike-box').forEach(box => {
    let gameId = box.dataset.game;
    let gameDate = box.dataset.date;
    let storageKey = 'vote_' + gameId + '_' + gameDate;
    
    let votedType = localStorage.getItem(storageKey);
    if (votedType) {
        let btn = box.querySelector('.btn-' + votedType);
        if(btn) {
            let span = btn.querySelector('.cnt');
            span.innerText = parseInt(span.innerText) + 1;
            btn.classList.add('active');
        }
    }
});


// 🟢 NEW: REALISTIC FAKE LIKES/DISLIKES AUTO INCREMENT SCRIPT 🟢
function autoIncreaseVotes() {
    // Random numbers jo aapne bataye thay
    let increments = [0, 1, 2, 3, 5, 8, 10, 12, 16]; 
    
    document.querySelectorAll('.like-dislike-box').forEach(box => {
        let likeSpan = box.querySelector('.btn-like .cnt');
        let dislikeSpan = box.querySelector('.btn-dislike .cnt');
        
        if(likeSpan && dislikeSpan) {
            // Like ke liye array se koi bhi random increment uthayega
            let randomIncLike = increments[Math.floor(Math.random() * increments.length)];
            
            // Dislike thoda kam badhe taaki positive lage, isliye chote numbers liye (0, 1, 2, 3)
            let randomIncDislike = (Math.random() > 0.6) ? increments[Math.floor(Math.random() * 4)] : 0; 
            
            // UI par number update karega
            likeSpan.innerText = parseInt(likeSpan.innerText) + randomIncLike;
            dislikeSpan.innerText = parseInt(dislikeSpan.innerText) + randomIncDislike;
        }
    });
    
    // Random time (3 sec se 8 sec) ke baad wapas number badhega
    let nextVoteUpdate = Math.floor(Math.random() * 5000) + 3000;
    setTimeout(autoIncreaseVotes, nextVoteUpdate);
}

// Page load hone ke 3 second baad yeh auto-increment background me chalu ho jayega
setTimeout(autoIncreaseVotes, 3000);
</script>