<?php
session_start();
require_once '../config/database.php';

// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit;
}

// Get date range for filtering
$startDate = $_GET['start_date'] ?? date('Y-m-01'); // First day of current month
$endDate = $_GET['end_date'] ?? date('Y-m-d'); // Today

// User Growth Statistics
$stmt = $pdo->prepare("
    SELECT DATE(created_at) as date, COUNT(*) as new_users
    FROM users 
    WHERE created_at BETWEEN ? AND ?
    GROUP BY DATE(created_at)
    ORDER BY date
");
$stmt->execute([$startDate, $endDate . ' 23:59:59']);
$userGrowth = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Product Sales Statistics
$stmt = $pdo->prepare("
    SELECT p.name, COUNT(o.id) as sales_count, SUM(o.total_coins) as total_revenue
    FROM orders o
    JOIN products p ON o.product_id = p.id
    WHERE o.created_at BETWEEN ? AND ? AND o.status = 'completed'
    GROUP BY p.id, p.name
    ORDER BY total_revenue DESC
");
$stmt->execute([$startDate, $endDate . ' 23:59:59']);
$productSales = $stmt->fetchAll(PDO::FETCH_ASSOC);

// AdMob Statistics
$stmt = $pdo->prepare("
    SELECT DATE(viewed_at) as date, COUNT(*) as views, SUM(coins_earned) as total_coins
    FROM video_rewards 
    WHERE viewed_at BETWEEN ? AND ?
    GROUP BY DATE(viewed_at)
    ORDER BY date
");
$stmt->execute([$startDate, $endDate . ' 23:59:59']);
$admobStats = $stmt->fetchAll(PDO::FETCH_ASSOC);

// User Activity Statistics
$stmt = $pdo->prepare("
    SELECT 
        COUNT(DISTINCT u.id) as total_users,
        COUNT(DISTINCT CASE WHEN o.id IS NOT NULL THEN u.id END) as users_with_orders,
        COUNT(DISTINCT CASE WHEN vr.id IS NOT NULL THEN u.id END) as users_with_videos,
        COUNT(DISTINCT CASE WHEN t.id IS NOT NULL THEN u.id END) as users_with_transactions
    FROM users u
    LEFT JOIN orders o ON u.id = o.user_id AND o.created_at BETWEEN ? AND ?
    LEFT JOIN video_rewards vr ON u.id = vr.user_id AND vr.viewed_at BETWEEN ? AND ?
    LEFT JOIN transactions t ON u.id = t.user_id AND t.created_at BETWEEN ? AND ?
");
$stmt->execute([$startDate, $endDate . ' 23:59:59', $startDate, $endDate . ' 23:59:59', $startDate, $endDate . ' 23:59:59']);
$userActivity = $stmt->fetch(PDO::FETCH_ASSOC);

// Overall Statistics
$stmt = $pdo->query("SELECT COUNT(*) as total_users FROM users");
$totalUsers = $stmt->fetch(PDO::FETCH_ASSOC)['total_users'];

$stmt = $pdo->query("SELECT COUNT(*) as total_products FROM products");
$totalProducts = $stmt->fetch(PDO::FETCH_ASSOC)['total_products'];

$stmt = $pdo->query("SELECT COUNT(*) as total_orders FROM orders WHERE status = 'completed'");
$totalOrders = $stmt->fetch(PDO::FETCH_ASSOC)['total_orders'];

$stmt = $pdo->query("SELECT SUM(coins_earned) as total_admob_coins FROM video_rewards");
$totalAdmobCoins = $stmt->fetch(PDO::FETCH_ASSOC)['total_admob_coins'] ?? 0;

$stmt = $pdo->query("SELECT SUM(total_coins) as total_revenue FROM orders WHERE status = 'completed'");
$totalRevenue = $stmt->fetch(PDO::FETCH_ASSOC)['total_revenue'] ?? 0;
?>

<!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>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.rtl.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Vazirmatn:wght@400;600;700&display=swap" rel="stylesheet">
    <link href="assets/css/admin.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body class="admin-app">
    <?php include 'includes/menu.php'; ?>
    <?php include 'includes/header_bar.php'; ?>

    <main class="main">
        <div class="main-content">
                <?php
                $admin_page_title = 'گزارش‌های پیشرفته';
                $admin_page_icon = 'fas fa-chart-bar';
                include 'includes/topbar.php';
                ?>

                    <div class="p-0">
                        <!-- Date Filter -->
                        <div class="card fade-in-up mb-4">
                            <div class="card-header">
                                <h6><i class="fas fa-filter me-2"></i>فیلتر تاریخ</h6>
                            </div>
                            <div class="card-body">
                                <form method="GET" class="row g-3">
                                    <div class="col-md-4">
                                        <label for="start_date" class="form-label">از تاریخ</label>
                                        <input type="date" class="form-control" id="start_date" name="start_date" 
                                               value="<?= $startDate ?>">
                                    </div>
                                    <div class="col-md-4">
                                        <label for="end_date" class="form-label">تا تاریخ</label>
                                        <input type="date" class="form-control" id="end_date" name="end_date" 
                                               value="<?= $endDate ?>">
                                    </div>
                                    <div class="col-md-4 d-flex align-items-end">
                                        <button type="submit" class="btn btn-primary me-2">
                                            <i class="fas fa-search me-2"></i>اعمال فیلتر
                                        </button>
                                        <a href="reports.php" class="btn btn-secondary">
                                            <i class="fas fa-times me-2"></i>پاک کردن
                                        </a>
                                    </div>
                                </form>
                            </div>
                        </div>

                        <!-- Overall Statistics -->
                        <div class="row mb-4">
                            <div class="col-md-3">
                                <div class="card stat-card info">
                                    <div class="card-body text-center">
                                        <i class="fas fa-users fa-2x mb-2"></i>
                                        <h4><?= number_format($totalUsers) ?></h4>
                                        <p class="mb-0">کل کاربران</p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="card stat-card success">
                                    <div class="card-body text-center">
                                        <i class="fas fa-shopping-cart fa-2x mb-2"></i>
                                        <h4><?= number_format($totalOrders) ?></h4>
                                        <p class="mb-0">کل سفارشات</p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="card stat-card warning">
                                    <div class="card-body text-center">
                                        <i class="fas fa-coins fa-2x mb-2"></i>
                                        <h4><?= number_format($totalRevenue) ?></h4>
                                        <p class="mb-0">کل درآمد (سکه)</p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="card stat-card">
                                    <div class="card-body text-center">
                                        <i class="fas fa-video fa-2x mb-2"></i>
                                        <h4><?= number_format($totalAdmobCoins) ?></h4>
                                        <p class="mb-0">سکه‌های AdMob</p>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Charts Row -->
                        <div class="row mb-4">
                            <!-- User Growth Chart -->
                            <div class="col-lg-6 mb-4">
                                <div class="card fade-in-up">
                                    <div class="card-header">
                                        <h6><i class="fas fa-chart-line me-2"></i>نمودار رشد کاربران</h6>
                                    </div>
                                    <div class="card-body">
                                        <canvas id="userGrowthChart" height="300"></canvas>
                                    </div>
                                </div>
                            </div>

                            <!-- AdMob Statistics Chart -->
                            <div class="col-lg-6 mb-4">
                                <div class="card fade-in-up">
                                    <div class="card-header">
                                        <h6><i class="fas fa-chart-bar me-2"></i>آمار AdMob</h6>
                                    </div>
                                    <div class="card-body">
                                        <canvas id="admobChart" height="300"></canvas>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Product Sales Table -->
                        <div class="card fade-in-up mb-4">
                            <div class="card-header">
                                <h6><i class="fas fa-box me-2"></i>آمار فروش محصولات</h6>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-hover">
                                        <thead>
                                            <tr>
                                                <th>نام محصول</th>
                                                <th>تعداد فروش</th>
                                                <th>درآمد کل (سکه)</th>
                                                <th>درصد از کل فروش</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($productSales as $product): ?>
                                            <tr>
                                                <td><?= htmlspecialchars($product['name']) ?></td>
                                                <td><?= number_format($product['sales_count']) ?></td>
                                                <td><?= number_format($product['total_revenue']) ?></td>
                                                <td>
                                                    <?php 
                                                    $percentage = $totalRevenue > 0 ? ($product['total_revenue'] / $totalRevenue) * 100 : 0;
                                                    echo number_format($percentage, 1) . '%';
                                                    ?>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                            <?php if (empty($productSales)): ?>
                                            <tr>
                                                <td colspan="4" class="text-center text-muted">هیچ فروشی در این بازه زمانی ثبت نشده است</td>
                                            </tr>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>

                        <!-- User Activity Statistics -->
                        <div class="card fade-in-up">
                            <div class="card-header">
                                <h6><i class="fas fa-user-chart me-2"></i>آمار فعالیت کاربران</h6>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-3 text-center">
                                        <div class="border rounded p-3">
                                            <h4 class="text-primary"><?= number_format($userActivity['total_users']) ?></h4>
                                            <p class="text-muted mb-0">کل کاربران</p>
                                        </div>
                                    </div>
                                    <div class="col-md-3 text-center">
                                        <div class="border rounded p-3">
                                            <h4 class="text-success"><?= number_format($userActivity['users_with_orders']) ?></h4>
                                            <p class="text-muted mb-0">کاربران با سفارش</p>
                                        </div>
                                    </div>
                                    <div class="col-md-3 text-center">
                                        <div class="border rounded p-3">
                                            <h4 class="text-warning"><?= number_format($userActivity['users_with_videos']) ?></h4>
                                            <p class="text-muted mb-0">کاربران با ویدئو</p>
                                        </div>
                                    </div>
                                    <div class="col-md-3 text-center">
                                        <div class="border rounded p-3">
                                            <h4 class="text-info"><?= number_format($userActivity['users_with_transactions']) ?></h4>
                                            <p class="text-muted mb-0">کاربران با تراکنش</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
        </div>
    </main>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <?php include 'includes/admin_shell_scripts.php'; ?>
    <script>
        // User Growth Chart
        const userGrowthCtx = document.getElementById('userGrowthChart').getContext('2d');
        new Chart(userGrowthCtx, {
            type: 'line',
            data: {
                labels: <?= json_encode(array_column($userGrowth, 'date')) ?>,
                datasets: [{
                    label: 'کاربران جدید',
                    data: <?= json_encode(array_column($userGrowth, 'new_users')) ?>,
                    borderColor: '#667eea',
                    backgroundColor: 'rgba(102, 126, 234, 0.1)',
                    tension: 0.4,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'top',
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });

        // AdMob Statistics Chart
        const admobCtx = document.getElementById('admobChart').getContext('2d');
        new Chart(admobCtx, {
            type: 'bar',
            data: {
                labels: <?= json_encode(array_column($admobStats, 'date')) ?>,
                datasets: [{
                    label: 'تعداد بازدید',
                    data: <?= json_encode(array_column($admobStats, 'views')) ?>,
                    backgroundColor: 'rgba(102, 126, 234, 0.8)',
                    borderColor: '#667eea',
                    borderWidth: 1
                }, {
                    label: 'سکه‌های کسب شده',
                    data: <?= json_encode(array_column($admobStats, 'total_coins')) ?>,
                    backgroundColor: 'rgba(118, 75, 162, 0.8)',
                    borderColor: '#764ba2',
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'top',
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });

        // Add fade-in animation to cards
        document.addEventListener('DOMContentLoaded', function() {
            const cards = document.querySelectorAll('.fade-in-up');
            cards.forEach((card, index) => {
                card.style.animationDelay = (index * 0.1) + 's';
            });
        });
    </script>
</body>
</html>
