<?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'];
// Fetch today's results from results table
date_default_timezone_set('Asia/Kolkata');
$today = date('Y-m-d');


// Fetch today's entries from database
$today_entries_from_db = [];
$today_total_from_db = 0;

// Try to fetch today's entries with timestamp first, fallback to all entries if no timestamp column
$sql = "SELECT * FROM entries WHERE userid = ? AND DATE(entry_time) = ? ORDER BY id DESC";
$stmt = mysqli_prepare($link, $sql);
if (!$stmt) {
    // Fallback: if entry_time column doesn't exist, fetch all entries for this user
    $sql = "SELECT * FROM entries WHERE userid = ? ORDER BY id DESC";
    $stmt = mysqli_prepare($link, $sql);
    if ($stmt) {
        mysqli_stmt_bind_param($stmt, "i", $userid);
        if (mysqli_stmt_execute($stmt)) {
            $result = mysqli_stmt_get_result($stmt);
            while ($row = mysqli_fetch_assoc($result)) {
                $today_entries_from_db[] = $row;
                $today_total_from_db += $row['amount'];
            }
        }
        mysqli_stmt_close($stmt);
    }
} else {
    mysqli_stmt_bind_param($stmt, "is", $userid, $today);
    if (mysqli_stmt_execute($stmt)) {
        $result = mysqli_stmt_get_result($stmt);
        while ($row = mysqli_fetch_assoc($result)) {
            $today_entries_from_db[] = $row;
            $today_total_from_db += $row['amount'];
        }
    }
    mysqli_stmt_close($stmt);
}

$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'] = [];

// Handle session-based messages
$entry_err = $_SESSION['entry_error'] ?? '';
$entry_success = $_SESSION['entry_success'] ?? '';
$show_confirm_popup = false;
$confirmed_entries = [];

// Clear session messages after displaying
if (!empty($_SESSION['entry_error'])) {
    unset($_SESSION['entry_error']);
}
if (!empty($_SESSION['entry_success'])) {
    unset($_SESSION['entry_success']);
}

// 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();

// Clear game options on fresh page load (not POST request)
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    // Don't clear if we want to keep the popup open
    if (!isset($_SESSION['keep_popup_open'])) {
        $_SESSION['show_game_options'] = false;
        $_SESSION['current_game'] = '';
        $_SESSION['ds_type'] = '';
        $_SESSION['hurruf_subtype'] = '';
    }
}

