<?php
session_start();
require_once 'config.php';

if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
    header('location: login.php');
    exit;
}

$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$today = date('Y-m-d');

$today_amount_sum = 0;
$game = $type = $subtype = $number = $amount = '';

// Store entries in session for demo (replace with DB logic as needed)
if (!isset($_SESSION['game_entries'])) $_SESSION['game_entries'] = [];
$entry_err = '';
$show_confirm_popup = false;
$confirmed_entries = [];

// Calculate sum of amount for today's entries from session (only today's entries)
function calculate_today_amount_sum() {
    return array_sum(array_column($_SESSION['game_entries'], 'amount'));
}
$_SESSION['today_amount_sum'] = calculate_today_amount_sum();

// Handle game button click
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    foreach (['ds','db','sg','fb','gb', 'rr', 'gl'] as $game) {
        if (isset($_POST['submit_' . $game])) {
            $_SESSION['show_game_options'] = true;
            $_SESSION['current_game'] = strtoupper($game);
            $_SESSION['ds_type'] = '';
            $_SESSION['hurruf_subtype'] = '';
        }
    }
    // Handle radio selection for DS type
    if (isset($_POST['ds_type'])) {
        $_SESSION['ds_type'] = $_POST['ds_type'];
        $_SESSION['hurruf_subtype'] = '';
    }
    // Handle radio selection for hurruf subtype
    if (isset($_POST['hurruf_subtype'])) {
        $_SESSION['hurruf_subtype'] = $_POST['hurruf_subtype'];
    }
    // Handle Add Entry
    if (isset($_POST['add_entry'])) {
    $number = trim($_POST['number']);
    $amount = trim($_POST['amount']);
    $game = $_SESSION['current_game']; // Use consistent variable name
    $type = $_SESSION['ds_type'];
    $subtype = $_SESSION['hurruf_subtype'];
    // Validation for hurruf Digit
    if ($type === 'hurruf') {
        if (!ctype_digit($number) || $number < 0 || $number > 9) {
            $entry_err = 'For Hurruf, Number must be an integer between 0 and 9.';
        } elseif (!ctype_digit($amount) || $amount < 10 || $amount > 1000) {
            $entry_err = 'Amount must be an integer between 10 and 1000.';
        } else {
            $_SESSION['game_entries'][] = [
                'userid'    => $userid,
                'username'  => $username,
                'game'  => $game, // Always use 'game'
                'type'      => $type,
                'subtype'   => $subtype,
                'number'    => $number,
                'amount'    => $amount
            ];
        }
    }

    // Validation for Jodi
    elseif ($type === 'jodi') {
        if (!ctype_digit($number) || $number < 01 || $number > 100) {
            $entry_err = 'For Jodi, Number must be an integer between 1 and 100.';
        } elseif (!ctype_digit($amount) || $amount < 10 || $amount > 100) {
            $entry_err = 'Amount must be an integer between 10 and 100.';
        } else {
            $_SESSION['game_entries'][] = [
                'userid'    => $userid,
                'username'  => $username,
                'game'  => $game, // Always use 'game'
                'type'      => $type,
                'subtype'   => $subtype,
                'number'    => $number,
                'amount'    => $amount
            ];
        }
    }
}
        // Recalculate sum after adding entry
        $_SESSION['today_amount_sum'] = calculate_today_amount_sum();
    }
    // Handle Confirm
   if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Insert confirmed_entries into DB
    if (isset($_POST['confirm_entries']) && !empty($_SESSION['game_entries'])) {
        $confirmed_entries = $_SESSION['game_entries']; 
        $show_confirm_popup = true;
    }

    // Insert and share on WhatsApp
    if (isset($_POST['wa_share'])) {
        $confirmed_entries = $_SESSION['game_entries'];
        foreach ($confirmed_entries as $entry) {
            // Insert into entries table
            $sql1 = "INSERT INTO entries (userid, username, game, type, subtype, number, amount) VALUES (?, ?, ?, ?, ?, ?, ?)";
            if ($stmt1 = mysqli_prepare($link, $sql1)) {
                mysqli_stmt_bind_param($stmt1, 'issssii',
                    $entry['userid'],
                    $entry['username'],
                    $entry['game'],
                    $entry['type'],
                    $entry['subtype'],
                    $entry['number'],
                    $entry['amount']
                );
                mysqli_stmt_execute($stmt1);
                mysqli_stmt_close($stmt1);
            }
            // Insert into entries_copy table
            $sql2 = "INSERT INTO entries_copy (userid, username, game, type, subtype, number, amount) VALUES (?, ?, ?, ?, ?, ?, ?)";
            if ($stmt2 = mysqli_prepare($link, $sql2)) {
                mysqli_stmt_bind_param($stmt2, 'issssii',
                    $entry['userid'],
                    $entry['username'],
                    $entry['game'],
                    $entry['type'],
                    $entry['subtype'],
                    $entry['number'],
                    $entry['amount']
                );
                mysqli_stmt_execute($stmt2);
                mysqli_stmt_close($stmt2);
            }
        }
    // Prepare WhatsApp message
    $wa_message = "Game Entries:\n";
    foreach ($confirmed_entries as $entry) {
        $wa_message .= "{$entry['game']} | {$entry['type']} | {$entry['subtype']} | {$entry['number']} | {$entry['amount']}\n";
    }
    $wa_message .= "Total Amount: " . $_SESSION['today_amount_sum'];
    $wa_message = urlencode($wa_message);
    $wa_number = "919759907027";
    $wa_url = "https://wa.me/$wa_number?text=$wa_message";
    // Clear session entries
    $_SESSION['game_entries'] = [];
    $_SESSION['today_amount_sum'] = 0;
    // Redirect to WhatsApp
    header("Location: $wa_url");
    exit;
}
    // Handle Update
    if (isset($_POST['update_entry'])) {
        $idx = intval($_POST['entry_idx']);
        $number = trim($_POST['number']);
        $amount = trim($_POST['amount']);
        $type = $_SESSION['game_entries'][$idx]['type'];
        if ($type === 'hurruf') {
            if (!ctype_digit($number) || $number < 0 || $number > 9) {
                $entry_err = 'For Hurruf, Number must be an integer between 0 and 9.';
            } elseif (!ctype_digit($amount) || $amount < 10 || $amount > 1000) {
                $entry_err = 'Amount must be an integer between 10 and 1000.';
            } else {
                $_SESSION['game_entries'][$idx]['number'] = $number;
                $_SESSION['game_entries'][$idx]['amount'] = $amount;
            }
        } else {
            if (!ctype_digit($number) || $number < 1 || $number > 100) {
                $entry_err = 'For Jodi, Number must be an integer between 1 and 100.';
            } elseif (!ctype_digit($amount) || $amount < 10 || $amount > 1000) {
                $entry_err = 'Amount must be an integer between 10 and 1000.';
            } else {
                $_SESSION['game_entries'][$idx]['number'] = $number;
                $_SESSION['game_entries'][$idx]['amount'] = $amount;
            }
        }
        // Recalculate sum after update
        $_SESSION['today_amount_sum'] = calculate_today_amount_sum();
    }
    // Handle Delete Entry
    if (isset($_POST['delete_entry'])) {
        $idx = intval($_POST['entry_idx']);
        array_splice($_SESSION['game_entries'], $idx, 1);
        // Recalculate sum after delete
        $_SESSION['today_amount_sum'] = calculate_today_amount_sum();
    }
    // Handle Add More Game (reset game options)
    if (isset($_POST['add_more_game'])) {
        $_SESSION['show_game_options'] = false;
        $_SESSION['current_game'] = '';
        $_SESSION['ds_type'] = '';
        $_SESSION['hurruf_subtype'] = '';
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Welcome</title>
   <style>
       body {
    font-family: 'Segoe UI', 'Roboto', Arial, sans-serif;
    background: linear-gradient(120deg, #e0eafc 0%, #cfdef3 100%);
    min-height: 100vh;
    margin: 0;
}

.wrapper {
    max-width: 1100px;
    margin: 48px auto 32px auto;
    background: linear-gradient(120deg, #fff 80%, #e3f6fd 100%);
    border-radius: 24px;
    box-shadow: 0 8px 32px rgba(23,162,184,0.12);
    padding: 40px 32px 32px 32px;
    position: relative;
    transition: box-shadow 0.2s;
}

.wrapper h2 {
    text-align: center;
    color: #005c97;
    font-size: 2rem;
    font-weight: 700;
    margin-bottom: 18px;
    letter-spacing: 1px;
}

.top-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 32px;
    padding-bottom: 8px;
    border-bottom: 2px solid #e3f6fd;
}

.top-info {
    display: flex;
    gap: 32px;
    align-items: center;
    font-size: 1.1rem;
}

.top-info b {
    color: #005c97;
    font-size: 1.15rem;
}

.top-info span {
    color: #17a2b8;
    font-weight: 600;
}

.top-info details {
    font-size: 1rem;
}

a {
    color: #005c97;
    text-decoration: none;
    font-weight: 500;
    transition: color 0.2s;
}
a:hover {
    color: #17a2b8;
    text-decoration: underline;
}

.error {
    color: #e53935;
    background: #fff3e0;
    border-radius: 8px;
    padding: 10px 16px;
    margin-bottom: 18px;
    font-size: 1.08rem;
    text-align: center;
    border: 1px solid #ffd600;
    box-shadow: 0 2px 8px rgba(255,214,0,0.08);
}

.timer-btn-group {
    display: flex;
    gap: 32px;
    justify-content: center;
    margin: 32px 0 24px 0;
    flex-wrap: wrap;
}

.timer-btn-item {
    background: linear-gradient(90deg, #005c97 60%, #363795 100%);
    border-radius: 16px;
    box-shadow: 0 2px 12px rgba(23,162,184,0.10);
    padding: 18px 24px;
    display: flex;
    flex-direction: column;
    align-items: center;
    min-width: 120px;
    margin-bottom: 8px;
    transition: box-shadow 0.2s, transform 0.2s;
}
.timer-btn-item:hover {
    box-shadow: 0 6px 24px rgba(23,162,184,0.18);
    transform: scale(1.06);
}

.timer-label {
    font-weight: bold;
    margin-bottom: 10px;
    color: white;
    font-size: 1.08rem;
    letter-spacing: 1px;
}

input[type="submit"], button, .cta-btn {
   background: linear-gradient(90deg, #17a2b8 60%, #ffd600 100%);
    color: #005c97;
    font-weight: 700;
    border: none;
    border-radius: 8px;
    padding: 10px 22px;
    font-size: 1.08rem;
    cursor: pointer;
    margin: 4px 0;
    box-shadow: 0 2px 8px rgba(23,162,184,0.10);
    transition: background 0.2s, color 0.2s, transform 0.2s;
}
input[type="submit"]:hover, button:hover, .cta-btn:hover {
    background: #17a2b8;
    color: #ffd600;
    transform: scale(1.08);
}

form label {
    font-weight: 600;
    color: #005c97;
    margin-right: 8px;
    font-size: 1rem;
}

form input[type="text"], form input[type="number"] {
    padding: 10px 14px;
    border-radius: 8px;
    border: 1.5px solid #17a2b8;
    background: #f7fafc;
    color: #222;
    font-size: 1.08rem;
    margin-bottom: 6px;
    outline: none;
    transition: border 0.2s, background 0.2s, box-shadow 0.2s;
    box-shadow: 0 1px 6px rgba(23,162,184,0.10);
}
form input[type="text"]:focus, form input[type="number"]:focus {
    border-color: #ffd600;
    background: #e3f6fd;
    box-shadow: 0 2px 12px rgba(255,214,0,0.10);
}

table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 24px;
    background: #fff;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(23,162,184,0.08);
}

th, td {
    border: 1px solid #e3f6fd;
    padding: 10px 8px;
    text-align: center;
    font-size: 1rem;
}

th {
   background: linear-gradient(90deg, #005c97 60%, #363795 100%);
    color: white;
    font-weight: 700;
    letter-spacing: 1px;
}

td input[type="text"], td input[type="number"] {
    width: 60px;
    padding: 6px 8px;
    font-size: 1rem;
    border-radius: 6px;
    border: 1px solid #17a2b8;
    background: #f7fafc;
}

.action-btns {
    display: flex;
    gap: 8px;
    justify-content: center;
}

.today-entries-table {
    margin-top: 10px;
    background: #f7fafc;
    border-radius: 8px;
    box-shadow: 0 1px 6px rgba(23,162,184,0.08);
}

.details summary {
    cursor: pointer;
    font-weight: 600;
    color: #005c97;
}

h4 {
    color: #005c97;
    font-size: 1.2rem;
    margin-top: 32px;
    margin-bottom: 12px;
    font-weight: 700;
    letter-spacing: 1px;
}

@media (max-width: 1100px) {
    .wrapper {
        max-width: 98vw;
        padding: 24px 8px;
    }
    .timer-btn-group {
        gap: 18px;
    }
}

@media (max-width: 700px) {
    .wrapper {
        max-width: 100vw;
        padding: 12px 2vw;
    }
    .top-bar, .top-info {
        flex-direction: column;
        gap: 12px;
        align-items: flex-start;
    }
    .timer-btn-group {
        flex-direction: column;
        gap: 12px;
    }
    table, .today-entries-table {
        font-size: 0.95rem;
    }
}

::-webkit-scrollbar {
    width: 8px;
    background: #e3f6fd;
}
::-webkit-scrollbar-thumb {
    background: #17a2b8;
    border-radius: 8px;
}
    </style>
</head>
<body>
    
    <div class="wrapper">
         <div class="top-bar">
            <div class="top-info">
                <b><?php echo htmlspecialchars($username); ?></b>
                <span>Today's Total Amount: ₹ <b><?php echo $_SESSION['today_amount_sum']; ?></b></span>
              
               <span>
    <button type="button" onclick="openEntriesPopup()" style="background:#005c97; color:#fff; border:none; border-radius:8px; padding:8px 18px; font-size:1rem; font-weight:600; cursor:pointer;">
        View Today's Entries
    </button>
</span>



            </div>
            <div><a href="logout.php">Logout</a></div>
        </div>
        <h2>Welcome to the Dashboard</h2>
        
        <!-- Timer and Submit Buttons -->
        <form method="post">
            <div class="timer-btn-group">
                <?php
                $labels = ['DS', 'DB', 'SG', 'FB', 'GB', 'RR', 'GL'];
foreach ($labels as $i => $label): ?>
    <div class="timer-btn-item">
        <label id="timerLabel<?php echo $i; ?>" class="timer-label">Timer: 00:00</label>
        <input type="submit" name="submit_<?php echo strtolower($label); ?>" value="<?php echo $label; ?>">
        <div style="font-size:0.98rem; color:white; font-weight:600; margin-top:8px;">
            Closing Time: <span id="closingTimeLabel<?php echo $i; ?>">--:--</span>
        </div>
    </div>
                <?php endforeach; ?>
            </div>
        </form>

        <?php if (!empty($entry_err)): ?>
            <div class="error"><?php echo $entry_err; ?></div>
        <?php endif; ?>

        <?php if (!empty($_SESSION['show_game_options'])): ?>
            <div style="margin-bottom:10px;">
                <b>Game Name:</b> <?php echo htmlspecialchars($_SESSION['current_game'] ?? ''); ?>
            </div>
            <form method="post">
                <label><input type="radio" name="ds_type" value="hurruf" <?php if(@$_SESSION['ds_type']=='hurruf') echo 'checked'; ?> onchange="this.form.submit();"> Hurruf</label>
                <label><input type="radio" name="ds_type" value="jodi" <?php if(@$_SESSION['ds_type']=='jodi') echo 'checked'; ?> onchange="this.form.submit();"> Jodi</label>
            </form>
            <?php if (!empty($_SESSION['ds_type']) && $_SESSION['ds_type'] == 'hurruf'): ?>
                <form method="post">
                    <label><input type="radio" name="hurruf_subtype" value="A" <?php if(@$_SESSION['hurruf_subtype']=='A') echo 'checked'; ?> onchange="this.form.submit();"> Andar</label>
                    <label><input type="radio" name="hurruf_subtype" value="B" <?php if(@$_SESSION['hurruf_subtype']=='B') echo 'checked'; ?> onchange="this.form.submit();"> Bahar</label>
                </form>
                <?php if (!empty($_SESSION['hurruf_subtype'])): ?>
                    <form method="post">
                        <label>Number:</label>
                        <input type="text" name="number" required>
                        <label>Amount:</label>
                        <input type="text" name="amount" required>
                        <button type="submit" name="add_entry">Add Entry</button>
                    </form>
                <?php endif; ?>
            <?php elseif (!empty($_SESSION['ds_type']) && $_SESSION['ds_type'] == 'jodi'): ?>
                <form method="post">
                    <label>Number:</label>
                    <input type="text" name="number" required>
                    <label>Amount:</label>
                    <input type="text" name="amount" required>
                    <button type="submit" name="add_entry">Add Entry</button>
                </form>
            <?php endif; ?>
        <?php endif; ?>

        <?php if (!empty($_SESSION['game_entries'])): ?>
            <h4>Your Entries</h4>
            <table>
                <tr>
                    <th>UserID</th>
                    <th>Username</th>
                    <th>Game Name</th>
                    <th>Type</th>
                    <th>Subtype</th>
                    <th>Number</th>
                    <th>Amount</th>
                    <th>Action</th>
                </tr>
                <?php foreach ($_SESSION['game_entries'] as $idx => $entry): ?>
                    <tr>
                        <form method="post">
                            <td><?php echo htmlspecialchars($entry['userid'] ?? ''); ?></td>
                            <td><?php echo htmlspecialchars($entry['username'] ?? ''); ?></td>
                            <td><?php echo htmlspecialchars($entry['game'] ?? ''); ?></td>
                            <td><?php echo htmlspecialchars($entry['type']); ?></td>
                            <td><?php echo htmlspecialchars($entry['subtype'] ?? ''); ?></td>
                            <td><input type="text" name="number" value="<?php echo htmlspecialchars($entry['number']); ?>"></td>
                            <td><input type="text" name="amount" value="<?php echo htmlspecialchars($entry['amount']); ?>"></td>
                            <td class="action-btns">
                                <input type="hidden" name="entry_idx" value="<?php echo $idx; ?>">
                                <button type="submit" name="update_entry">Update</button>
                                <button type="submit" name="delete_entry" onclick="return confirm('Delete this entry?');">Delete</button>
                            </td>
                        </form>
                    </tr>
                <?php endforeach; ?>
            </table>
            <br>
<form method="post" style="display:inline;">
    <button type="submit" name="confirm_entries">Confirm</button>
</form>


            <form method="post" style="display:inline;">
                <button type="submit" name="add_more_game">Add More Game</button>
            </form>
        <?php endif; ?>

        <script>
window.onload = function() {
    // Define open/close times for each game (24-hour format)
    const gameTimes = [
        { label: 'DS', openHour: 18, openMinute: 0, closeHour: 3, closeMinute: 0 },  // 6:00 PM - 3:00 AM
        { label: 'DB', openHour: 13, openMinute: 0, closeHour: 14, closeMinute: 40 },
        { label: 'SG', openHour: 15, openMinute: 5, closeHour: 16, closeMinute: 0 },
        { label: 'FB', openHour: 16, openMinute: 40, closeHour: 17, closeMinute: 40 },
        { label: 'GB', openHour: 18, openMinute: 50, closeHour: 20, closeMinute: 20 },
        { label: 'RR', openHour: 21, openMinute: 45, closeHour: 22, closeMinute: 45 },
        { label: 'GL', openHour: 21, openMinute: 30, closeHour: 23, closeMinute: 30 }
    ];

    function pad(n) { return String(n).padStart(2, '0'); }

    function getDSTimerText() {
        const now = new Date();
        // DS open/close times
        let open = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 18, 0, 0, 0);
        let close = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 3, 0, 0, 0);

        // If now is after midnight but before close (3:00 AM), open was yesterday
        if (now.getHours() < 3 || (now.getHours() === 3 && now.getMinutes() < 0)) {
            open.setDate(open.getDate() - 1);
        }
        // If close time is less than open time, close is next day
        if (3 < 18) {
            close.setDate(open.getDate() + 1);
        }

        if (now < open) {
            // Not open yet
            let diff = open - now;
            let hours = Math.floor(diff / (1000 * 60 * 60));
            let minutes = Math.floor((diff / (1000 * 60)) % 60);
            let seconds = Math.floor((diff / 1000) % 60);
            return 'Opens in: ' + pad(hours) + ':' + pad(minutes) + ':' + pad(seconds);
        } else if (now >= open && now < close) {
            // Open, show time left to close
            let diff = close - now;
            let hours = Math.floor(diff / (1000 * 60 * 60));
            let minutes = Math.floor((diff / (1000 * 60)) % 60);
            let seconds = Math.floor((diff / 1000) % 60);
            return 'Time Left: ' + pad(hours) + ':' + pad(minutes) + ':' + pad(seconds);
        } else {
            // Closed
            return 'Closed';
        }
    }

    function updateTimers() {
        const now = new Date();
        gameTimes.forEach(function(game, i) {
            let timerLabel = document.getElementById('timerLabel'+i);
            let closingLabel = document.getElementById('closingTimeLabel'+i);

            // Show closing time in HH:MM AM/PM format
            let closingHour = game.closeHour % 12 === 0 ? 12 : game.closeHour % 12;
            let closingPeriod = game.closeHour < 12 ? 'AM' : 'PM';
            let closingTimeStr = pad(closingHour) + ':' + pad(game.closeMinute) + ' ' + closingPeriod;
            if (closingLabel) closingLabel.textContent = closingTimeStr;

            // For DS, use the main DS timer logic
            if (i === 0) {
                if (timerLabel) {
                    timerLabel.textContent = getDSTimerText();
                    timerLabel.style.color = '#cbe535ff';
                }
                // Enable/disable DS button as per DS timer
                const dsText = getDSTimerText();
                var btn = document.querySelectorAll('.timer-btn-item input[type="submit"]')[i];
                if (btn) {
                    if (dsText.startsWith('Time Left:')) {
                        btn.disabled = false;
                        btn.style.opacity = 1;
                        btn.title = '';
                    } else {
                        btn.disabled = true;
                        btn.style.opacity = 0.5;
                        btn.title = dsText;
                    }
                }
                return;
            }

            // For other games, use their own logic
            let open = new Date(now.getFullYear(), now.getMonth(), now.getDate(), game.openHour, game.openMinute, 0, 0);
            let close = new Date(now.getFullYear(), now.getMonth(), now.getDate(), game.closeHour, game.closeMinute, 0, 0);

            if (
                game.closeHour < game.openHour ||
                (game.closeHour === game.openHour && game.closeMinute < game.openMinute)
            ) {
                close.setDate(close.getDate() + 1);
            }
            if (now > close) {
                open.setDate(open.getDate() + 1);
                close.setDate(close.getDate() + 1);
            }

            if (now < open) {
                let diff = open - now;
                let hours = Math.floor(diff / (1000 * 60 * 60));
                let minutes = Math.floor((diff / (1000 * 60)) % 60);
                let seconds = Math.floor((diff / 1000) % 60);
                if (timerLabel) {
                    timerLabel.textContent = 'Opens in: ' + pad(hours) + ':' + pad(minutes) + ':' + pad(seconds);
                    timerLabel.style.color = 'white';
                }
                disableGameEntry(i, true, 'Opens at ' + pad(game.openHour % 12 === 0 ? 12 : game.openHour % 12) + ':' + pad(game.openMinute) + ' ' + (game.openHour < 12 ? 'AM' : 'PM'));
            } else if (now >= open && now < close) {
                let diff = close - now;
                let hours = Math.floor(diff / (1000 * 60 * 60));
                let minutes = Math.floor((diff / (1000 * 60)) % 60);
                let seconds = Math.floor((diff / 1000) % 60);
                if (timerLabel) {
                    timerLabel.textContent = 'Time Left: ' + pad(hours) + ':' + pad(minutes) + ':' + pad(seconds);
                    timerLabel.style.color = '#cbe535ff';
                }
                disableGameEntry(i, false);
            } else {
                if (timerLabel) {
                    timerLabel.textContent = 'Closed';
                    timerLabel.style.color = '#cbe535ff';
                }
                disableGameEntry(i, true, 'Closed');
            }
        });
    }

    function disableGameEntry(idx, disable, msg) {
        var btn = document.querySelectorAll('.timer-btn-item input[type="submit"]')[idx];
        if (btn) {
            btn.disabled = disable;
            btn.style.opacity = disable ? 0.5 : 1;
            btn.title = msg || '';
        }
    }

    updateTimers();
    setInterval(updateTimers, 1000);
};
        </script>

    </div>
</script>
<!-- Today's Entries Popup -->
<?php
if (isset($_POST['confirm_entries'])) {
    $confirmed_entries = $_SESSION['game_entries']; // Store for popup
    $show_confirm_popup = true;
    // Do NOT clear $_SESSION['game_entries'] here!
}
// Prepare today's entries for popup from SQL table
$today_entries_popup = [];
$sql = "SELECT game, type, subtype, number, amount FROM entries WHERE userid = ? AND DATE(entry_time) = ?";
if ($stmt = mysqli_prepare($link, $sql)) {
    mysqli_stmt_bind_param($stmt, 'is', $userid, $today); // 'i' for userid (int), 's' for today (string)
    mysqli_stmt_execute($stmt);
    mysqli_stmt_bind_result($stmt, $game, $type, $subtype, $number, $amount);
    while (mysqli_stmt_fetch($stmt)) {
        $today_entries_popup[] = [
            'game' => $game,
            'type'     => $type,
            'subtype'  => $subtype,
            'number'   => $number,
            'amount'   => $amount
        ];
    }
    mysqli_stmt_close($stmt);
}
?>

<!--confirmation popup-->
<?php if ($show_confirm_popup && !empty($confirmed_entries)): ?>
<div id="confirm-popup" style="display:flex; position:fixed; top:0; left:0; right:0; bottom:0; background:rgba(0,0,0,0.45); z-index:99999; align-items:center; justify-content:center;">
    <div style="background:linear-gradient(120deg,#fff 80%,#e3f6fd 100%); border-radius:24px; box-shadow:0 8px 32px rgba(23,162,184,0.18); max-width:98vw; width:600px; margin:auto; padding:32px 24px; position:relative;">
        <h3 style="text-align:center; color:#005c97; font-size:1.5rem; font-weight:700; margin-bottom:18px;">Entries Confirmed!</h3>
        <table style="width:100%; border-collapse:collapse; background:#fff; border-radius:12px; box-shadow:0 2px 12px rgba(23,162,184,0.08); margin-bottom:18px;">
            <tr style="background:linear-gradient(90deg,#005c97 60%,#363795 100%); color:white;">
                <th>Game Name</th>
                <th>Type</th>
                <th>Subtype</th>
                <th>Number</th>
                <th>Amount</th>
            </tr>
            <?php foreach ($confirmed_entries as $entry): ?>
            <tr>
                <td><?php echo htmlspecialchars($entry['game'] ?? ''); ?></td>
                <td><?php echo htmlspecialchars($entry['type'] ?? ''); ?></td>
                <td><?php echo htmlspecialchars($entry['subtype'] ?? ''); ?></td>
                <td><?php echo htmlspecialchars($entry['number'] ?? ''); ?></td>
                <td><?php echo htmlspecialchars($entry['amount'] ?? ''); ?></td>
            </tr>
            <?php endforeach; ?>
        </table>
        <form id="waShareForm" method="post">
    <input type="hidden" name="wa_share" value="1">
    <button type="submit" style="background:#25d366; color:#fff; border:none; border-radius:8px; padding:10px 22px; font-size:1rem; font-weight:600; cursor:pointer; margin:auto; display:block;">
        👉Share on WhatsApp To Confirm Your Numbers
    </button>
</form>
        <button onclick="closeConfirmPopup()" style="background:#17a2b8; color:#fff; border:none; border-radius:8px; padding:10px 22px; font-size:1rem; font-weight:600; cursor:pointer; margin:auto; display:block;">Back</button>
    </div>
</div>
<script>
function closeConfirmPopup() {
    document.getElementById('confirm-popup').style.display = 'none';
    document.body.style.overflow = '';
}
document.body.style.overflow = 'hidden';
</script>
<?php endif; ?>

</body>
</html>