<?php
// filepath: c:\xampp\htdocs\vc\01\admin\admin-dashboard.php
session_start();
require_once '../config.php';

// Enable error logging
ini_set('log_errors', 1);
ini_set('error_log', '../error.log');

// Check if admin is logged in
if (!isset($_SESSION['admin_id']) || !isset($_SESSION['admin_name'])) {
    header("Location: admin-login.php");
    exit;
}

// Get today's date
date_default_timezone_set('Asia/Kolkata');
$today = date('Y-m-d');

// Get admin name
$admin_name = $_SESSION['admin_name'] ?? 'Admin';

// Get today's total amount
$today_amount = 0;
$res = mysqli_query($link, "SELECT SUM(amount) as total FROM entries WHERE DATE(entry_time) = '$today'");
if ($row = mysqli_fetch_assoc($res)) {
    $today_amount = $row['total'] ?? 0;
}

// Get today's entries
$today_entries = [];
$res = mysqli_query($link, "SELECT * FROM entries WHERE DATE(entry_time) = '$today'");
while ($row = mysqli_fetch_assoc($res)) {
    $today_entries[] = $row;
}

// Get all entries
$all_entries = [];
$res = mysqli_query($link, "SELECT * FROM entries ORDER BY entry_time DESC LIMIT 100");
while ($row = mysqli_fetch_assoc($res)) {
    $all_entries[] = $row;
}

// Get today's users
$today_users = [];
$res = mysqli_query($link, "SELECT DISTINCT username FROM entries WHERE DATE(entry_time) = '$today'");
while ($row = mysqli_fetch_assoc($res)) {
    $today_users[] = $row['username'];
}

// Get total users
$total_users = 0;
$res = mysqli_query($link, "SELECT COUNT(DISTINCT username) as total FROM users");
if ($row = mysqli_fetch_assoc($res)) {
    $total_users = $row['total'];
}
// Handle add result
$msg = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_result_submit'])) {
    // Debug: Log the form submission
    error_log("Add result form submitted");
    error_log("POST data: " . print_r($_POST, true));
    
    $result_date = $_POST['result_date'] ?? '';
    $game = $_POST['game'] ?? '';
    $result_number = $_POST['result_number'] ?? '';
    
    // Validate inputs
    if (empty($result_date) || empty($game) || empty($result_number)) {
        error_log("Missing required fields - Date: $result_date, Game: $game, Number: $result_number");
        header("Location: admin-dashboard.php?show_section=add_result&msg=missing");
        exit;
    }
    
    // Check if results table exists, create if not
    $check_table = mysqli_query($link, "SHOW TABLES LIKE 'results'");
    if (mysqli_num_rows($check_table) == 0) {
        error_log("Results table doesn't exist, creating it");
        $create_table = "CREATE TABLE results (
            id INT AUTO_INCREMENT PRIMARY KEY,
            result_date DATE NOT NULL,
            game VARCHAR(50) NOT NULL,
            result_number VARCHAR(10) NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )";
        if (!mysqli_query($link, $create_table)) {
            error_log("Failed to create results table: " . mysqli_error($link));
            header("Location: admin-dashboard.php?show_section=add_result&msg=dberror");
            exit;
        }
    }
    
    $sql = "INSERT INTO results (result_date, game, result_number) VALUES (?, ?, ?)";
    if ($stmt = mysqli_prepare($link, $sql)) {
        mysqli_stmt_bind_param($stmt, 'sss', $result_date, $game, $result_number);
        if (mysqli_stmt_execute($stmt)) {
            error_log("Result added successfully: Date=$result_date, Game=$game, Number=$result_number");
            header("Location: admin-dashboard.php?show_section=add_result&msg=success");
            exit;
        } else {
            error_log("Execute error: " . mysqli_stmt_error($stmt));
            header("Location: admin-dashboard.php?show_section=add_result&msg=error");
            exit;
        }
        mysqli_stmt_close($stmt);
    } else {
        error_log("Prepare error: " . mysqli_error($link));
        header("Location: admin-dashboard.php?show_section=add_result&msg=dberror");
        exit;
    }
}

