<?php
require_once 'admin_init.php';



require_once 'includes/header.php';
$conn = $conn_header;

// নিরাপদ ফাংশন যা টেবিল থেকে গণনা করে
function get_count_from_table($conn, $tableName) {
    
    $checkTable = $conn->query("SHOW TABLES LIKE '{$tableName}'");
    if ($checkTable->num_rows > 0) {
        $result = $conn->query("SELECT COUNT(*) as count FROM {$tableName}");
        return $result ? $result->fetch_assoc()['count'] : 0;
    }
    return 0;
}

// নিরাপদ ফাংশন যা মোট আয় গণনা করে
function get_total_earnings_from_table($conn, $tableName, $amountColumn = 'amount') {
    // এই ফাংশনটি ব্যবহারের আগে নিশ্চিত করুন যে আপনার আয়ের টেবিল এবং কলামের নাম সঠিক
    // উদাহরণ: get_total_earnings_from_table($conn, 'user_earnings', 'earned_amount');
    $checkTable = $conn->query("SHOW TABLES LIKE '{$tableName}'");
    if ($checkTable->num_rows > 0) {
        // চেক করুন কলামটি আছে কিনা
        $checkColumn = $conn->query("SHOW COLUMNS FROM {$tableName} LIKE '{$amountColumn}'");
        if ($checkColumn->num_rows > 0) {
            $result = $conn->query("SELECT SUM({$amountColumn}) as total FROM {$tableName}");
            return $result ? ($result->fetch_assoc()['total'] ?? 0) : 0;
        }
    }
    return 0;
}

// --- পরিসংখ্যান ---
$total_users = get_count_from_table($conn, 'users');
$pending_withdrawals = get_count_from_table($conn, 'withdrawals_pending');
$withdraw_methods = get_count_from_table($conn, 'withdraw_methods');

// --- টাস্ক সংখ্যা ---
$adsterra_tasks_total = get_count_from_table($conn, 'adsterra_tasks');
$monetag_tasks_total = get_count_from_table($conn, 'monetag_tasks');
$gigapub_tasks_total = get_count_from_table($conn, 'website_ads');
$telegram_tasks_total = get_count_from_table($conn, 'telegram_tasks');

// --- গ্রাফের জন্য মোট আয় (উদাহরণ হিসেবে মান দেওয়া হলো, আপনি আপনার ডাটাবেস থেকে আনবেন) ---
// নিচের মানগুলো আপনার ডাটাবেসের আসল ডেটা দিয়ে প্রতিস্থাপন করুন
$earnings_telegram = 550.75;  // مثال: get_total_earnings_from_table($conn, 'earnings_log', 'amount', "WHERE type='telegram'");
$earnings_gigapub = 320.50;
$earnings_adsterra = 810.20;
$earnings_monetag = 480.00;
$earnings_visit = 250.90;    // Visit tasks
?>

