<?php
require_once 'config.php';
date_default_timezone_set('Asia/Kolkata');
$today = date('Y-m-d');

echo "<h2>User Count Debug</h2>";

// Check entries for today
echo "<h3>Today's Entries (what admin counts):</h3>";
$res = mysqli_query($link, "SELECT DISTINCT username FROM entries WHERE DATE(entry_time) = '$today'");
if ($res) {
    $count = 0;
    while ($row = mysqli_fetch_assoc($res)) {
        $count++;
        echo "<p>{$count}. Username: " . htmlspecialchars($row['username']) . "</p>";
    }
    echo "<p><strong>Total from entries: {$count}</strong></p>";
} else {
    echo "<p>Error: " . mysqli_error($link) . "</p>";
}

echo "<hr>";

// Check users table
echo "<h3>Users in Users Table (what admin displays):</h3>";
$today_users_from_entries = [];
$res = mysqli_query($link, "SELECT DISTINCT username FROM entries WHERE DATE(entry_time) = '$today'");
if ($res) {
    while ($row = mysqli_fetch_assoc($res)) {
        $today_users_from_entries[] = $row['username'];
    }
}

if (!empty($today_users_from_entries)) {
    $usernames = array_map(function($u) use ($link) {
        return mysqli_real_escape_string($link, $u);
    }, $today_users_from_entries);
    $usernames_str = "'" . implode("','", $usernames) . "'";
    
    $res = mysqli_query($link, "SELECT id, username, usernumber FROM users WHERE username IN ($usernames_str)");
    if ($res) {
        $display_count = 0;
        while ($row = mysqli_fetch_assoc($res)) {
            $display_count++;
            echo "<p>{$display_count}. ID: {$row['id']}, Username: " . htmlspecialchars($row['username']) . ", Number: " . htmlspecialchars($row['usernumber']) . "</p>";
        }
        echo "<p><strong>Total displayed: {$display_count}</strong></p>";
        
        if (count($today_users_from_entries) != $display_count) {
            echo "<p><strong style='color: red;'>MISMATCH: {count($today_users_from_entries)} entries vs {$display_count} users displayed</strong></p>";
            
            echo "<h4>Missing Users (in entries but not in users table):</h4>";
            $found_users = [];
            mysqli_data_seek($res, 0);
            while ($row = mysqli_fetch_assoc($res)) {
                $found_users[] = $row['username'];
            }
            
            $missing = array_diff($today_users_from_entries, $found_users);
            foreach ($missing as $missing_user) {
                echo "<p style='color: red;'>Missing: " . htmlspecialchars($missing_user) . "</p>";
            }
        }
    }
} else {
    echo "<p>No users found for today</p>";
}

mysqli_close($link);
?>