// Debug: Log when page loads
error_log("Admin dashboard loaded - REQUEST_METHOD: " . $_SERVER['REQUEST_METHOD']);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    error_log("POST request detected - POST keys: " . implode(', ', array_keys($_POST)));
}
// Handle edit/update/delete for copy report
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Edit/update/delete logic for copy report
    if (isset($_POST['delete_copy_entry'])) {
        $id = intval($_POST['copy_id']);
        mysqli_query($link, "DELETE FROM entries_copy WHERE id = $id");
    }
    if (isset($_POST['update_copy_entry'])) {
        $id = intval($_POST['copy_id']);
        $amount = intval($_POST['amount']);
        $number = $_POST['number'];
        mysqli_query($link, "UPDATE entries_copy SET amount = $amount, number = '$number' WHERE id = $id");
    }
    // Generate copy report
    if (isset($_POST['generate_copy_report'])) {
        // Copy today's entries to entries_copy table
        mysqli_query($link, "DELETE FROM entries_copy WHERE DATE(entry_time) = '$today'");
        foreach ($today_entries as $entry) {
            $sql = "INSERT INTO entries_copy (userid, username, game, type, subtype, number, amount, entry_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
            if ($stmt = mysqli_prepare($link, $sql)) {
                mysqli_stmt_bind_param($stmt, 'isssssis',
                    $entry['userid'],
                    $entry['username'],
                    $entry['game'],
                    $entry['type'],
                    $entry['subtype'],
                    $entry['number'],
                    $entry['amount'],
                    $entry['entry_time']
                );
                mysqli_stmt_execute($stmt);
                mysqli_stmt_close($stmt);
            }
        }
    }
    // Share on WhatsApp
    if (isset($_POST['share_whatsapp'])) {
        // Insert updated entries_copy into another table (entries_shared)
        $shared_entries = [];
        $res = mysqli_query($link, "SELECT * FROM entries_copy WHERE DATE(entry_time) = '$today'");
        while ($row = mysqli_fetch_assoc($res)) {
            $shared_entries[] = $row;
        }
        foreach ($shared_entries as $entry) {
            $sql = "INSERT INTO entries_shared (userid, username, game, type, subtype, number, amount, entry_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
            if ($stmt = mysqli_prepare($link, $sql)) {
                mysqli_stmt_bind_param($stmt, 'isssssis',
                    $entry['userid'],
                    $entry['username'],
                    $entry['game'],
                    $entry['type'],
                    $entry['subtype'],
                    $entry['number'],
                    $entry['amount'],
                    $entry['entry_time']
                );
                mysqli_stmt_execute($stmt);
                mysqli_stmt_close($stmt);
            }
        }
        // Prepare WhatsApp message
        $wa_message = "Today's Entries:\n";
        foreach ($shared_entries as $entry) {
            $wa_message .= "{$entry['username']} | {$entry['game']} | {$entry['type']} | {$entry['subtype']} | {$entry['number']} | {$entry['amount']}\n";
        }
        $wa_message .= "Total Amount: $today_amount";
        $wa_message = urlencode($wa_message);
        $wa_number = "919759907027";
        $wa_url = "https://wa.me/$wa_number?text=$wa_message";
        header("Location: $wa_url");
        exit;
    }
}
$show_section = $_POST['show_section'] ?? '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard | Shubank Gaming</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" 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: #333;
        }

        /* Header */
        .admin-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: 100;
        }

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

        .admin-brand {
            display: flex;
            align-items: center;
            gap: 1rem;
            color: white;
        }

        .admin-avatar {
            width: 50px;
            height: 50px;
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
            font-weight: 700;
            color: white;
            border: 2px solid rgba(255, 255, 255, 0.3);
        }

        .admin-info h2 {
            font-size: 1.2rem;
            font-weight: 700;
            margin-bottom: 0.25rem;
        }

        .admin-role {
            font-size: 0.9rem;
            color: rgba(255, 255, 255, 0.8);
            font-weight: 500;
        }

        .header-stats {
            display: flex;
            gap: 2rem;
            align-items: center;
        }

        .stat-item {
            text-align: center;
            color: white;
        }

        .stat-value {
            font-size: 1.5rem;
            font-weight: 800;
            display: block;
            color: #4facfe;
        }

        .stat-label {
            font-size: 0.8rem;
            opacity: 0.9;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .header-actions {
            display: flex;
            gap: 1rem;
            align-items: center;
        }

        .refresh-btn {
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            color: white;
            padding: 0.75rem;
            border-radius: 12px;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .refresh-btn:hover {
            background: rgba(255, 255, 255, 0.2);
            transform: translateY(-2px);
        }

        .logout-btn {
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
            border: none;
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 12px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .logout-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(239, 68, 68, 0.3);
        }

        /* Main Content */
        .main-content {
            max-width: 1400px;
            margin: 0 auto;
            padding: 2rem;
        }

        /* Dashboard Cards */
        .dashboard-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }

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

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

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

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

        .card-title {
            color: white;
            font-size: 1rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .card-icon {
            width: 50px;
            height: 50px;
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.5rem;
        }

        .card-value {
            font-size: 2.5rem;
            font-weight: 800;
            color: white;
            margin-bottom: 0.5rem;
        }

        .card-description {
            color: rgba(255, 255, 255, 0.8);
            font-size: 0.9rem;
            margin-bottom: 1.5rem;
        }

        .card-action {
            width: 100%;
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            border: none;
            color: white;
            padding: 0.75rem 1rem;
            border-radius: 12px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .card-action:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(79, 172, 254, 0.3);
        }

        /* Content Sections */
        .content-section {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(20px);
            border-radius: 20px;
            border: 1px solid rgba(255, 255, 255, 0.2);
            padding: 2rem;
            margin-bottom: 2rem;
            display: none;
        }

        .content-section.active {
            display: block;
            animation: fadeIn 0.3s ease;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .section-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 2rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid rgba(255, 255, 255, 0.2);
        }

        .section-title {
            color: white;
            font-size: 1.5rem;
            font-weight: 700;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .back-btn {
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            color: white;
            padding: 0.5rem 1rem;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .back-btn:hover {
            background: rgba(255, 255, 255, 0.2);
        }

        /* Tables */
        .table-container {
            overflow-x: auto;
            border-radius: 12px;
            background: rgba(255, 255, 255, 0.05);
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
            background: transparent;
        }

        .data-table th,
        .data-table td {
            padding: 1rem;
            text-align: left;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            color: white;
        }

        .data-table th {
            background: rgba(255, 255, 255, 0.1);
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            font-size: 0.9rem;
        }

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

        /* Forms */
        .form-container {
            max-width: 600px;
            margin: 0 auto;
        }

        .form-group {
            margin-bottom: 1.5rem;
        }

        .form-label {
            display: block;
            color: white;
            font-weight: 600;
            margin-bottom: 0.5rem;
            font-size: 0.9rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .form-input,
        .form-select {
            width: 100%;
            padding: 0.75rem 1rem;
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 8px;
            color: white;
            font-size: 1rem;
            transition: all 0.3s ease;
            backdrop-filter: blur(10px);
        }

        .form-select {
            cursor: pointer;
            appearance: none;
            background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='white' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6,9 12,15 18,9'%3e%3c/polyline%3e%3c/svg%3e");
            background-repeat: no-repeat;
            background-position: right 0.75rem center;
            background-size: 1rem;
            padding-right: 3rem;
        }

        .form-select option {
            background: rgba(102, 126, 234, 0.95);
            color: white;
            padding: 0.5rem;
            border: none;
        }

        .form-select option:hover,
        .form-select option:focus,
        .form-select option:checked {
            background: rgba(79, 172, 254, 0.9);
            color: white;
        }

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

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

        .submit-btn {
            width: 100%;
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            border: none;
            color: white;
            padding: 1rem;
            border-radius: 12px;
            font-weight: 700;
            cursor: pointer;
            transition: all 0.3s ease;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin-top: 1rem;
        }

        .submit-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(79, 172, 254, 0.3);
        }

        /* Action Buttons */
        .action-buttons {
            display: flex;
            gap: 0.5rem;
            flex-wrap: wrap;
        }

        .btn {
            padding: 0.5rem 1rem;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            font-size: 0.85rem;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
        }

        .btn-update {
            background: #4facfe;
            color: white;
        }

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

        .btn-whatsapp {
            background: #25d366;
            color: white;
        }

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

        /* Alerts */
        .alert {
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-weight: 500;
        }

        .alert-success {
            background: rgba(34, 197, 94, 0.2);
            border: 1px solid rgba(34, 197, 94, 0.3);
            color: #bbf7d0;
        }

        .alert-error {
            background: rgba(239, 68, 68, 0.2);
            border: 1px solid rgba(239, 68, 68, 0.3);
            color: #fecaca;
        }

        /* Mobile Responsiveness */
        @media (max-width: 768px) {
            .header-content {
                flex-direction: column;
                text-align: center;
            }

            .header-stats {
                gap: 1rem;
            }

            .main-content {
                padding: 1rem;
            }

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

            .dashboard-card {
                padding: 1.5rem;
            }

            .card-value {
                font-size: 2rem;
            }

            .data-table th,
            .data-table td {
                padding: 0.75rem 0.5rem;
                font-size: 0.9rem;
            }

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

            .section-header {
                flex-direction: column;
                gap: 1rem;
                text-align: center;
            }
        }

        @media (max-width: 480px) {
            .main-content {
                padding: 0.5rem;
            }

            .dashboard-card {
                padding: 1rem;
            }

            .card-value {
                font-size: 1.75rem;
            }

            .data-table {
                font-size: 0.8rem;
            }

            .data-table th,
            .data-table td {
                padding: 0.5rem 0.25rem;
            }
        }

        /* Loading States */
        .loading {
            opacity: 0.6;
            pointer-events: none;
        }

        .spinner {
            width: 20px;
            height: 20px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-top: 2px solid white;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* Utility Classes */
        .text-center { text-align: center; }
        .mb-1 { margin-bottom: 1rem; }
        .mb-2 { margin-bottom: 2rem; }
        .mt-1 { margin-top: 1rem; }
        .mt-2 { margin-top: 2rem; }
        .flex { display: flex; }
        .justify-between { justify-content: space-between; }
        .items-center { align-items: center; }
        .gap-1 { gap: 1rem; }
    </style>
</head>
<body>
    <!-- Header -->
    <header class="admin-header">
        <div class="header-content">
            <div class="admin-brand">
                <div class="admin-avatar">
                    <?php echo strtoupper(substr($admin_name, 0, 1)); ?>
                </div>
                <div class="admin-info">
                    <h2><?php echo htmlspecialchars($admin_name); ?></h2>
                    <div class="admin-role">System Administrator</div>
                </div>
            </div>

            <div class="header-stats">
                <div class="stat-item">
                    <span class="stat-value">₹<?php echo number_format($today_amount); ?></span>
                    <span class="stat-label">Today's Total</span>
                </div>
                <div class="stat-item">
                    <span class="stat-value"><?php echo count($today_entries); ?></span>
                    <span class="stat-label">Today's Entries</span>
                </div>
                <div class="stat-item">
                    <span class="stat-value"><?php echo count($today_users); ?></span>
                    <span class="stat-label">Active Users</span>
                </div>
            </div>

            <div class="header-actions">
                <button class="refresh-btn" onclick="location.reload()">
                    <i class="fas fa-sync-alt"></i>
                    <span>Refresh</span>
                </button>
                <a href="admin-logout.php" class="logout-btn">
                    <i class="fas fa-sign-out-alt"></i>
                    <span>Logout</span>
                </a>
            </div>
        </div>
    </header>

    <!-- Main Content -->
    <main class="main-content">
        <!-- Dashboard Overview -->
        <div id="dashboard-overview" class="content-section active">
            <div class="dashboard-grid">
                <!-- Today's Entries Card -->
                <div class="dashboard-card" onclick="showSection('today_entries')">
                    <div class="card-header">
                        <h3 class="card-title">Today's Entries</h3>
                        <div class="card-icon">
                            <i class="fas fa-calendar-day"></i>
                        </div>
                    </div>
                    <div class="card-value"><?php echo count($today_entries); ?></div>
                    <div class="card-description">Entries submitted today</div>
                    <button class="card-action" onclick="showSection('today_entries')">
                        <i class="fas fa-eye"></i> View Details
                    </button>
                </div>

                <!-- All Entries Card -->
                <div class="dashboard-card" onclick="showSection('all_entries')">
                    <div class="card-header">
                        <h3 class="card-title">All Entries</h3>
                        <div class="card-icon">
                            <i class="fas fa-list"></i>
                        </div>
                    </div>
                    <div class="card-value"><?php echo count($all_entries); ?></div>
                    <div class="card-description">Total system entries</div>
                    <button class="card-action" onclick="showSection('all_entries')">
                        <i class="fas fa-eye"></i> View All
                    </button>
                </div>

                <!-- Today's Users Card -->
                <div class="dashboard-card" onclick="showSection('today_users')">
                    <div class="card-header">
                        <h3 class="card-title">Active Users</h3>
                        <div class="card-icon">
                            <i class="fas fa-users"></i>
                        </div>
                    </div>
                    <div class="card-value"><?php echo count($today_users); ?></div>
                    <div class="card-description">Users active today</div>
                    <button class="card-action" onclick="showSection('today_users')">
                        <i class="fas fa-eye"></i> View Users
                    </button>
                </div>

                <!-- Total Users Card -->
                <div class="dashboard-card" onclick="showSection('total_users')">
                    <div class="card-header">
                        <h3 class="card-title">Total Users</h3>
                        <div class="card-icon">
                            <i class="fas fa-user-friends"></i>
                        </div>
                    </div>
                    <div class="card-value"><?php echo $total_users; ?></div>
                    <div class="card-description">Registered users</div>
                    <button class="card-action" onclick="showSection('total_users')">
                        <i class="fas fa-eye"></i> View All Users
                    </button>
                </div>

                <!-- Add Result Card -->
                <div class="dashboard-card" onclick="showSection('add_result')">
                    <div class="card-header">
                        <h3 class="card-title">Add Results</h3>
                        <div class="card-icon">
                            <i class="fas fa-plus-circle"></i>
                        </div>
                    </div>
                    <div class="card-value"><i class="fas fa-trophy"></i></div>
                    <div class="card-description">Add game results</div>
                    <button class="card-action" onclick="showSection('add_result')">
                        <i class="fas fa-plus"></i> Add Result
                    </button>
                </div>

                <!-- Copy Report Card -->
                <div class="dashboard-card" onclick="showSection('generate_copy_report')">
                    <div class="card-header">
                        <h3 class="card-title">Copy Report</h3>
                        <div class="card-icon">
                            <i class="fas fa-copy"></i>
                        </div>
                    </div>
                    <div class="card-value"><i class="fas fa-clipboard-list"></i></div>
                    <div class="card-description">Generate daily report</div>
                    <button class="card-action" onclick="showSection('generate_copy_report')">
                        <i class="fas fa-file-alt"></i> Generate Report
                    </button>
                </div>
            </div>
        </div>

        <!-- Add Result Section -->
        <div id="add_result" class="content-section">
            <div class="section-header">
                <h2 class="section-title">
                    <i class="fas fa-plus-circle"></i>
                    Add Game Results
                </h2>
                <button class="back-btn" onclick="showSection('dashboard-overview')">
                    <i class="fas fa-arrow-left"></i>
                    Back to Dashboard
                </button>
            </div>

            <?php if (isset($_GET['msg'])) { ?>
                <?php if ($_GET['msg'] === 'success') { ?>
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle"></i>
                        Result added successfully!
                    </div>
                <?php } elseif ($_GET['msg'] === 'error') { ?>
                    <div class="alert alert-error">
                        <i class="fas fa-exclamation-triangle"></i>
                        Error adding result. Please try again.
                    </div>
                <?php } elseif ($_GET['msg'] === 'dberror') { ?>
                    <div class="alert alert-error">
                        <i class="fas fa-database"></i>
                        Database error occurred.
                    </div>
                <?php } elseif ($_GET['msg'] === 'missing') { ?>
                    <div class="alert alert-error">
                        <i class="fas fa-exclamation-circle"></i>
                        Please fill in all required fields.
                    </div>
                <?php } ?>
            <?php } ?>

            <div class="form-container">
                <form method="post" action="admin-dashboard.php">
                    <input type="hidden" name="show_section" value="add_result">
                    
                    <div class="form-group">
                        <label for="result_date" class="form-label">
                            <i class="fas fa-calendar"></i> Date
                        </label>
                        <input type="date" name="result_date" id="result_date" class="form-input" required>
                    </div>

                    <div class="form-group">
                        <label for="game" class="form-label">
                            <i class="fas fa-gamepad"></i> Game
                        </label>
                        <select name="game" id="game" class="form-select" required>
                            <option value="">Select Game</option>
                            <option value="disawar">Disawar</option>
                            <option value="dl_bazaar">DL Bazaar</option>
                            <option value="shri_ganesh">Shri Ganesh</option>
                            <option value="faridabad">Faridabad</option>
                            <option value="ghaziabad">Ghaziabad</option>
                            <option value="radhey_radhey">Radhey Radhey</option>
                            <option value="gali">Gali</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="result_number" class="form-label">
                            <i class="fas fa-hashtag"></i> Result Number
                        </label>
                        <input type="text" name="result_number" id="result_number" class="form-input" 
                               placeholder="Enter result number" required>
                    </div>

                    <button type="submit" name="add_result_submit" class="submit-btn">
                        <i class="fas fa-plus"></i>
                        Add Result
                    </button>
                </form>
            </div>
        </div>

        <!-- Today's Entries Section -->
        <div id="today_entries" class="content-section">
            <div class="section-header">
                <h2 class="section-title">
                    <i class="fas fa-calendar-day"></i>
                    Today's Entries (<?php echo count($today_entries); ?>)
                </h2>
                <button class="back-btn" onclick="showSection('dashboard-overview')">
                    <i class="fas fa-arrow-left"></i>
                    Back to Dashboard
                </button>
            </div>

            <div class="table-container">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th><i class="fas fa-user"></i> User</th>
                            <th><i class="fas fa-gamepad"></i> Game</th>
                            <th><i class="fas fa-tag"></i> Type</th>
                            <th><i class="fas fa-layer-group"></i> Subtype</th>
                            <th><i class="fas fa-hashtag"></i> Number</th>
                            <th><i class="fas fa-rupee-sign"></i> Amount</th>
                            <th><i class="fas fa-clock"></i> Time</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($today_entries)) { ?>
                            <?php foreach ($today_entries as $entry) { ?>
                                <tr>
                                    <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><?php echo htmlspecialchars($entry['number']); ?></td>
                                    <td>₹<?php echo number_format($entry['amount']); ?></td>
                                    <td><?php echo date('H:i:s', strtotime($entry['entry_time'])); ?></td>
                                </tr>
                            <?php } ?>
                        <?php } else { ?>
                            <tr>
                                <td colspan="7" class="text-center">
                                    <i class="fas fa-info-circle"></i>
                                    No entries found for today
                                </td>
                            </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- All Entries Section -->
        <div id="all_entries" class="content-section">
            <div class="section-header">
                <h2 class="section-title">
                    <i class="fas fa-list"></i>
                    All Entries (<?php echo count($all_entries); ?>)
                </h2>
                <button class="back-btn" onclick="showSection('dashboard-overview')">
                    <i class="fas fa-arrow-left"></i>
                    Back to Dashboard
                </button>
            </div>

            <div class="table-container">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th><i class="fas fa-user"></i> User</th>
                            <th><i class="fas fa-gamepad"></i> Game</th>
                            <th><i class="fas fa-tag"></i> Type</th>
                            <th><i class="fas fa-layer-group"></i> Subtype</th>
                            <th><i class="fas fa-hashtag"></i> Number</th>
                            <th><i class="fas fa-rupee-sign"></i> Amount</th>
                            <th><i class="fas fa-clock"></i> Time</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($all_entries)) { ?>
                            <?php foreach ($all_entries as $entry) { ?>
                                <tr>
                                    <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><?php echo htmlspecialchars($entry['number']); ?></td>
                                    <td>₹<?php echo number_format($entry['amount']); ?></td>
                                    <td><?php echo date('M j, H:i', strtotime($entry['entry_time'])); ?></td>
                                </tr>
                            <?php } ?>
                        <?php } else { ?>
                            <tr>
                                <td colspan="7" class="text-center">
                                    <i class="fas fa-info-circle"></i>
                                    No entries found
                                </td>
                            </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>
        </div>
        <!-- Copy Report Section -->
        <div id="generate_copy_report" class="content-section">
            <div class="section-header">
                <h2 class="section-title">
                    <i class="fas fa-copy"></i>
                    Copy Report - Today's Entries
                </h2>
                <button class="back-btn" onclick="showSection('dashboard-overview')">
                    <i class="fas fa-arrow-left"></i>
                    Back to Dashboard
                </button>
            </div>

            <div class="table-container">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th><i class="fas fa-user"></i> User</th>
                            <th><i class="fas fa-gamepad"></i> Game</th>
                            <th><i class="fas fa-tag"></i> Type</th>
                            <th><i class="fas fa-layer-group"></i> Subtype</th>
                            <th><i class="fas fa-hashtag"></i> Number</th>
                            <th><i class="fas fa-rupee-sign"></i> Amount</th>
                            <th><i class="fas fa-clock"></i> Time</th>
                            <th><i class="fas fa-cogs"></i> Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $copy_entries = [];
                        $res = mysqli_query($link, "SELECT * FROM entries_copy WHERE DATE(entry_time) = '$today'");
                        while ($row = mysqli_fetch_assoc($res)) {
                            $copy_entries[] = $row;
                        }
                        
                        if (!empty($copy_entries)) {
                            foreach ($copy_entries as $entry) { ?>
                                <tr>
                                    <form method="post" style="display: contents;">
                                        <input type="hidden" name="copy_id" value="<?php echo $entry['id']; ?>">
                                        <input type="hidden" name="show_section" value="generate_copy_report">\n                                        
                                        <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']); ?>" 
                                                   class="form-input" style="width: 80px; padding: 0.5rem;">
                                        </td>
                                        <td>
                                            <input type="text" name="amount" value="<?php echo htmlspecialchars($entry['amount']); ?>" 
                                                   class="form-input" style="width: 80px; padding: 0.5rem;">
                                        </td>
                                        <td><?php echo date('H:i:s', strtotime($entry['entry_time'])); ?></td>
                                        <td>
                                            <div class="action-buttons">
                                                <button type="submit" name="update_copy_entry" class="btn btn-update">
                                                    <i class="fas fa-save"></i> Update
                                                </button>
                                                <button type="submit" name="delete_copy_entry" class="btn btn-delete" 
                                                        onclick="return confirm('Delete this entry?');">
                                                    <i class="fas fa-trash"></i> Delete
                                                </button>
                                            </div>
                                        </td>
                                    </form>
                                </tr>
                            <?php }
                        } else { ?>
                            <tr>
                                <td colspan="8" class="text-center">
                                    <i class="fas fa-info-circle"></i>
                                    No entries found for today. Generate report first.
                                </td>
                            </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>

            <div class="flex justify-between items-center mt-2">
                <form method="post">
                    <button type="submit" name="generate_copy_report" value="1" class="btn btn-update">
                        <i class="fas fa-sync"></i>
                        Generate Report
                    </button>
                    <input type="hidden" name="show_section" value="generate_copy_report">
                </form>
                
                <?php if (!empty($copy_entries)) { ?>
                    <form method="post">
                        <button type="submit" name="share_whatsapp" class="btn btn-whatsapp">
                            <i class="fab fa-whatsapp"></i>
                            Send on WhatsApp
                        </button>
                    </form>
                <?php } ?>
            </div>
        </div>

        <!-- Today's Users Section -->
        <div id="today_users" class="content-section">
            <div class="section-header">
                <h2 class="section-title">
                    <i class="fas fa-users"></i>
                    Today's Active Users (<?php echo count($today_users); ?>)
                </h2>
                <button class="back-btn" onclick="showSection('dashboard-overview')">
                    <i class="fas fa-arrow-left"></i>
                    Back to Dashboard
                </button>
            </div>

            <div class="table-container">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th><i class="fas fa-id-card"></i> User ID</th>
                            <th><i class="fas fa-user"></i> Username</th>
                            <th><i class="fas fa-phone"></i> User Number</th>
                            <th><i class="fas fa-calendar"></i> Registered Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        if (!empty($today_users)) {
                            $usernames = array_map(function($u) use ($link) {
                                return mysqli_real_escape_string($link, $u);
                            }, $today_users);
                            $usernames_str = "'" . implode("','", $usernames) . "'";
                            $res = mysqli_query($link, "SELECT id, username, usernumber, reg_date FROM users WHERE username IN ($usernames_str)");
                            while ($row = mysqli_fetch_assoc($res)) { ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($row['id']); ?></td>
                                    <td><?php echo htmlspecialchars($row['username']); ?></td>
                                    <td><?php echo htmlspecialchars($row['usernumber']); ?></td>
                                    <td><?php echo date('M j, Y', strtotime($row['reg_date'])); ?></td>
                                </tr>
                            <?php }
                        } else { ?>
                            <tr>
                                <td colspan="4" class="text-center">
                                    <i class="fas fa-info-circle"></i>
                                    No active users today
                                </td>
                            </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Total Users Section -->
        <div id="total_users" class="content-section">
            <div class="section-header">
                <h2 class="section-title">
                    <i class="fas fa-user-friends"></i>
                    All Registered Users (<?php echo $total_users; ?>)
                </h2>
                <button class="back-btn" onclick="showSection('dashboard-overview')">
                    <i class="fas fa-arrow-left"></i>
                    Back to Dashboard
                </button>
            </div>

            <div class="table-container">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th><i class="fas fa-id-card"></i> User ID</th>
                            <th><i class="fas fa-user"></i> Username</th>
                            <th><i class="fas fa-phone"></i> User Number</th>
                            <th><i class="fas fa-calendar"></i> Registered Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $res = mysqli_query($link, "SELECT id, username, usernumber, reg_date FROM users ORDER BY reg_date DESC");
                        if (mysqli_num_rows($res) > 0) {
                            while ($row = mysqli_fetch_assoc($res)) { ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($row['id']); ?></td>
                                    <td><?php echo htmlspecialchars($row['username']); ?></td>
                                    <td><?php echo htmlspecialchars($row['usernumber']); ?></td>
                                    <td><?php echo date('M j, Y', strtotime($row['reg_date'])); ?></td>
                                </tr>
                            <?php }
                        } else { ?>
                            <tr>
                                <td colspan="4" class="text-center">
                                    <i class="fas fa-info-circle"></i>
                                    No users found
                                </td>
                            </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- View Shared Entries Section -->
        <div id="view_copy_report" class="content-section">
            <div class="section-header">
                <h2 class="section-title">
                    <i class="fas fa-share"></i>
                    Today's Shared Entries
                </h2>
                <button class="back-btn" onclick="showSection('dashboard-overview')">
                    <i class="fas fa-arrow-left"></i>
                    Back to Dashboard
                </button>
            </div>

            <div class="table-container">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th><i class="fas fa-user"></i> User</th>
                            <th><i class="fas fa-gamepad"></i> Game</th>
                            <th><i class="fas fa-tag"></i> Type</th>
                            <th><i class="fas fa-layer-group"></i> Subtype</th>
                            <th><i class="fas fa-hashtag"></i> Number</th>
                            <th><i class="fas fa-rupee-sign"></i> Amount</th>
                            <th><i class="fas fa-clock"></i> Time</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $shared_entries = [];
                        $res = mysqli_query($link, "SELECT * FROM entries_shared WHERE DATE(entry_time) = '$today'");
                        while ($row = mysqli_fetch_assoc($res)) {
                            $shared_entries[] = $row;
                        }
                        
                        if (!empty($shared_entries)) {
                            foreach ($shared_entries as $entry) { ?>
                                <tr>
                                    <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><?php echo htmlspecialchars($entry['number']); ?></td>
                                    <td>₹<?php echo number_format($entry['amount']); ?></td>
                                    <td><?php echo date('H:i:s', strtotime($entry['entry_time'])); ?></td>
                                </tr>
                            <?php }
                        } else { ?>
                            <tr>
                                <td colspan="7" class="text-center">
                                    <i class="fas fa-info-circle"></i>
                                    No shared entries found for today
                                </td>
                            </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>
        </div>
    </main>

    <script>
        // Section management
        function showSection(sectionId) {
            // Hide all sections
            const sections = document.querySelectorAll('.content-section');
            sections.forEach(section => {
                section.classList.remove('active');
            });
            
            // Show target section
            const targetSection = document.getElementById(sectionId);
            if (targetSection) {
                targetSection.classList.add('active');
            }
        }

        // Auto-refresh functionality
        let autoRefresh = false;
        function toggleAutoRefresh() {
            autoRefresh = !autoRefresh;
            if (autoRefresh) {
                setInterval(() => {
                    if (document.getElementById('dashboard-overview').classList.contains('active')) {
                        location.reload();
                    }
                }, 30000); // Refresh every 30 seconds
            }
        }

        // Handle URL parameters for showing specific sections
        document.addEventListener('DOMContentLoaded', function() {
            const urlParams = new URLSearchParams(window.location.search);
            const sectionToShow = urlParams.get('show_section');
            
            if (sectionToShow) {
                showSection(sectionToShow);
            }

            // Set today's date as default for date inputs
            const dateInputs = document.querySelectorAll('input[type="date"]');
            const today = new Date().toISOString().split('T')[0];
            dateInputs.forEach(input => {
                if (!input.value) {
                    input.value = today;
                }
            });
        });

        // Form validation
        function validateForm(form) {
            // Skip validation for add result form - let HTML5 validation handle it
            if (form.querySelector('button[name="add_result_submit"]')) {
                return true;
            }
            
            const requiredFields = form.querySelectorAll('[required]');
            let valid = true;
            
            requiredFields.forEach(field => {
                if (!field.value.trim()) {
                    field.style.borderColor = '#ef4444';
                    valid = false;
                } else {
                    field.style.borderColor = '';
                }
            });
            
            return valid;
        }

        // Add form submission handlers
        document.querySelectorAll('form').forEach(form => {
            form.addEventListener('submit', function(e) {
                console.log('Form submitted:', this);
                console.log('Form data:', new FormData(this));
                
                // Skip validation for add_result form to prevent blocking
                if (this.querySelector('input[name="add_result_submit"]') || this.querySelector('button[name="add_result_submit"]')) {
                    console.log('Add result form - allowing submission');
                    return true;
                }
                
                if (!validateForm(this)) {
                    e.preventDefault();
                    alert('Please fill in all required fields.');
                    return false;
                }
                
                // Log that form validation passed
                console.log('Form validation passed');
            });
        });

        // Add loading states to buttons
        document.querySelectorAll('button[type="submit"]').forEach(button => {
            button.addEventListener('click', function(e) {
                // Skip loading state for add result button to prevent blocking
                if (this.name === 'add_result_submit') {
                    console.log('Add result button clicked - allowing immediate submission');
                    return true;
                }
                
                // Only add loading state if form is valid
                const form = this.closest('form');
                if (form && validateForm(form)) {
                    this.classList.add('loading');
                    this.disabled = true;
                    
                    // Re-enable after 10 seconds as fallback
                    setTimeout(() => {
                        this.classList.remove('loading');
                        this.disabled = false;
                    }, 10000);
                }
            });
        });

        // Auto-hide alerts after 5 seconds
        document.querySelectorAll('.alert').forEach(alert => {
            setTimeout(() => {
                alert.style.opacity = '0';
                setTimeout(() => {
                    alert.remove();
                }, 300);
            }, 5000);
        });
    </script>
</body>
</html>