<!-- ======================= CSS স্টাইল (অপরিবর্তিত) ======================= -->
<style>
    body::before {
        content: ''; position: fixed; top: -50%; left: -50%; width: 200%; height: 200%;
        background: radial-gradient(circle at 20% 20%, rgba(0, 123, 255, 0.2), transparent 30%),
                    radial-gradient(circle at 80% 30%, rgba(40, 167, 69, 0.2), transparent 30%),
                    radial-gradient(circle at 50% 80%, rgba(255, 193, 7, 0.2), transparent 30%);
        animation: animateBackground 20s linear infinite; z-index: -1; filter: blur(100px);
    }
    @keyframes animateBackground { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
    .dashboard-container h2 { color: var(--text-dark); margin-bottom: 25px; font-size: 2em; }
    .stats-grid-container { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 25px; }
    .stat-card-link { text-decoration: none; color: inherit; }
    @keyframes pulse-glow {
        0%, 100% { box-shadow: 0 0 5px 0px var(--glow-color-soft); }
        50% { box-shadow: 0 0 20px 5px var(--glow-color-soft); }
    }
    .stat-card {
        background: rgba(255, 255, 255, 0.5); backdrop-filter: blur(12px);
        border: 1px solid rgba(255, 255, 255, 0.2); border-radius: 18px;
        padding: 25px; position: relative; overflow: hidden;
        transition: all 0.3s ease; animation: pulse-glow 4s infinite ease-in-out;
    }
    .stat-card:hover { transform: translateY(-10px); animation-duration: 2s; box-shadow: 0 16px 40px 0 rgba(31, 38, 135, 0.2); }
    .stat-card > * { position: relative; z-index: 1; }
    .stat-card-header { display: flex; align-items: center; gap: 15px; margin-bottom: 15px; color: var(--text-dark); }
    .stat-card-icon { width: 50px; height: 50px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 1.5em; color: #fff; }
    .stat-card-title h3 { margin: 0; font-size: 1.3em; font-weight: 600; }
    .stat-card-body .value { font-size: 2.5em; font-weight: 700; color: var(--text-dark); margin: 0; }
    .stat-card-body p { margin: 5px 0 0; color: var(--text-muted); }
    .card-users { --glow-color-soft: rgba(0, 123, 255, 0.5); }
    .card-withdraw { --glow-color-soft: rgba(40, 167, 69, 0.5); }
    .card-methods { --glow-color-soft: rgba(255, 193, 7, 0.5); }
    .card-adsterra { --glow-color-soft: rgba(23, 162, 184, 0.5); }
    .card-monetag { --glow-color-soft: rgba(253, 126, 20, 0.5); }
    .card-gigapub { --glow-color-soft: rgba(220, 53, 69, 0.5); }
    .card-telegram { --glow-color-soft: rgba(0, 136, 204, 0.5); }
    .card-notification { --glow-color-soft: rgba(108, 99, 255, 0.5); }
    .card-settings { --glow-color-soft: rgba(108, 117, 125, 0.5); }
    .analytics-card { --glow-color-soft: rgba(111, 66, 193, 0.5); margin-top: 25px; }
    .bg-icon-users { background: linear-gradient(45deg, #007bff, #0056b3); }
    .bg-icon-withdraw { background: linear-gradient(45deg, #28a745, #1e7e34); }
    .bg-icon-methods { background: linear-gradient(45deg, #ffc107, #d39e00); }
    .bg-icon-adsterra { background: linear-gradient(45deg, #17a2b8, #117a8b); }
    .bg-icon-monetag { background: linear-gradient(45deg, #fd7e14, #d35400); }
    .bg-icon-gigapub { background: linear-gradient(45deg, #dc3545, #a71d2a); }
    .bg-icon-telegram { background: linear-gradient(45deg, #0088cc, #3498db); }
    .bg-icon-notification { background: linear-gradient(45deg, #6c63ff, #4d44b4); }
    .bg-icon-settings { background: linear-gradient(45deg, #6c757d, #495057); }
</style>

<!-- ======================= HTML কন্টেন্ট (সম্পূর্ণ এবং অপরিবর্তিত) ======================= -->
<div class="dashboard-container">
    <h2>Dashboard</h2>
    <div class="stats-grid-container">
        
        <!-- Users Card -->
        <a href="users.php" class="stat-card-link">
            <div class="stat-card card-users">
                <div class="stat-card-header">
                    <div class="stat-card-icon bg-icon-users"><i class="fas fa-users"></i></div>
                    <div class="stat-card-title"><h3>Total Users</h3></div>
                </div>
                <div class="stat-card-body"><p class="value"><?= $total_users; ?></p></div>
            </div>
        </a>

        <!-- Pending Withdrawals Card -->
        <a href="completed_tasks.php" class="stat-card-link">
            <div class="stat-card card-withdraw">
                <div class="stat-card-header">
                    <div class="stat-card-icon bg-icon-withdraw"><i class="fas fa-hourglass-half"></i></div>
                    <div class="stat-card-title"><h3>Total Task  </h3></div>
                </div>
                <div class="stat-card-body"><p class="value"><?= $pending_withdrawals; ?></p></div>
            </div>
        </a>
        
        <!-- Withdraw Methods Card -->
        <a href="withdrawals.php" class="stat-card-link">
            <div class="stat-card card-methods">
                <div class="stat-card-header">
                    <div class="stat-card-icon bg-icon-methods"><i class="fas fa-credit-card"></i></div>
                    <div class="stat-card-title"><h3>Withdraw Methods</h3></div>
                </div>
                <div class="stat-card-body"><p class="value"><?= $withdraw_methods; ?></p></div>
            </div>
        </a>

        <!-- Adsterra Task Card -->
        <a href="gigapub_settings.php" class="stat-card-link">
            <div class="stat-card card-adsterra">
                <div class="stat-card-header">
                    <div class="stat-card-icon bg-icon-adsterra"><i class="fas fa-rocket"></i></div>
                    <div class="stat-card-title"><h3>Giga pub  Tasks</h3></div>
                </div>
                <div class="stat-card-body"><p class="value"><?= $adsterra_tasks_total; ?></p><p>Total available tasks</p></div>
            </div>
        </a>

        <!-- MoneTag Task Card -->
        <a href="monetag_settings.php" class="stat-card-link">
            <div class="stat-card card-monetag">
                <div class="stat-card-header">
                    <div class="stat-card-icon bg-icon-monetag"><i class="fas fa-tags"></i></div>
                    <div class="stat-card-title"><h3>MoneTag Tasks</h3></div>
                </div>
                <div class="stat-card-body"><p class="value"><?= $monetag_tasks_total; ?></p><p>Total available tasks</p></div>
            </div>
        </a>
        
        <!-- GigaPub Task Card -->
        <a href="adsterra_settings.php" class="stat-card-link">
            <div class="stat-card card-gigapub">
                <div class="stat-card-header">
                    <div class="stat-card-icon bg-icon-gigapub"><i class="fas fa-mouse-pointer"></i></div>
                    <div class="stat-card-title"><h3>Adsterra (Visit) Tasks</h3></div>
                </div>
                <div class="stat-card-body"><p class="value"><?= $gigapub_tasks_total; ?></p><p>Total available sites</p></div>
            </div>
        </a>

        <!-- Telegram Task Card -->
        <a href="telegram_tasks.php" class="stat-card-link">
            <div class="stat-card card-telegram">
                <div class="stat-card-header">
                    <div class="stat-card-icon bg-icon-telegram"><i class="fab fa-telegram-plane"></i></div>
                    <div class="stat-card-title"><h3>Telegram Tasks</h3></div>
                </div>
                <div class="stat-card-body"><p class="value"><?= $telegram_tasks_total; ?></p><p>Total available tasks</p></div>
            </div>
        </a>

        <!-- Bot Notification Card -->
        <a href="notifications.php" class="stat-card-link">
            <div class="stat-card card-notification">
                <div class="stat-card-header">
                    <div class="stat-card-icon bg-icon-notification"><i class="fas fa-paper-plane"></i></div>
                    <div class="stat-card-title"><h3>Bot Notifications</h3></div>
                </div>
                <div class="stat-card-body"><p style="font-size: 1em;">Send messages to all users directly from here.</p></div>
            </div>
        </a>

        <!-- Settings Card -->
        <a href="settings.php" class="stat-card-link">
            <div class="stat-card card-settings">
                <div class="stat-card-header">
                    <div class="stat-card-icon bg-icon-settings"><i class="fas fa-cog"></i></div>
                    <div class="stat-card-title"><h3>System Settings</h3></div>
                </div>
                <div class="stat-card-body"><p style="font-size: 1em;">Manage your bot and dashboard settings.</p></div>
            </div>
        </a>

    </div>

    <!-- ======================= নতুন অ্যানালিটিক্স গ্রাফ কার্ড ======================= -->
    <div class="stat-card analytics-card">
        <div class="stat-card-header">
            <div class="stat-card-icon" style="background: linear-gradient(45deg, #6f42c1, #4a238e);"><i class="fas fa-chart-bar"></i></div>
            <div class="stat-card-title"><h3>Task Earnings Analytics</h3></div>
        </div>
        <div class="stat-card-body">
            <canvas id="earningsChart" style="height: 300px; width: 100%;"></canvas>
        </div>
    </div>
</div>

<!-- ======================= গ্রাফের জন্য JS কোড ======================= -->
<!-- Chart.js লাইব্রেরি যোগ করা -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const earningsData = {
            telegram: <?= json_encode($earnings_telegram, JSON_NUMERIC_CHECK) ?>,
            gigaPub: <?= json_encode($earnings_gigapub, JSON_NUMERIC_CHECK) ?>,
            adsterra: <?= json_encode($earnings_adsterra, JSON_NUMERIC_CHECK) ?>,
            moneTag: <?= json_encode($earnings_monetag, JSON_NUMERIC_CHECK) ?>,
            visit: <?= json_encode($earnings_visit, JSON_NUMERIC_CHECK) ?>
        };

        const ctx = document.getElementById('earningsChart').getContext('2d');
        new Chart(ctx, {
            type: 'bar',
            data: {
                labels: ['Telegram', 'GigaPub', 'Adsterra', 'MoneTag', 'Visit'],
                datasets: [{
                    label: 'Total Earnings (৳)',
                    data: [
                        earningsData.telegram, 
                        earningsData.gigaPub, 
                        earningsData.adsterra, 
                        earningsData.moneTag, 
                        earningsData.visit
                    ],
                    backgroundColor: [
                        'rgba(0, 136, 204, 0.7)',  'rgba(220, 53, 69, 0.7)',   
                        'rgba(23, 162, 184, 0.7)', 'rgba(253, 126, 20, 0.7)',
                        'rgba(108, 99, 255, 0.7)'
                    ],
                    borderColor: [
                        '#0088cc', '#dc3545', '#17a2b8', '#fd7e14', '#6c63ff'
                    ],
                    borderWidth: 1.5,
                    borderRadius: 5,
                    barThickness: 'flex',
                    maxBarThickness: 50
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: { color: 'var(--text-dark)' },
                        grid: { color: 'rgba(0, 0, 0, 0.1)' }
                    },
                    x: {
                        ticks: { color: 'var(--text-dark)' },
                        grid: { display: false }
                    }
                },
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        backgroundColor: 'rgba(0,0,0,0.8)',
                        callbacks: {
                            label: (context) => `৳${context.parsed.y.toFixed(2)}`
                        }
                    }
                }
            }
        });
    });
</script>

<?php require_once 'includes/footer.php'; ?>