<?php
session_start();
include 'config.php';
include 'logger.php';

if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: index.php");
    exit;
}

event_log('view', 'Dashboard görüntülendi', ['admin' => $_SESSION['admin_user'] ?? 'unknown']);

// Tarih filtresi
$start = isset($_GET['start']) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $_GET['start']) ? $_GET['start'] : date('Y-m-d', strtotime('-7 days'));
$end   = isset($_GET['end'])   && preg_match('/^\d{4}-\d{2}-\d{2}$/', $_GET['end'])   ? $_GET['end']   : date('Y-m-d');

// Fetch total user count
$totalUsersStmt = $pdo->query("SELECT COUNT(*) as total_users FROM kullanicilar");
$totalUsers = $totalUsersStmt->fetch(PDO::FETCH_ASSOC)['total_users'];

// Fetch weekly user growth
$weeklyGrowthStmt = $pdo->prepare("SELECT COUNT(*) as new_users, DATE(created_at) as created_date FROM kullanicilar WHERE DATE(created_at) BETWEEN :start AND :end GROUP BY created_date ORDER BY created_date");
$weeklyGrowthStmt->execute([':start' => $start, ':end' => $end]);
$weeklyGrowthData = $weeklyGrowthStmt->fetchAll(PDO::FETCH_ASSOC);

// Prepare data for the chart
$dates = [];
$newUsers = [];
foreach ($weeklyGrowthData as $data) {
    $dates[] = $data['created_date'];
    $newUsers[] = $data['new_users'];
}

// Yeni üye sayısı (seçilen aralık)
$newUsersCountStmt = $pdo->prepare("SELECT COUNT(*) as cnt FROM kullanicilar WHERE DATE(created_at) BETWEEN :start AND :end");
$newUsersCountStmt->execute([':start' => $start, ':end' => $end]);
$newUsersCount = (int)$newUsersCountStmt->fetch(PDO::FETCH_ASSOC)['cnt'];