// Handle game button click
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Debug: Log all POST data
    error_log("POST received: " . json_encode($_POST));
    
    // Handle setting current game (from popup JavaScript)
    if (isset($_POST['set_current_game'])) {
        $_SESSION['current_game'] = $_POST['set_current_game'];
        $_SESSION['show_game_options'] = true;
        $_SESSION['ds_type'] = '';
        $_SESSION['hurruf_subtype'] = '';
        
        // Set flag to keep popup open
        if (isset($_POST['keep_popup_open'])) {
            $_SESSION['keep_popup_open'] = true;
        }
        
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit;
    }
    
    // Handle setting current game (from popup form)
    if (isset($_POST['current_game']) && !isset($_POST['ds_type']) && !isset($_POST['hurruf_subtype']) && !isset($_POST['add_entry'])) {
        $_SESSION['current_game'] = $_POST['current_game'];
        $_SESSION['show_game_options'] = true;
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit;
    }
    
    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'] = '';
            header('Location: ' . $_SERVER['PHP_SELF']);
            exit;
        }
    }
    // Handle Add Entry (check this FIRST)
    if (isset($_POST['add_entry'])) {
        // Add debug logging
        error_log("Add Entry clicked - POST data: " . json_encode($_POST));
        
        $number = trim($_POST['number']);
        $amount = trim($_POST['amount']);
        $game = $_SESSION['current_game']; // Use consistent variable name
        $type = $_SESSION['ds_type'];
        $subtype = $_SESSION['hurruf_subtype'];
        
        error_log("Processing entry - Game: $game, Type: $type, Subtype: $subtype, Number: $number, Amount: $amount");
        
        // Validation for hurruf Digit
        if ($type === 'hurruf') {
            if (!ctype_digit($number) || $number < 0 || $number > 9) {
                $_SESSION['entry_error'] = 'For Hurruf, Number must be an integer between 0 and 9.';
            } elseif (!ctype_digit($amount) || $amount < 10 || $amount > 1000) {
                $_SESSION['entry_error'] = '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
                ];
                $_SESSION['entry_success'] = 'Entry added successfully!';
            }
        }
        // Validation for Jodi
        elseif ($type === 'jodi') {
            if (!ctype_digit($number) || $number < 01 || $number > 100) {
                $_SESSION['entry_error'] = 'For Jodi, Number must be an integer between 1 and 100.';
            } elseif (!ctype_digit($amount) || $amount < 10 || $amount > 100) {
                $_SESSION['entry_error'] = '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
                ];
                $_SESSION['entry_success'] = 'Entry added successfully!';
            }
        }
        
        // Recalculate sum after adding entry
        $_SESSION['today_amount_sum'] = calculate_today_amount_sum();
        $_SESSION['keep_popup_open'] = true;
        
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit;
    }
    
    // Handle radio selection for hurruf subtype (check this AFTER add_entry)
    if (isset($_POST['hurruf_subtype'])) {
        error_log("PROCESSING HURRUF SUBTYPE - Value: " . $_POST['hurruf_subtype']);
        
        // Ensure current_game and ds_type are set
        if (isset($_POST['current_game']) && !empty($_POST['current_game'])) {
            $_SESSION['current_game'] = $_POST['current_game'];
            error_log("Set current_game to: " . $_POST['current_game']);
        }
        if (isset($_POST['ds_type']) && !empty($_POST['ds_type'])) {
            $_SESSION['ds_type'] = $_POST['ds_type'];
            error_log("Set ds_type to: " . $_POST['ds_type']);
        }
        $_SESSION['hurruf_subtype'] = $_POST['hurruf_subtype'];
        $_SESSION['show_game_options'] = true;
        $_SESSION['keep_popup_open'] = true;
        
        error_log("FINAL SESSION VALUES - Game: " . ($_SESSION['current_game'] ?? 'NOT SET') . 
                  ", Type: " . ($_SESSION['ds_type'] ?? 'NOT SET') . 
                  ", Subtype: " . ($_SESSION['hurruf_subtype'] ?? 'NOT SET'));
        
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit;
    }
    // Handle radio selection for DS type
    if (isset($_POST['ds_type'])) {
        // Ensure current_game is set
        if (isset($_POST['current_game']) && !empty($_POST['current_game'])) {
            $_SESSION['current_game'] = $_POST['current_game'];
        }
        $_SESSION['ds_type'] = $_POST['ds_type'];
        $_SESSION['hurruf_subtype'] = '';
        $_SESSION['show_game_options'] = true;
        $_SESSION['keep_popup_open'] = true;
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit;
    }
    // Handle Confirm
    // Insert confirmed_entries into DB
    if (isset($_POST['confirm_entries']) && !empty($_SESSION['game_entries'])) {
        $confirmed_entries = $_SESSION['game_entries']; 
        $show_confirm_popup = true;
        
        // Calculate total amount of confirmed entries
        $total_confirmed_amount = 0;
        foreach ($confirmed_entries as $entry) {
            $total_confirmed_amount += $entry['amount'];
        }
        
        // Close the main popup and clear session flags
        $_SESSION['show_game_options'] = false;
        $_SESSION['keep_popup_open'] = false;
        unset($_SESSION['current_game']);
        unset($_SESSION['ds_type']);
        unset($_SESSION['hurruf_subtype']);
        
        // Set flag to show confirmation popup
        $_SESSION['show_confirm_popup'] = true;
        $_SESSION['confirmed_entries'] = $confirmed_entries;
        $_SESSION['confirmed_total_amount'] = $total_confirmed_amount;
        
        // Clear the current entries since they're now confirmed
        $_SESSION['game_entries'] = [];
        $_SESSION['today_amount_sum'] = 0;
        
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit;
    }

    // Insert and share on WhatsApp
    if (isset($_POST['wa_share'])) {
        error_log("WhatsApp share triggered");
        error_log("Confirmed entries in session: " . print_r($_SESSION['confirmed_entries'] ?? 'NOT SET', true));
        error_log("Confirmed total amount: " . ($_SESSION['confirmed_total_amount'] ?? 'NOT SET'));
        
        $confirmed_entries = $_SESSION['confirmed_entries'] ?? []; // Use confirmed entries instead of game_entries
        
        if (empty($confirmed_entries)) {
            error_log("ERROR: No confirmed entries found!");
            // Fallback to current game entries if confirmed entries are empty
            $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";
    if (!empty($confirmed_entries)) {
        foreach ($confirmed_entries as $entry) {
            $wa_message .= "{$entry['game']} | {$entry['type']} | {$entry['subtype']} | {$entry['number']} | {$entry['amount']}\n";
        }
    } else {
        $wa_message .= "No entries found\n";
    }
    $wa_message .= "Total Amount: " . ($_SESSION['confirmed_total_amount'] ?? $_SESSION['today_amount_sum'] ?? 0); // Use confirmed total with fallback
    
    error_log("WhatsApp message content: " . $wa_message);
    $wa_message = urlencode($wa_message);
    $wa_number = "919759907027";
    $wa_url = "https://wa.me/$wa_number?text=$wa_message";
    // Clear session entries including confirmed entries after WhatsApp share
    $_SESSION['game_entries'] = [];
    $_SESSION['today_amount_sum'] = 0;
    $_SESSION['confirmed_entries'] = [];
    $_SESSION['confirmed_total_amount'] = 0;
    $_SESSION['show_confirm_popup'] = false;
    // 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) {
                $_SESSION['entry_error'] = 'For Hurruf, Number must be an integer between 0 and 9.';
            } elseif (!ctype_digit($amount) || $amount < 10 || $amount > 1000) {
                $_SESSION['entry_error'] = 'Amount must be an integer between 10 and 1000.';
            } else {
                $_SESSION['game_entries'][$idx]['number'] = $number;
                $_SESSION['game_entries'][$idx]['amount'] = $amount;
                $_SESSION['entry_success'] = 'Entry updated successfully!';
            }
        } else {
            if (!ctype_digit($number) || $number < 1 || $number > 100) {
                $_SESSION['entry_error'] = 'For Jodi, Number must be an integer between 1 and 100.';
            } elseif (!ctype_digit($amount) || $amount < 10 || $amount > 1000) {
                $_SESSION['entry_error'] = 'Amount must be an integer between 10 and 1000.';
            } else {
                $_SESSION['game_entries'][$idx]['number'] = $number;
                $_SESSION['game_entries'][$idx]['amount'] = $amount;
                $_SESSION['entry_success'] = 'Entry updated successfully!';
            }
        }
        // Recalculate sum after update
        $_SESSION['today_amount_sum'] = calculate_today_amount_sum();
        
        // Keep the popup open with the same game state
        $_SESSION['keep_popup_open'] = true;
        $_SESSION['show_game_options'] = true;
        
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit;
    }
    // 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();
        $_SESSION['entry_success'] = 'Entry deleted successfully!';
        
        // Keep the popup open with the same game state
        $_SESSION['keep_popup_open'] = true;
        $_SESSION['show_game_options'] = true;
        
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit;
    }
    // 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'] = '';
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit;
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard - Shubank Gaming</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #2d3748;
            overflow-x: hidden;
        }

        /* Header */
        .header {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(20px);
            border-bottom: 1px solid rgba(255, 255, 255, 0.2);
            padding: 1rem 0;
            position: sticky;
            top: 0;
            z-index: 1000;
        }

        .header-content {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 1rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 1.5rem;
            flex-wrap: wrap;
        }

        .user-avatar {
            width: 48px;
            height: 48px;
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 700;
            font-size: 1.2rem;
            box-shadow: 0 4px 16px rgba(79, 172, 254, 0.3);
        }

        .user-details h3 {
            color: white;
            font-weight: 600;
            margin-bottom: 2px;
        }

        .total-amount {
            background: rgba(255, 255, 255, 0.15);
            padding: 8px 16px;
            border-radius: 25px;
            color: white;
            font-weight: 600;
            border: 1px solid rgba(255, 255, 255, 0.2);
        }

        .total-amount .amount {
            color: #ffd700;
            font-weight: 700;
            font-size: 1.1rem;
        }

        .header-actions {
            display: flex;
            gap: 12px;
            align-items: center;
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            font-size: 0.9rem;
        }

        .btn-primary {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            box-shadow: 0 4px 16px rgba(79, 172, 254, 0.3);
        }

        .btn-secondary {
            background: rgba(255, 255, 255, 0.15);
            color: white;
            border: 1px solid rgba(255, 255, 255, 0.3);
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
        }

        /* Main Container */
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 2rem 1rem;
        }

        .dashboard-title {
            text-align: center;
            color: white;
            font-size: 2.5rem;
            font-weight: 800;
            margin-bottom: 3rem;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
        }

        /* Game Grid */
        .game-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 2rem;
            margin-bottom: 3rem;
        }

        .game-card {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(20px);
            border-radius: 20px;
            padding: 2rem;
            border: 1px solid rgba(255, 255, 255, 0.2);
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }

        .game-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, #4facfe 0%, #00f2fe 100%);
        }

        .game-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            background: rgba(255, 255, 255, 0.15);
        }

        .game-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
        }

        .game-name {
            font-size: 1.5rem;
            font-weight: 700;
            color: white;
        }

        .game-status {
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
            text-transform: uppercase;
        }

        .status-open {
            background: rgba(55, 236, 176, 0.2);
            color: #f9fafaff;
            border: 1px solid rgba(16, 185, 129, 0.3);
        }

        .status-closed {
            background: rgba(239, 68, 68, 0.2);
            color: #ef4444;
            border: 1px solid rgba(239, 68, 68, 0.3);
        }

        .status-opening {
            background: rgba(245, 158, 11, 0.2);
            color: #f59e0b;
            border: 1px solid rgba(245, 158, 11, 0.3);
        }

        .timer-display {
            background: rgba(0, 0, 0, 0.2);
            padding: 1rem;
            border-radius: 12px;
            margin-bottom: 1rem;
            text-align: center;
        }

        .timer-label {
            color: rgba(255, 255, 255, 0.8);
            font-size: 0.9rem;
            margin-bottom: 4px;
        }

        .timer-value {
            color: #ffd700;
            font-size: 1.2rem;
            font-weight: 700;
            font-family: 'Monaco', 'Menlo', monospace;
        }

        .closing-time {
            color: rgba(255, 255, 255, 0.7);
            font-size: 0.8rem;
            margin-top: 8px;
        }

        .game-button {
            width: 100%;
            padding: 12px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 10px;
            font-weight: 600;
            font-size: 1rem;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 16px rgba(102, 126, 234, 0.3);
        }

        .game-button:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
        }

        .game-button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            transform: none;
        }

        /* Game Configuration Popup */
        .game-popup-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.7);
            backdrop-filter: blur(8px);
            z-index: 10000;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 1rem;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
        }

        .game-popup-overlay.active {
            opacity: 1;
            visibility: visible;
        }

        .game-popup-content {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 20px;
            padding: 2rem;
            max-width: 700px;
            width: 100%;
            max-height: 95vh;
            overflow-y: auto;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            border: 1px solid rgba(255, 255, 255, 0.2);
            transform: scale(0.9);
            transition: transform 0.3s ease;
        }

        .game-popup-overlay.active .game-popup-content {
            transform: scale(1);
        }

        .popup-close {
            position: absolute;
            top: 15px;
            right: 15px;
            background: rgba(255, 255, 255, 0.2);
            border: none;
            border-radius: 50%;
            width: 35px;
            height: 35px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .popup-close:hover {
            background: rgba(255, 255, 255, 0.3);
            transform: scale(1.1);
        }

        /* Game Options Section */
        .game-options {
            position: relative;
            margin-bottom: 0;
        }

        .options-header {
            display: flex;
            align-items: center;
            gap: 12px;
            margin-bottom: 2rem;
        }

        .options-header h3 {
            color: white;
            font-size: 1.5rem;
            font-weight: 700;
        }

        .game-badge {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 0.9rem;
            font-weight: 600;
        }

        .option-group {
            margin-bottom: 2rem;
        }

        .option-label {
            color: white;
            font-weight: 600;
            margin-bottom: 1rem;
            display: block;
        }

        .radio-group {
            display: flex;
            gap: 1rem;
            flex-wrap: wrap;
        }

        .radio-option {
            position: relative;
        }

        .radio-option input[type="radio"] {
            position: absolute;
            opacity: 0;
        }

        .radio-option label {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 12px 20px;
            background: rgba(255, 255, 255, 0.1);
            border: 2px solid rgba(255, 255, 255, 0.2);
            border-radius: 10px;
            color: white;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: 500;
        }

        .radio-option input[type="radio"]:checked + label {
            background: rgba(79, 172, 254, 0.3);
            border-color: #4facfe;
            color: white;
        }

        .input-group {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            margin-bottom: 2rem;
        }

        .input-field {
            position: relative;
        }

        .input-field label {
            display: block;
            color: white;
            font-weight: 600;
            margin-bottom: 8px;
        }

        .input-field input {
            width: 100%;
            padding: 12px 16px;
            background: rgba(255, 255, 255, 0.1);
            border: 2px solid rgba(255, 255, 255, 0.2);
            border-radius: 10px;
            color: white;
            font-size: 1rem;
            transition: all 0.3s ease;
        }

        .input-field input::placeholder {
            color: rgba(255, 255, 255, 0.6);
        }

        .input-field input:focus {
            outline: none;
            border-color: #4facfe;
            background: rgba(255, 255, 255, 0.15);
            box-shadow: 0 0 20px rgba(79, 172, 254, 0.2);
        }

        /* Error & Success Messages */
        .error-message {
            background: rgba(239, 68, 68, 0.1);
            border: 1px solid rgba(239, 68, 68, 0.3);
            color: #fecaca;
            padding: 1rem;
            border-radius: 12px;
            margin-bottom: 2rem;
            text-align: center;
            font-weight: 500;
        }

        .success-message {
            background: rgba(16, 185, 129, 0.1);
            border: 1px solid rgba(16, 185, 129, 0.3);
            color: #6ee7b7;
            padding: 1rem;
            border-radius: 12px;
            margin-bottom: 2rem;
            text-align: center;
            font-weight: 500;
        }

        /* Entries Table */
        .entries-section {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(20px);
            border-radius: 20px;
            padding: 2rem;
            margin-bottom: 2rem;
            border: 1px solid rgba(255, 255, 255, 0.2);
        }

        .entries-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
        }

        .entries-header h3 {
            color: white;
            font-size: 1.5rem;
            font-weight: 700;
        }

        .table-container {
            overflow-x: auto;
            border-radius: 12px;
        }

        .entries-table {
            width: 100%;
            border-collapse: collapse;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 12px;
            overflow: hidden;
        }

        .entries-table th {
            background: rgba(0, 0, 0, 0.3);
            color: white;
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }

        .entries-table td {
            padding: 1rem;
            border-bottom: 1px solid rgba(255, 255, 255, 0.05);
            color: rgba(255, 255, 255, 0.9);
        }

        .entries-table tr:hover {
            background: rgba(255, 255, 255, 0.05);
        }

        .entries-table input {
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 6px;
            color: white;
            padding: 8px 12px;
            width: 80px;
        }

        .action-buttons {
            display: flex;
            gap: 8px;
        }

        .btn-sm {
            padding: 6px 12px;
            font-size: 0.8rem;
            border-radius: 6px;
            border: none;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .btn-update {
            background: #10b981;
            color: white;
        }

        .btn-delete {
            background: #ef4444;
            color: white;
        }

        .btn-sm:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
        }

        /* Bottom Actions */
        .bottom-actions {
            display: flex;
            gap: 1rem;
            justify-content: center;
            flex-wrap: wrap;
            margin-top: 2rem;
        }

        /* Popup Styles */
        .popup-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.7);
            backdrop-filter: blur(8px);
            z-index: 9999;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 1rem;
        }

        .popup-content {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 20px;
            padding: 2rem;
            max-width: 600px;
            width: 100%;
            max-height: 80vh;
            overflow-y: auto;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }

        .popup-header {
            text-align: center;
            margin-bottom: 2rem;
        }

        .popup-header h3 {
            color: white;
            font-size: 1.8rem;
            font-weight: 700;
            margin-bottom: 8px;
        }

        .popup-table {
            background: rgba(255, 255, 255, 0.1);
            border-radius: 12px;
            overflow: hidden;
            margin-bottom: 2rem;
        }

        .popup-actions {
            display: flex;
            gap: 1rem;
            justify-content: center;
            flex-wrap: wrap;
        }

        .btn-whatsapp {
            background: #25d366;
            color: white;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        /* Mobile Responsive */
        @media (max-width: 768px) {
            .container {
                padding: 1rem;
            }

            .dashboard-title {
                font-size: 2rem;
                margin-bottom: 2rem;
            }

            .header-content {
                flex-direction: column;
                text-align: center;
            }

            .user-info {
                justify-content: center;
            }

            .game-grid {
                grid-template-columns: 1fr;
                gap: 1rem;
            }

            .game-card {
                padding: 1.5rem;
            }

            .radio-group {
                flex-direction: column;
            }

            .input-group {
                grid-template-columns: 1fr;
            }

            .entries-table {
                font-size: 0.9rem;
            }

            .entries-table th,
            .entries-table td {
                padding: 0.75rem 0.5rem;
            }

            .bottom-actions {
                flex-direction: column;
            }

            .popup-content,
            .game-popup-content {
                margin: 1rem;
                padding: 1.5rem;
                max-height: 85vh;
            }

            .action-buttons {
                flex-direction: column;
            }
        }

        @media (max-width: 480px) {
            .dashboard-title {
                font-size: 1.5rem;
            }

            .game-card {
                padding: 1rem;
            }

            .game-options,
            .entries-section {
                padding: 1rem;
            }

            .entries-table th,
            .entries-table td {
                padding: 0.5rem 0.25rem;
                font-size: 0.8rem;
            }

            .entries-table input {
                width: 60px;
                padding: 4px 8px;
            }
        }

        /* Scrollbar Styling */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }

        ::-webkit-scrollbar-track {
            background: rgba(255, 255, 255, 0.1);
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb {
            background: rgba(255, 255, 255, 0.3);
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: rgba(255, 255, 255, 0.5);
        }

        /* Animation for loading states */
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.7; }
        }

        .loading {
            animation: pulse 1.5s ease-in-out infinite;
        }
    </style>
