<?php
// Gerçek site istatistikleri: MySQL veritabanından hesaplanır
// Bu dosya, admin panelindeki stats.php tarafından JSON olarak tüketilir.

require_once __DIR__ . '/database.php'; // $conn (mysqli)

header('Cache-Control: no-store');

function safe_int($v) { return (int)($v ?? 0); }
function safe_float($v) { return (float)($v ?? 0); }

function getTotalUsers(mysqli $conn) {
    $sql = "SELECT COUNT(*) AS c FROM kullanicilar";
    if ($res = $conn->query($sql)) { $row = $res->fetch_assoc(); return safe_int($row['c'] ?? 0); }
    return 0;
}

function getActiveUsers(mysqli $conn) {
    // "Aktif" kullanıcı: son 24 saatte en az bir işlem yapan benzersiz kullanıcı
    $sql = "SELECT COUNT(DISTINCT user_id) AS c FROM transactions WHERE created_at >= DATE_SUB(NOW(), INTERVAL 1 DAY)";
    if ($res = $conn->query($sql)) { $row = $res->fetch_assoc(); return safe_int($row['c'] ?? 0); }
    return 0;
}

function getTodayBets(mysqli $conn) {
    // Bugünkü toplam bahis tutarı (stake_amount)
    $sql = "SELECT SUM(stake_amount) AS s FROM bets WHERE DATE(bet_date) = CURDATE()";
    if ($res = $conn->query($sql)) { $row = $res->fetch_assoc(); return safe_float($row['s'] ?? 0); }
    return 0.0;
}

function getTotalDeposits(mysqli $conn) {
    // Deposit/Yatırım: type metni üzerinden heuristik
    $sql = "SELECT SUM(amount) AS s FROM transactions WHERE LOWER(type) LIKE '%deposit%' OR LOWER(type) LIKE '%yat%' OR LOWER(type) LIKE '%dep%'";
    if ($res = $conn->query($sql)) { $row = $res->fetch_assoc(); return safe_float($row['s'] ?? 0); }
    return 0.0;
}

function getTotalPayout(mysqli $conn) {
    // Ödeme/Çekim/Kazanç: type metni üzerinden heuristik
    $sql = "SELECT SUM(amount) AS s FROM transactions WHERE LOWER(type) LIKE '%withdraw%' OR LOWER(type) LIKE '%cek%' OR LOWER(type) LIKE '%win%' OR LOWER(type) LIKE '%kaz%'";
    if ($res = $conn->query($sql)) { $row = $res->fetch_assoc(); return safe_float($row['s'] ?? 0); }
    return 0.0;
}

function getRecentWinners(mysqli $conn) {
    // Son kazananlar: Kazandı statüsündeki bahisler
    $out = [];
    $sql = "SELECT username, potential_winnings AS kazanc, bet_date AS tarih FROM bets WHERE status = 'Kazandı' ORDER BY bet_date DESC LIMIT 8";
    if ($res = $conn->query($sql)) {
        while ($row = $res->fetch_assoc()) {
            $out[] = [
                'kullanici_adi' => $row['username'] ?? '-',
                'kazanc' => safe_float($row['kazanc'] ?? 0),
                'tarih' => $row['tarih'] ?? null,
            ];
        }
    }
    return $out;
}

// AJAX isteklerini ele al
if (isset($_GET['action']) && $_GET['action'] === 'get_stats') {
    header('Content-Type: application/json; charset=utf-8');
    
    // Basit sağlık kontrolü: gerekli tablolar var mı?
    $requiredTables = ['kullanicilar', 'transactions', 'bets'];
    $tablesOk = true;
    foreach ($requiredTables as $t) {
        $check = $conn->query("SHOW TABLES LIKE '" . $conn->real_escape_string($t) . "'");
        if (!$check || $check->num_rows === 0) { $tablesOk = false; break; }
        $check && $check->close();
    }

    if (!$tablesOk) {
        echo json_encode([
            'error' => 'Tablolar eksik',
            'total_users' => 0,
            'active_users' => 0,
            'total_payout' => 0,
            'recent_winners' => [],
            'today_bets' => 0,
            'total_deposits' => 0
        ]);
        exit;
    }

    $stats = [
        'total_users' => getTotalUsers($conn),
        'active_users' => getActiveUsers($conn),
        'total_payout' => getTotalPayout($conn),
        'recent_winners' => getRecentWinners($conn),
        'today_bets' => getTodayBets($conn),
        'total_deposits' => getTotalDeposits($conn)
    ];

    echo json_encode($stats);
    exit;
}
?>