// Kar/Zarar (seçilen aralık)
$profitStmt = $pdo->prepare("
    SELECT 
        SUM(CASE 
            WHEN LOWER(type) LIKE '%deposit%' OR LOWER(type) LIKE '%yat%' THEN amount
            WHEN LOWER(type) LIKE '%withdraw%' OR LOWER(type) LIKE '%cek%' OR LOWER(type) LIKE '%win%' OR LOWER(type) LIKE '%kaz%' THEN -amount
            ELSE 0 
        END) AS net_profit
    FROM transactions
    WHERE DATE(created_at) BETWEEN :start AND :end
");
$profitStmt->execute([':start' => $start, ':end' => $end]);
$netProfit = (float)($profitStmt->fetch(PDO::FETCH_ASSOC)['net_profit'] ?? 0);

// İşlem türü bazında toplamlar
$byTypeStmt = $pdo->prepare("SELECT LOWER(type) as type, SUM(amount) total FROM transactions WHERE DATE(created_at) BETWEEN :start AND :end GROUP BY LOWER(type) ORDER BY total DESC");
$byTypeStmt->execute([':start' => $start, ':end' => $end]);
$typeTotals = $byTypeStmt->fetchAll(PDO::FETCH_ASSOC);

// Günlük kar/zarar grafiği verisi
$dailyProfitStmt = $pdo->prepare("
    SELECT DATE(created_at) as d,
           SUM(CASE 
                WHEN LOWER(type) LIKE '%deposit%' OR LOWER(type) LIKE '%yat%' THEN amount
                WHEN LOWER(type) LIKE '%withdraw%' OR LOWER(type) LIKE '%cek%' OR LOWER(type) LIKE '%win%' OR LOWER(type) LIKE '%kaz%' THEN -amount
                ELSE 0
           END) as profit
    FROM transactions
    WHERE DATE(created_at) BETWEEN :start AND :end
    GROUP BY DATE(created_at)
    ORDER BY DATE(created_at)
");
$dailyProfitStmt->execute([':start' => $start, ':end' => $end]);
$dailyProfitData = $dailyProfitStmt->fetchAll(PDO::FETCH_ASSOC);
$profitDates = array_column($dailyProfitData, 'd');
$profitValues = array_map('floatval', array_column($dailyProfitData, 'profit'));

// Son kullanıcılar
$recentUsersStmt = $pdo->query("SELECT id, username, email, created_at FROM kullanicilar ORDER BY created_at DESC LIMIT 10");
$recentUsers = $recentUsersStmt->fetchAll(PDO::FETCH_ASSOC);

// Son işlemler
$recentTxStmt = $pdo->query("SELECT id, user_id, amount, type, created_at FROM transactions ORDER BY created_at DESC LIMIT 10");
$recentTx = $recentTxStmt->fetchAll(PDO::FETCH_ASSOC);

// Top oyunlar (seçilen aralık)
$topGamesStmt = $pdo->prepare("
    SELECT COALESCE(g.game_name, t.game) as game_name, COUNT(*) as cnt
    FROM transactions t
    LEFT JOIN games g ON t.game = g.game_code
    WHERE DATE(t.created_at) BETWEEN :start AND :end
    GROUP BY COALESCE(g.game_name, t.game)
    ORDER BY cnt DESC
    LIMIT 10
");
$topGamesStmt->execute([':start' => $start, ':end' => $end]);
$topGames = $topGamesStmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Paneli</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">
    <link rel="stylesheet" href="styles.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <?php include 'sidebar.php'; ?>

            <!-- Main Content -->
            <div class="col-md-10 p-4">
                <?php include __DIR__ . '/topbar.php'; ?>
                <h1>Hoşgeldiniz, Admin</h1>
                <p class="text-muted">Seçilen tarih aralığına göre sistem metrikleri ve özetler.</p>

                <!-- Tarih Filtresi -->
                <form class="row g-3 mb-4" method="GET" action="dashboard.php">
                    <div class="col-auto">
                        <input type="date" name="start" class="form-control" value="<?= htmlspecialchars($start) ?>">
                    </div>
                    <div class="col-auto">
                        <input type="date" name="end" class="form-control" value="<?= htmlspecialchars($end) ?>">
                    </div>
                    <div class="col-auto">
                        <button type="submit" class="btn btn-primary">Filtrele</button>
                    </div>
                </form>

                <!-- Total Users Card -->
                <div class="card mb-4">
                    <div class="card-body">
                        <h5 class="card-title">Toplam Kullanıcı Sayısı</h5>
                        <p class="card-text"><?= htmlspecialchars($totalUsers) ?> kullanıcı bulunmaktadır.</p>
                    </div>
                </div>

                <!-- Yeni Üye ve Kar/Zarar Kartları -->
                <div class="row mb-4">
                    <div class="col-md-6">
                        <div class="card h-100">
                            <div class="card-body">
                                <h5 class="card-title">Yeni Üyeler (<?= htmlspecialchars($start) ?> - <?= htmlspecialchars($end) ?>)</h5>
                                <p class="display-6 text-success mb-0"><?= htmlspecialchars($newUsersCount) ?></p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="card h-100">
                            <div class="card-body">
                                <h5 class="card-title">Kar / Zarar (<?= htmlspecialchars($start) ?> - <?= htmlspecialchars($end) ?>)</h5>
                                <?php $profitClass = $netProfit >= 0 ? 'text-success' : 'text-danger'; ?>
                                <p class="display-6 <?= $profitClass ?> mb-0"><?= number_format($netProfit, 2) ?> ₺</p>
                                <small class="text-muted">Not: Tür adlarına göre heuristik sınıflandırma ile hesaplanır.</small>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Weekly Growth Chart -->
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">Yeni Üye Grafiği</h5>
                        <div class="chart-wrapper" style="position: relative; width: 100%; height: 300px;">
                            <canvas id="weeklyGrowthChart"></canvas>
                        </div>
                    </div>
                </div>

                <!-- Günlük Kar/Zarar Grafiği -->
                <div class="card mt-4">
                    <div class="card-body">
                        <h5 class="card-title">Günlük Kar/Zarar</h5>
                        <div class="chart-wrapper" style="position: relative; width: 100%; height: 300px;">
                            <canvas id="dailyProfitChart"></canvas>
                        </div>
                    </div>
                </div>

                <!-- Tür Bazında İşlem Toplamları -->
                <div class="card mt-4">
                    <div class="card-body">
                        <h5 class="card-title">İşlem Türlerine Göre Toplamlar</h5>
                        <div class="table-responsive">
                            <table class="table table-sm table-striped">
                                <thead>
                                    <tr>
                                        <th>Tür</th>
                                        <th>Toplam</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($typeTotals as $row): ?>
                                    <tr>
                                        <td><?= htmlspecialchars($row['type'] ?? 'bilinmiyor') ?></td>
                                        <td><?= number_format((float)$row['total'], 2) ?> ₺</td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Top Oyunlar -->
                <div class="card mt-4">
                    <div class="card-body">
                        <h5 class="card-title">En Çok İşlem Yapılan Oyunlar</h5>
                        <div class="table-responsive">
                            <table class="table table-sm table-striped">
                                <thead>
                                    <tr>
                                        <th>Oyun</th>
                                        <th>İşlem Sayısı</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($topGames as $g): ?>
                                    <tr>
                                        <td><?= htmlspecialchars($g['game_name'] ?: 'Bilinmiyor') ?></td>
                                        <td><?= (int)$g['cnt'] ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Son Kullanıcılar ve Son İşlemler -->
                <div class="row mt-4">
                    <div class="col-md-6">
                        <div class="card h-100">
                            <div class="card-body">
                                <h5 class="card-title">Son Kullanıcılar</h5>
                                <div class="table-responsive">
                                    <table class="table table-sm table-striped">
                                        <thead>
                                            <tr>
                                                <th>ID</th>
                                                <th>Kullanıcı</th>
                                                <th>E-posta</th>
                                                <th>Oluşturulma</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($recentUsers as $u): ?>
                                            <tr>
                                                <td><?= (int)$u['id'] ?></td>
                                                <td><?= htmlspecialchars($u['username']) ?></td>
                                                <td><?= htmlspecialchars($u['email'] ?? '-') ?></td>
                                                <td><?= htmlspecialchars($u['created_at']) ?></td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="card h-100">
                            <div class="card-body">
                                <h5 class="card-title">Son İşlemler</h5>
                                <div class="table-responsive">
                                    <table class="table table-sm table-striped">
                                        <thead>
                                            <tr>
                                                <th>ID</th>
                                                <th>Kullanıcı ID</th>
                                                <th>Tutar</th>
                                                <th>Tür</th>
                                                <th>Tarih</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($recentTx as $t): ?>
                                            <tr>
                                                <td><?= (int)$t['id'] ?></td>
                                                <td><?= (int)$t['user_id'] ?></td>
                                                <td><?= number_format((float)$t['amount'], 2) ?> ₺</td>
                                                <td><?= htmlspecialchars($t['type']) ?></td>
                                                <td><?= htmlspecialchars($t['created_at']) ?></td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Weekly Growth Chart
        const ctx = document.getElementById('weeklyGrowthChart').getContext('2d');
        // Destroy previous instance if exists to prevent growth/duplication
        if (window._weeklyGrowthChart) {
            try { window._weeklyGrowthChart.destroy(); } catch (e) {}
        }
        const weeklyGrowthChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: <?= json_encode($dates) ?>,
                datasets: [{
                    label: 'Yeni Kullanıcılar',
                    data: <?= json_encode($newUsers) ?>,
                    borderColor: '#FFD700',
                    backgroundColor: 'rgba(255, 215, 0, 0.2)',
                    borderWidth: 2,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: { color: '#333' },
                        ticks: { color: '#fff' }
                    },
                    x: {
                        grid: { color: '#333' },
                        ticks: { color: '#fff' }
                    }
                },
                plugins: {
                    legend: { labels: { color: '#fff' } }
                }
            }
        });
        window._weeklyGrowthChart = weeklyGrowthChart;

        // Daily Profit Chart
        const ctxProfit = document.getElementById('dailyProfitChart').getContext('2d');
        // Destroy previous instance if exists to prevent growth/duplication
        if (window._dailyProfitChart) {
            try { window._dailyProfitChart.destroy(); } catch (e) {}
        }
        const dailyProfitChart = new Chart(ctxProfit, {
            type: 'bar',
            data: {
                labels: <?= json_encode($profitDates) ?>,
                datasets: [{
                    label: 'Kar/Zarar',
                    data: <?= json_encode($profitValues) ?>,
                    backgroundColor: 'rgba(0, 201, 87, 0.5)',
                    borderColor: '#00C957',
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: { color: '#333' },
                        ticks: { color: '#fff' }
                    },
                    x: {
                        grid: { color: '#333' },
                        ticks: { color: '#fff' }
                    }
                },
                plugins: {
                    legend: { labels: { color: '#fff' } }
                }
            }
        });
        window._dailyProfitChart = dailyProfitChart;
    </script>
</body>
</html>
<script src="admin.js"></script>
