<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    header("Location: login.php");
    exit;
}

// اتصال به دیتابیس
require_once 'config.php';
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

try {
    // تعداد کل کاربران
    $total_users = $db->query("SELECT COUNT(*) FROM Users")->fetchColumn();

    // کاربران فعال امروز
    $today = date("Y-m-d");
    $active_today_stmt = $db->prepare("SELECT COUNT(*) FROM Users WHERE DATE(LastVisit) = ?");
    $active_today_stmt->execute([$today]);
    $active_today_count = $active_today_stmt->fetchColumn();
    
    // کاربران فعال مینی‌اپ (تلگرام) امروز از جدول Users
    $miniapp_today_stmt = $db->prepare("SELECT COUNT(*) FROM Users WHERE DATE(LastMiniAppVisit) = ?");
    $miniapp_today_stmt->execute([$today]);
    $miniapp_today_count = $miniapp_today_stmt->fetchColumn();
    
    // بازدیدکنندگان مینی‌اپ (وب/guest) امروز
    $guest_today_stmt = $db->prepare("SELECT COUNT(*) FROM MiniAppGuests WHERE DATE(last_visit) = ?");
    $guest_today_stmt->execute([$today]);
    $guest_today_count = $guest_today_stmt->fetchColumn();
    
    // مجموعِ فعال امروز (ربات + مینی‌اپ تلگرام + مینی‌اپ وب/guest)
    $active_any_stmt = $db->prepare("
        SELECT COUNT(*) FROM Users
        WHERE (LastVisit IS NOT NULL AND DATE(LastVisit) = ?)
           OR (LastMiniAppVisit IS NOT NULL AND DATE(LastMiniAppVisit) = ?)
    ");
    $active_any_stmt->execute([$today, $today]);
    $active_any_count = $active_any_stmt->fetchColumn();
    
    $total_active_all = (int)$active_any_count + (int)$guest_today_count; // جمعِ تلگرام‌ها + guest


    // جدیدترین کاربر
    $newest_user = $db->query("SELECT UserId, LastVisit FROM Users ORDER BY LastVisit DESC LIMIT 1")->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $error = "❌ خطا در ارتباط با دیتابیس: " . $e->getMessage();
}
?>

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>آمار ربات</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        body {
            font-family: 'Vazirmatn', sans-serif;
        }
    </style>
    <link href="https://fonts.googleapis.com/css2?family=Vazirmatn:wght@400;500;700&display=swap" rel="stylesheet">
</head>
<body class="bg-gray-100 min-h-screen flex items-center justify-center p-4">
    <div class="bg-white rounded-2xl shadow-xl p-8 w-full max-w-2xl">
        <h2 class="text-2xl font-bold text-center text-gray-800 mb-6">📊 آمار کلی ربات</h2>

        <?php if (isset($error)): ?>
            <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded-lg mb-6 animate-fade-in">
                <?= htmlspecialchars($error) ?>
            </div>
        <?php endif; ?>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div class="bg-gray-50 p-4 rounded-lg shadow-sm">
                <div class="flex items-center space-x-2">
                    <span class="text-xl">👤</span>
                    <h3 class="text-lg font-medium text-gray-700">کل کاربران</h3>
                </div>
                <p class="text-2xl font-bold text-blue-600 mt-2"><?= number_format($total_users) ?></p>
            </div>

            <div class="bg-gray-50 p-4 rounded-lg shadow-sm">
                <div class="flex items-center space-x-2">
                    <span class="text-xl">🕐</span>
                    <h3 class="text-lg font-medium text-gray-700">کاربران فعال امروز</h3>
                </div>
                <p class="text-2xl font-bold text-blue-600 mt-2"><?= number_format($active_today_count) ?></p>
            </div>
            
<div class="bg-gray-50 p-4 rounded-lg shadow-sm">
  <div class="flex items-center space-x-2">
    <span class="text-xl">📱</span>
    <h3 class="text-lg font-medium text-gray-700">کاربران فعال مینی‌اپ (تلگرام) امروز</h3>
  </div>
  <p class="text-2xl font-bold text-blue-600 mt-2"><?= number_format($miniapp_today_count ?? 0) ?></p>
</div>

<div class="bg-gray-50 p-4 rounded-lg shadow-sm">
  <div class="flex items-center space-x-2">
    <span class="text-xl">🌐</span>
    <h3 class="text-lg font-medium text-gray-700">بازدیدکنندگان مینی‌اپ (وب/Guest) امروز</h3>
  </div>
  <p class="text-2xl font-bold text-blue-600 mt-2"><?= number_format($guest_today_count ?? 0) ?></p>
</div>

<div class="bg-gray-50 p-4 rounded-lg shadow-sm md:col-span-2">
  <div class="flex items-center space-x-2">
    <span class="text-xl">✅</span>
    <h3 class="text-lg font-medium text-gray-700">کل فعال امروز (ربات + مینی‌اپ تلگرام + وب)</h3>
  </div>
  <p class="text-2xl font-bold text-blue-600 mt-2"><?= number_format($total_active_all ?? 0) ?></p>
</div>


            <div class="bg-gray-50 p-4 rounded-lg shadow-sm md:col-span-2">
                <div class="flex items-center space-x-2">
                    <span class="text-xl">🆕</span>
                    <h3 class="text-lg font-medium text-gray-700">جدیدترین عضو</h3>
                </div>
                    <p class="text-lg text-gray-600 mt-2">
                        <strong>کاربر ناشناس</strong>
                        (<?= htmlspecialchars($newest_user['UserId'] ?? 'نامشخص') ?>) — 
                        <?= htmlspecialchars($newest_user['LastVisit'] ?? 'نامشخص') ?>
                    </p>
            </div>
        </div>

        <div class="mt-8 text-center">
            <a href="dashboard.php" class="text-blue-600 hover:text-blue-800 font-medium">⬅️ بازگشت به داشبورد</a>
        </div>
    </div>

    <script>
        const cards = document.querySelectorAll('.bg-gray-50');
        cards.forEach(card => {
            card.addEventListener('mouseenter', () => {
                card.classList.add('scale-105', 'shadow-md');
            });
            card.addEventListener('mouseleave', () => {
                card.classList.remove('scale-105', 'shadow-md');
            });
        });
    </script>
</body>
</html>