</head>
<body>
    <!-- Header -->
    <header class="header">
        <div class="header-content">
            <div class="user-info">
                <div class="user-avatar">
                    <?php echo strtoupper(substr($username, 0, 1)); ?>
                </div>
                <div class="user-details">
                    <h3><?php echo htmlspecialchars($username); ?></h3>
                    <div class="total-amount">
                        <i class="fas fa-wallet"></i>
                        Today's Total: ₹<span class="amount"><?php echo $today_total_from_db + ($_SESSION['today_amount_sum'] ?? 0); ?></span>
                    </div>
                    <?php if (!empty($_SESSION['game_entries'])): ?>
                    <div class="amount-breakdown" style="font-size: 0.8rem; color: rgba(255,255,255,0.7); margin-top: 0.25rem;">
                        Confirmed: ₹<?php echo $today_total_from_db; ?> | Pending: ₹<?php echo $_SESSION['today_amount_sum'] ?? 0; ?>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            <div class="header-actions">
                <button type="button" class="btn btn-primary" onclick="openEntriesPopup()">
                    <i class="fas fa-list"></i>
                    View Entries
                </button>
                <a href="logout.php" class="btn btn-secondary">
                    <i class="fas fa-sign-out-alt"></i>
                    Logout
                </a>
            </div>
        </div>
    </header>

    <!-- Main Container -->
    <div class="container">
        <h1 class="dashboard-title">
            <i class="fas fa-gamepad"></i>
            Gaming Dashboard
        </h1>

        <!-- Error/Success Messages -->
        <?php if (!empty($entry_err)): ?>
            <div class="error-message">
                <i class="fas fa-exclamation-triangle"></i>
                <?php echo $entry_err; ?>
            </div>
        <?php endif; ?>
        
        <?php if (!empty($entry_success)): ?>
            <div class="success-message">
                <i class="fas fa-check-circle"></i>
                <?php echo $entry_success; ?>
            </div>
        <?php endif; ?>

        <!-- Game Selection Grid -->
        <form method="post">
            <div class="game-grid">
                <?php
                $games = [
                    ['code' => 'ds', 'name' => 'DISAWAR', 'icon' => 'fas fa-crown'],
                    ['code' => 'db', 'name' => 'DL BAZAAR', 'icon' => 'fas fa-star'],
                    ['code' => 'sg', 'name' => 'SHRI GANESH', 'icon' => 'fas fa-gem'],
                    ['code' => 'fb', 'name' => 'FARIDABAD', 'icon' => 'fas fa-fire'],
                    ['code' => 'gb', 'name' => 'GHAZIABAD', 'icon' => 'fas fa-bolt'],
                    ['code' => 'rr', 'name' => 'RR', 'icon' => 'fas fa-mountain'],
                    ['code' => 'gl', 'name' => 'GALI', 'icon' => 'fas fa-chess']
                ];
                
                foreach ($games as $index => $game): ?>
                    <div class="game-card">
                        <div class="game-header">
                            <div>
                                <i class="<?php echo $game['icon']; ?>" style="color: #4facfe; margin-right: 8px;"></i>
                                <span class="game-name"><?php echo $game['name']; ?></span>
                            </div>
                            <div class="game-status status-opening" id="status<?php echo $index; ?>">
                                Loading...
                            </div>
                        </div>
                        
                        <div class="timer-display">
                            <div class="timer-label">Timer Status</div>
                            <div class="timer-value" id="timerLabel<?php echo $index; ?>">00:00:00</div>
                            <div class="closing-time">
                                Closes at: <span id="closingTimeLabel<?php echo $index; ?>">--:--</span>
                            </div>
                        </div>
                        
                        <button type="button" class="game-button" id="gameBtn<?php echo $index; ?>" 
                                onclick="openGamePopup('<?php echo $game['name']; ?>')">
                            <i class="fas fa-play"></i>
                            Play <?php echo $game['name']; ?>
                        </button>
                    </div>
                <?php endforeach; ?>
            </div>
        </form>

        <!-- Game Configuration Popup -->
        <div class="game-popup-overlay" id="gamePopup">
            <div class="game-popup-content">
                <button class="popup-close" onclick="closeGamePopup()">
                    <i class="fas fa-times"></i>
                </button>
                
                <div class="game-options">
                    <div class="options-header">
                        <h3>
                            <i class="fas fa-cog"></i>
                            Game Configuration
                        </h3>
                        <div class="game-badge" id="currentGameBadge">
                            <!-- Game name will be set by JavaScript -->
                        </div>
                    </div>

                    <!-- Error/Success Messages in Popup -->
                    <?php if (!empty($entry_err)): ?>
                        <div class="error-message" style="margin-bottom: 1.5rem;">
                            <i class="fas fa-exclamation-triangle"></i>
                            <?php echo $entry_err; ?>
                        </div>
                    <?php endif; ?>
                    
                    <?php if (!empty($entry_success)): ?>
                        <div class="success-message" style="margin-bottom: 1.5rem;">
                            <i class="fas fa-check-circle"></i>
                            <?php echo $entry_success; ?>
                        </div>
                    <?php endif; ?>

                    <!-- Game Type Selection -->
                    <div class="option-group">
                        <label class="option-label">Select Game Type:</label>
                        <form method="post" id="gameTypeForm">
                            <input type="hidden" name="current_game" id="currentGameInput" value="">
                            <div class="radio-group">
                                <div class="radio-option">
                                    <input type="radio" name="ds_type" value="hurruf" id="hurruf" 
                                           <?php if(@$_SESSION['ds_type']=='hurruf') echo 'checked'; ?> 
                                           onchange="this.form.submit();">
                                    <label for="hurruf">
                                        <i class="fas fa-dice"></i>
                                        Hurruf (Single Digit)
                                    </label>
                                </div>
                                <div class="radio-option">
                                    <input type="radio" name="ds_type" value="jodi" id="jodi" 
                                           <?php if(@$_SESSION['ds_type']=='jodi') echo 'checked'; ?> 
                                           onchange="this.form.submit();">
                                    <label for="jodi">
                                        <i class="fas fa-dice-d20"></i>
                                        Jodi (Pair)
                                    </label>
                                </div>
                            </div>
                        </form>
                    </div>

                    <!-- Progress Indicator -->
                    <?php if (!empty($_SESSION['ds_type'])): ?>
                        <div style="background: rgba(79, 172, 254, 0.1); border: 1px solid rgba(79, 172, 254, 0.3); color: #4facfe; padding: 0.75rem; border-radius: 10px; margin-bottom: 1.5rem; text-align: center; font-weight: 500;">
                            <i class="fas fa-check-circle"></i>
                            Selected: <?php echo ucfirst($_SESSION['ds_type']); ?> 
                            <?php if ($_SESSION['ds_type'] == 'hurruf' && !empty($_SESSION['hurruf_subtype'])): ?>
                                - <?php echo $_SESSION['hurruf_subtype'] == 'A' ? 'Andar' : 'Bahar'; ?>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>

                    <!-- Hurruf Subtype Selection -->
                    <?php if (!empty($_SESSION['ds_type']) && $_SESSION['ds_type'] == 'hurruf'): ?>
                        <div class="option-group">
                            <label class="option-label">
                                <i class="fas fa-hand-pointer" style="color: #ffd700;"></i>
                                Now Select Position:
                            </label>
                            
                            <div class="radio-group">
                                <!-- Andar Button -->
                                <form method="post" style="display: inline; margin-right: 15px;">
                                    <input type="hidden" name="current_game" value="<?php echo $_SESSION['current_game'] ?? ''; ?>">
                                    <input type="hidden" name="ds_type" value="hurruf">
                                    <input type="hidden" name="hurruf_subtype" value="A">
                                    <button type="submit" style="background: #667eea; color: white; padding: 15px 30px; border: none; border-radius: 10px; font-size: 16px; cursor: pointer;">
                                        <i class="fas fa-arrow-left"></i> Andar
                                    </button>
                                </form>
                                
                                <!-- Bahar Button -->
                                <form method="post" style="display: inline;">
                                    <input type="hidden" name="current_game" value="<?php echo $_SESSION['current_game'] ?? ''; ?>">
                                    <input type="hidden" name="ds_type" value="hurruf">
                                    <input type="hidden" name="hurruf_subtype" value="B">
                                    <button type="submit" style="background: #764ba2; color: white; padding: 15px 30px; border: none; border-radius: 10px; font-size: 16px; cursor: pointer;">
                                        <i class="fas fa-arrow-right"></i> Bahar
                                    </button>
                                </form>
                            </div>
                        </div>

                        <!-- Number and Amount Input for Hurruf -->
                        <?php if (!empty($_SESSION['hurruf_subtype'])): ?>
                            <div style="background: rgba(16, 185, 129, 0.1); border: 1px solid rgba(16, 185, 129, 0.3); color: #6ee7b7; padding: 0.75rem; border-radius: 10px; margin-bottom: 1.5rem; text-align: center; font-weight: 500;">
                                <i class="fas fa-check-circle"></i>
                                Ready to add entries! Fill the form below:
                            </div>
                            <form method="post" id="entryForm">
                                <input type="hidden" name="current_game" value="<?php echo $_SESSION['current_game'] ?? ''; ?>">
                                <input type="hidden" name="ds_type" value="hurruf">
                                <input type="hidden" name="hurruf_subtype" value="<?php echo $_SESSION['hurruf_subtype'] ?? ''; ?>">
                                <div class="input-group">
                                    <div class="input-field">
                                        <label for="number">
                                            <i class="fas fa-hashtag"></i>
                                            Number (0-9)
                                        </label>
                                        <input type="text" name="number" id="number" required 
                                               placeholder="Enter digit 0-9" maxlength="1">
                                    </div>
                                    <div class="input-field">
                                        <label for="amount">
                                            <i class="fas fa-rupee-sign"></i>
                                            Amount (₹10-1000)
                                        </label>
                                        <input type="text" name="amount" id="amount" required 
                                               placeholder="Enter amount">
                                    </div>
                                </div>
                                <div style="text-align: center; margin-bottom: 1rem;">
                                    <button type="submit" name="add_entry" class="btn btn-primary">
                                        <i class="fas fa-plus"></i>
                                        Add Entry
                                    </button>
                                </div>
                            </form>
                        <?php endif; ?>

                    <!-- Number and Amount Input for Jodi -->
                    <?php elseif (!empty($_SESSION['ds_type']) && $_SESSION['ds_type'] == 'jodi'): ?>
                        <form method="post" id="jodiEntryForm">
                            <input type="hidden" name="current_game" value="<?php echo $_SESSION['current_game'] ?? ''; ?>">
                            <input type="hidden" name="ds_type" value="jodi">
                            <div class="input-group">
                                <div class="input-field">
                                    <label for="number">
                                        <i class="fas fa-hashtag"></i>
                                        Number (01-99)
                                    </label>
                                    <input type="text" name="number" id="number" required 
                                           placeholder="Enter number 01-99" maxlength="2">
                                </div>
                                <div class="input-field">
                                    <label for="amount">
                                        <i class="fas fa-rupee-sign"></i>
                                        Amount (₹10-100)
                                    </label>
                                    <input type="text" name="amount" id="amount" required 
                                           placeholder="Enter amount">
                                </div>
                            </div>
                            <div style="text-align: center; margin-bottom: 1rem;">
                                <button type="submit" name="add_entry" class="btn btn-primary">
                                    <i class="fas fa-plus"></i>
                                    Add Entry
                                </button>
                            </div>
                        </form>
                    <?php endif; ?>
                    
                    <!-- Current Entries Table in Popup -->
                    <?php if (!empty($_SESSION['game_entries'])): ?>
                        <div class="entries-section" style="margin-top: 2rem; background: rgba(255, 255, 255, 0.05); border-radius: 15px; padding: 1.5rem;">
                            <div class="entries-header">
                                <h3 style="margin-bottom: 1rem; font-size: 1.3rem;">
                                    <i class="fas fa-list-alt"></i>
                                    Your Current Entries
                                </h3>
                                <div class="total-amount">
                                    Total: ₹<span class="amount"><?php echo $_SESSION['today_amount_sum']; ?></span>
                                </div>
                            </div>

                            <div class="table-container" style="max-height: 300px; overflow-y: auto;">
                                <table class="entries-table" style="font-size: 0.9rem;">
                                    <thead>
                                        <tr>
                                            <th>Game</th>
                                            <th>Type</th>
                                            <th>Pos</th>
                                            <th>Number</th>
                                            <th>Amount</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($_SESSION['game_entries'] as $idx => $entry): ?>
                                            <tr>
                                                <form method="post">
                                                    <td>
                                                        <span class="game-badge" style="font-size: 0.7rem; padding: 2px 6px;">
                                                            <?php echo htmlspecialchars($entry['game'] ?? ''); ?>
                                                        </span>
                                                    </td>
                                                    <td style="font-size: 0.8rem;"><?php echo htmlspecialchars($entry['type']); ?></td>
                                                    <td style="font-size: 0.8rem;"><?php echo htmlspecialchars($entry['subtype'] ?? '-'); ?></td>
                                                    <td>
                                                        <input type="text" name="number" 
                                                               value="<?php echo htmlspecialchars($entry['number']); ?>"
                                                               style="width: 50px; padding: 4px; font-size: 0.9rem;">
                                                    </td>
                                                    <td>
                                                        <input type="text" name="amount" 
                                                               value="<?php echo htmlspecialchars($entry['amount']); ?>"
                                                               style="width: 60px; padding: 4px; font-size: 0.9rem;">
                                                    </td>
                                                    <td>
                                                        <div class="action-buttons" style="gap: 4px;">
                                                            <input type="hidden" name="entry_idx" value="<?php echo $idx; ?>">
                                                            <button type="submit" name="update_entry" class="btn-sm btn-update" style="padding: 4px 8px; font-size: 0.7rem;">
                                                                <i class="fas fa-edit"></i>
                                                            </button>
                                                            <button type="submit" name="delete_entry" class="btn-sm btn-delete" style="padding: 4px 8px; font-size: 0.7rem;"
                                                                    onclick="return confirm('Delete this entry?');">
                                                                <i class="fas fa-trash"></i>
                                                            </button>
                                                        </div>
                                                    </td>
                                                </form>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>

                            <div class="bottom-actions" style="margin-top: 1rem; justify-content: center; gap: 0.5rem;">
                                <form method="post" style="display:inline;">
                                    <button type="submit" name="confirm_entries" class="btn btn-primary" style="padding: 8px 16px; font-size: 0.9rem;">
                                        <i class="fas fa-check-circle"></i>
                                        Confirm All Entries
                                    </button>
                                </form>
                            </div>
                        </div>
                    <?php endif; ?>
                    
                    <!-- Add More Games Button -->
                    <div style="text-align: center; margin-top: 1rem;">
                        <button type="button" onclick="resetGameSelection()" class="btn btn-secondary">
                            <i class="fas fa-plus-circle"></i>
                            Select Another Game
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Current Entries are now shown only in popup -->

    </div>

    <!-- Enhanced JavaScript -->
    <script>
        // Enhanced Timer System with Professional UI Updates
        window.onload = function() {
            // Game configuration with enhanced timing
            const gameTimes = [
                { label: 'DS', openHour: 18, openMinute: 0, closeHour: 3, closeMinute: 0 },
                { 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 updateGameStatus(index, status, text) {
                const statusElement = document.getElementById('status' + index);
                const buttonElement = document.getElementById('gameBtn' + index);
                
                if (statusElement) {
                    statusElement.className = 'game-status status-' + status;
                    statusElement.textContent = text;
                }
                
                if (buttonElement) {
                    buttonElement.disabled = (status !== 'open');
                    if (status === 'open') {
                        buttonElement.style.opacity = '1';
                        buttonElement.style.pointerEvents = 'auto';
                    } else {
                        buttonElement.style.opacity = '0.6';
                        buttonElement.style.pointerEvents = 'none';
                    }
                }
            }

            function getDSTimerText() {
                const now = new Date();
                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.getHours() < 3 || (now.getHours() === 3 && now.getMinutes() < 0)) {
                    open.setDate(open.getDate() - 1);
                }
                if (3 < 18) {
                    close.setDate(open.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);
                    return {
                        text: 'Opens in: ' + pad(hours) + ':' + pad(minutes) + ':' + pad(seconds),
                        status: 'opening'
                    };
                } 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);
                    return {
                        text: 'Time Left: ' + pad(hours) + ':' + pad(minutes) + ':' + pad(seconds),
                        status: 'open'
                    };
                } else {
                    return {
                        text: 'Closed',
                        status: '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
                    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;

                    // Handle DS game specially
                    if (i === 0) {
                        const dsResult = getDSTimerText();
                        if (timerLabel) {
                            timerLabel.textContent = dsResult.text;
                        }
                        updateGameStatus(i, dsResult.status, dsResult.status.toUpperCase());
                        return;
                    }

                    // Handle other games
                    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);
                        }
                        updateGameStatus(i, 'opening', 'OPENING');
                    } 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);
                        }
                        updateGameStatus(i, 'open', 'OPEN');
                    } else {
                        if (timerLabel) {
                            timerLabel.textContent = 'Closed';
                        }
                        updateGameStatus(i, 'closed', 'CLOSED');
                    }
                });
            }

            // Initialize timers
            updateTimers();
            setInterval(updateTimers, 1000);

            // Function to submit position form dynamically
            function submitPositionForm(position) {
                console.log('Submitting position:', position);
                
                // Create a form dynamically
                var form = document.createElement('form');
                form.method = 'POST';
                form.action = 'dashboard.php';
                
                // Add hidden fields
                var gameInput = document.createElement('input');
                gameInput.type = 'hidden';
                gameInput.name = 'current_game';
                gameInput.value = '<?php echo $_SESSION['current_game'] ?? ''; ?>';
                form.appendChild(gameInput);
                
                var typeInput = document.createElement('input');
                typeInput.type = 'hidden';
                typeInput.name = 'ds_type';
                typeInput.value = 'hurruf';
                form.appendChild(typeInput);
                
                var subtypeInput = document.createElement('input');
                subtypeInput.type = 'hidden';
                subtypeInput.name = 'hurruf_subtype';
                subtypeInput.value = position;
                form.appendChild(subtypeInput);
                
                // Append form to body and submit
                document.body.appendChild(form);
                console.log('Form created, submitting...');
                form.submit();
            }

            // Add click handlers for debugging
            document.addEventListener('DOMContentLoaded', function() {
                // Debug andar/bahar button clicks - using proper event listeners
                const andarBtn = document.querySelector('.andar-submit-btn');
                const baharBtn = document.querySelector('.bahar-submit-btn');
                
                if (andarBtn) {
                    andarBtn.addEventListener('click', function(e) {
                        console.log('Andar button clicked - form should submit');
                    });
                }
                
                if (baharBtn) {
                    baharBtn.addEventListener('click', function(e) {
                        console.log('Bahar button clicked - form should submit');
                    });
                }
                
                // Also add form submit listeners to see if forms are actually submitting
                const andarForm = document.getElementById('andarForm');
                const baharForm = document.getElementById('baharForm');
                
                if (andarForm) {
                    andarForm.addEventListener('submit', function(e) {
                        console.log('Andar form submitting with data:', new FormData(this));
                    });
                }
                
                if (baharForm) {
                    baharForm.addEventListener('submit', function(e) {
                        console.log('Bahar form submitting with data:', new FormData(this));
                    });
                }
            });
            
            // Auto-open popup if session flag is set or for specific conditions
            <?php if (!empty($_SESSION['keep_popup_open']) || (!empty($_SESSION['current_game']) || !empty($entry_err))): ?>
            setTimeout(function() {
                const popup = document.getElementById('gamePopup');
                if (popup) {
                    <?php if (!empty($_SESSION['current_game'])): ?>
                    document.getElementById('currentGameBadge').textContent = '<?php echo $_SESSION['current_game']; ?>';
                    document.getElementById('currentGameInput').value = '<?php echo $_SESSION['current_game']; ?>';
                    <?php endif; ?>
                    popup.classList.add('active');
                    document.body.style.overflow = 'hidden';
                    
                    // Update all hidden game inputs
                    const gameInputs = document.querySelectorAll('input[name="current_game"]');
                    gameInputs.forEach(input => {
                        input.value = '<?php echo $_SESSION['current_game'] ?? ''; ?>';
                    });
                }
            }, 100);
            <?php 
            // Clear the flag after using it
            if (!empty($_SESSION['keep_popup_open'])) {
                unset($_SESSION['keep_popup_open']);
            }
            ?>
            <?php endif; ?>

            // Add smooth scrolling for mobile
            document.querySelectorAll('a[href^="#"]').forEach(anchor => {
                anchor.addEventListener('click', function (e) {
                    e.preventDefault();
                    document.querySelector(this.getAttribute('href')).scrollIntoView({
                        behavior: 'smooth'
                    });
                });
            });
        };

        // Game popup functionality  
        function openGamePopup(gameName) {
            // Set the current game in the popup
            document.getElementById('currentGameBadge').textContent = gameName;
            document.getElementById('currentGameInput').value = gameName;
            
            // Show the popup immediately
            const popup = document.getElementById('gamePopup');
            popup.classList.add('active');
            document.body.style.overflow = 'hidden';
            
            // Update all hidden game inputs in forms
            const gameInputs = document.querySelectorAll('input[name="current_game"]');
            gameInputs.forEach(input => {
                input.value = gameName;
            });
            
            // Submit a simple form to set the game in session
            const form = document.createElement('form');
            form.method = 'POST';
            form.style.display = 'none';
            
            const gameInput = document.createElement('input');
            gameInput.type = 'hidden';
            gameInput.name = 'set_current_game';
            gameInput.value = gameName;
            
            const keepOpenInput = document.createElement('input');
            keepOpenInput.type = 'hidden';
            keepOpenInput.name = 'keep_popup_open';
            keepOpenInput.value = '1';
            
            form.appendChild(gameInput);
            form.appendChild(keepOpenInput);
            document.body.appendChild(form);
            form.submit();
        }

        // Function to keep popup open after form submission
        function keepPopupOpen() {
            // Store flag that popup should stay open
            sessionStorage.setItem('keepGamePopupOpen', 'true');
            // Also store the current game name
            const gameName = document.getElementById('currentGameBadge').textContent;
            if (gameName) {
                sessionStorage.setItem('currentGameName', gameName);
            }
            
            // Debug log
            console.log('keepPopupOpen called for game:', gameName);
            
            // Ensure all current_game inputs have the correct value
            const gameInputs = document.querySelectorAll('input[name="current_game"]');
            gameInputs.forEach(input => {
                input.value = gameName;
                console.log('Set current_game input to:', gameName);
            });
            
            return true; // Allow form submission
        }

        function closeGamePopup() {
            const popup = document.getElementById('gamePopup');
            popup.classList.remove('active');
            document.body.style.overflow = '';
        }

        function resetGameSelection() {
            // Reset form states
            const forms = document.querySelectorAll('#gamePopup form');
            forms.forEach(form => {
                const radioInputs = form.querySelectorAll('input[type="radio"]');
                radioInputs.forEach(radio => {
                    radio.checked = false;
                });
                const textInputs = form.querySelectorAll('input[type="text"]');
                textInputs.forEach(input => {
                    input.value = '';
                });
            });
            
            // Close popup
            closeGamePopup();
        }

        // Enhanced popup functionality
        function openEntriesPopup() {
            // Check if we have database entries for today or current session entries
            <?php if (!empty($today_entries_from_db) || !empty($_SESSION['game_entries'])): ?>
                // Create and show a professional entries popup with database entries
                const popup = document.createElement('div');
                popup.className = 'popup-overlay';
                popup.innerHTML = `
                    <div class="popup-content">
                        <div class="popup-header">
                            <h3><i class="fas fa-calendar-day"></i> Today's Entries</h3>
                            <p style="color: rgba(255,255,255,0.8); margin: 0;">View all your game entries for today</p>
                        </div>
                        <div class="popup-table">
                            <table class="entries-table">
                                <thead>
                                    <tr>
                                        <th>Game</th>
                                        <th>Type</th>
                                        <th>Position</th>
                                        <th>Number</th>
                                        <th>Amount</th>
                                    </tr>
                                </thead>
                                <tbody id="popup-entries-body">
                                    <?php 
                                    // Display database entries first
                                    if (!empty($today_entries_from_db)):
                                        foreach ($today_entries_from_db 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; 
                                    endif;
                                    
                                    // Display current session entries (if any)
                                    if (!empty($_SESSION['game_entries'])):
                                        foreach ($_SESSION['game_entries'] as $entry): ?>
                                    <tr style="background-color: rgba(255,255,0,0.1);">
                                        <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']); ?> <small>(Pending)</small></td>
                                    </tr>
                                    <?php endforeach; 
                                    endif; ?>
                                </tbody>
                            </table>
                        </div>
                        <div class="popup-summary" style="background: rgba(255,255,255,0.1); padding: 1rem; margin: 1rem 0; border-radius: 10px;">
                            <div style="display: flex; justify-content: space-between; align-items: center;">
                                <span style="font-weight: 600;">Total Amount:</span>
                                <span style="font-size: 1.2rem; font-weight: 700; color: #4facfe;">
                                    ₹<?php echo $today_total_from_db + ($_SESSION['today_amount_sum'] ?? 0); ?>
                                </span>
                            </div>
                            <?php if (!empty($_SESSION['game_entries'])): ?>
                            <div style="font-size: 0.9rem; color: rgba(255,255,255,0.7); margin-top: 0.5rem;">
                                Confirmed: ₹<?php echo $today_total_from_db; ?> | Pending: ₹<?php echo $_SESSION['today_amount_sum'] ?? 0; ?>
                            </div>
                            <?php endif; ?>
                        </div>
                        <div class="popup-actions">
                            <button onclick="closeEntriesPopup()" class="btn btn-secondary">
                                <i class="fas fa-times"></i> Close
                            </button>
                        </div>
                    </div>
                `;
                
                // Add click outside to close
                popup.addEventListener('click', function(e) {
                    if (e.target === popup) {
                        closeEntriesPopup();
                    }
                });
                
                document.body.appendChild(popup);
                document.body.style.overflow = 'hidden';
            <?php else: ?>
                // Create and show a professional entries popup for empty state
                const popup = document.createElement('div');
                popup.className = 'popup-overlay';
                popup.innerHTML = `
                    <div class="popup-content">
                        <div class="popup-header">
                            <h3><i class="fas fa-calendar-day"></i> Today's Entries</h3>
                            <p style="color: rgba(255,255,255,0.8); margin: 0;">View all your game entries for today</p>
                        </div>
                        <div class="popup-table">
                            <table class="entries-table">
                                <thead>
                                    <tr>
                                        <th>Game</th>
                                        <th>Type</th>
                                        <th>Position</th>
                                        <th>Number</th>
                                        <th>Amount</th>
                                    </tr>
                                </thead>
                                <tbody id="popup-entries-body">
                                    <tr>
                                        <td colspan="5" style="text-align: center; color: rgba(255,255,255,0.7);">
                                            <i class="fas fa-info-circle"></i> No entries found for today
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <div class="popup-actions">
                            <button onclick="closeEntriesPopup()" class="btn btn-secondary">
                                <i class="fas fa-times"></i> Close
                            </button>
                        </div>
                    </div>
                `;
                
                // Add click outside to close
                popup.addEventListener('click', function(e) {
                    if (e.target === popup) {
                        closeEntriesPopup();
                    }
                });
                
                document.body.appendChild(popup);
                document.body.style.overflow = 'hidden';
            <?php endif; ?>
        }

        function closeEntriesPopup() {
            const popup = document.querySelector('.popup-overlay');
            if (popup) {
                popup.remove();
                document.body.style.overflow = '';
            }
        }

        function closeConfirmPopup() {
            const popup = document.getElementById('confirm-popup');
            if (popup) {
                popup.style.display = 'none';
                document.body.style.overflow = '';
            }
            
            // Reset game popup state
            const gamePopup = document.getElementById('gamePopup');
            if (gamePopup) {
                gamePopup.classList.remove('active');
            }
        }

        // Input validation
        document.addEventListener('DOMContentLoaded', function() {
            // Close popup when clicking outside
            document.getElementById('gamePopup').addEventListener('click', function(e) {
                if (e.target === this) {
                    closeGamePopup();
                }
            });

            // Close popup on Escape key
            document.addEventListener('keydown', function(e) {
                if (e.key === 'Escape') {
                    closeGamePopup();
                    closeEntriesPopup();
                    closeConfirmPopup();
                }
            });

            // Number input validation for hurruf (0-9)
            const numberInputs = document.querySelectorAll('input[name="number"]');
            numberInputs.forEach(input => {
                input.addEventListener('input', function() {
                    // Remove non-digit characters
                    this.value = this.value.replace(/[^0-9]/g, '');
                    
                    // Check if we're in hurruf mode
                    const isHurruf = document.querySelector('input[name="ds_type"][value="hurruf"]:checked');
                    if (isHurruf && this.value.length > 1) {
                        this.value = this.value.slice(0, 1);
                    }
                    
                    // Check if we're in jodi mode
                    const isJodi = document.querySelector('input[name="ds_type"][value="jodi"]:checked');
                    if (isJodi && this.value.length > 2) {
                        this.value = this.value.slice(0, 2);
                    }
                });
            });

            // Amount input validation
            const amountInputs = document.querySelectorAll('input[name="amount"]');
            amountInputs.forEach(input => {
                input.addEventListener('input', function() {
                    // Remove non-digit characters
                    this.value = this.value.replace(/[^0-9]/g, '');
                    
                    // Limit to reasonable amount
                    if (this.value.length > 4) {
                        this.value = this.value.slice(0, 4);
                    }
                });
            });
        });
    </script>
    <!-- Enhanced Confirmation Popup -->
    <?php if (!empty($_SESSION['show_confirm_popup']) && !empty($_SESSION['confirmed_entries'])): ?>
    <div id="confirm-popup" class="popup-overlay">
        <div class="popup-content">
            <div class="popup-header">
                <h3>
                    <i class="fas fa-check-circle" style="color: #10b981;"></i>
                    Entries Confirmed!
                </h3>
                <p style="color: rgba(255,255,255,0.8); margin: 0;">
                    Review your entries before sharing on WhatsApp
                </p>
            </div>
            
            <div class="popup-table">
                <table class="entries-table">
                    <thead>
                        <tr>
                            <th>Game</th>
                            <th>Type</th>
                            <th>Position</th>
                            <th>Number</th>
                            <th>Amount</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($_SESSION['confirmed_entries'] as $entry): ?>
                        <tr>
                            <td>
                                <span class="game-badge" style="font-size: 0.8rem;">
                                    <?php echo htmlspecialchars($entry['game'] ?? ''); ?>
                                </span>
                            </td>
                            <td><?php echo htmlspecialchars($entry['type'] ?? ''); ?></td>
                            <td><?php echo htmlspecialchars($entry['subtype'] ?? '-'); ?></td>
                            <td>
                                <strong style="color: #ffd700;">
                                    <?php echo htmlspecialchars($entry['number'] ?? ''); ?>
                                </strong>
                            </td>
                            <td>
                                <strong style="color: #10b981;">
                                    ₹<?php echo htmlspecialchars($entry['amount'] ?? ''); ?>
                                </strong>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <tr style="background: rgba(79, 172, 254, 0.1); font-weight: 600;">
                            <td colspan="4" style="text-align: right;">
                                <strong>Total Amount:</strong>
                            </td>
                            <td>
                                <strong style="color: #ffd700; font-size: 1.1rem;">
                                    ₹<?php echo $_SESSION['confirmed_total_amount'] ?? 0; ?>
                                </strong>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            
            <div class="popup-actions">
                <form id="waShareForm" method="post" style="display: inline;">
                    <input type="hidden" name="wa_share" value="1">
                    <button type="submit" class="btn btn-whatsapp">
                        <i class="fab fa-whatsapp"></i>
                        Share on WhatsApp to Confirm
                    </button>
                </form>
                <button onclick="closeConfirmPopup()" class="btn btn-secondary">
                    <i class="fas fa-arrow-left"></i>
                    Back to Dashboard
                </button>
            </div>
        </div>
    </div>
    <script>
        // Close game popup if it's open and show confirmation popup
        document.body.style.overflow = 'hidden';
        closeGamePopup();
        
        // Ensure confirmation popup is visible
        setTimeout(function() {
            document.getElementById('confirm-popup').style.display = 'flex';
        }, 100);
    </script>
    <?php 
    // Clear the confirmation popup flags after displaying - but keep confirmed_entries for WhatsApp share
    if (!empty($_SESSION['show_confirm_popup']) && !isset($_POST['wa_share'])) {
        unset($_SESSION['show_confirm_popup']);
        // Don't clear confirmed_entries and confirmed_total_amount yet - they're needed for WhatsApp share
    }
    ?>
    <?php endif; ?>

</body>
</html>