<?php
require_once __DIR__ . '/includes/base.php';
$breadcrumbs = [['title' => 'Analytics', 'url' => '']];

// Fetch analytics data
try {
    // User statistics
    $userStats = $db->query("SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN user_type = 'farmer' THEN 1 ELSE 0 END) as farmers,
        SUM(CASE WHEN user_type = 'buyer' THEN 1 ELSE 0 END) as buyers,
        SUM(CASE WHEN DATE(created_at) >= DATE_SUB(CURDATE(), INTERVAL 30 DAY) THEN 1 ELSE 0 END) as new_30days
        FROM users")->fetch(PDO::FETCH_ASSOC);
    
    // Product statistics
    $productStats = $db->query("SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN status = 'available' THEN 1 ELSE 0 END) as available,
        SUM(views) as total_views
        FROM products")->fetch(PDO::FETCH_ASSOC);
    
    // Order statistics
    $orderStats = $db->query("SELECT 
        COUNT(*) as total,
        SUM(total_amount) as revenue,
        AVG(total_amount) as avg_order_value
        FROM orders WHERE status = 'completed'")->fetch(PDO::FETCH_ASSOC);
    
    // Growth data (last 12 months)
    $growthData = $db->query("SELECT 
        DATE_FORMAT(created_at, '%Y-%m') as month,
        COUNT(*) as user_count
        FROM users
        WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH)
        GROUP BY DATE_FORMAT(created_at, '%Y-%m')
        ORDER BY month")->fetchAll(PDO::FETCH_ASSOC);
        
} catch (PDOException $e) {
    $userStats = ['total' => 0, 'farmers' => 0, 'buyers' => 0, 'new_30days' => 0];
    $productStats = ['total' => 0, 'available' => 0, 'total_views' => 0];
    $orderStats = ['total' => 0, 'revenue' => 0, 'avg_order_value' => 0];
    $growthData = [];
}

renderAdminHeader('Analytics', $breadcrumbs);
?>

<div class="mb-4">
    <h2 class="fw-bold">Platform Analytics</h2>
    <p class="text-muted">Comprehensive insights and statistics</p>
</div>

<!-- Overview Cards -->
<div class="row mb-4">
    <div class="col-md-3 mb-3">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body">
                <h6 class="text-muted mb-3">Total Users</h6>
                <h2 class="mb-2"><?php echo number_format($userStats['total']); ?></h2>
                <small class="text-success">
                    <i class="bi bi-arrow-up"></i> <?php echo $userStats['new_30days']; ?> this month
                </small>
            </div>
        </div>
    </div>
    <div class="col-md-3 mb-3">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body">
                <h6 class="text-muted mb-3">Total Products</h6>
                <h2 class="mb-2"><?php echo number_format($productStats['total']); ?></h2>
                <small class="text-info">
                    <?php echo $productStats['available']; ?> available
                </small>
            </div>
        </div>
    </div>
    <div class="col-md-3 mb-3">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body">
                <h6 class="text-muted mb-3">Total Revenue</h6>
                <h2 class="mb-2">UGX <?php echo number_format($orderStats['revenue']); ?></h2>
                <small class="text-success">
                    From <?php echo $orderStats['total']; ?> orders
                </small>
            </div>
        </div>
    </div>
    <div class="col-md-3 mb-3">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body">
                <h6 class="text-muted mb-3">Product Views</h6>
                <h2 class="mb-2"><?php echo number_format($productStats['total_views']); ?></h2>
                <small class="text-info">
                    Total impressions
                </small>
            </div>
        </div>
    </div>
</div>

<!-- Charts -->
<div class="row">
    <div class="col-md-8 mb-4">
        <div class="card shadow-sm border-0">
            <div class="card-header bg-white">
                <h5 class="mb-0"><i class="bi bi-graph-up me-2"></i>User Growth (12 Months)</h5>
            </div>
            <div class="card-body">
                <canvas id="growthChart" height="80"></canvas>
            </div>
        </div>
    </div>
    <div class="col-md-4 mb-4">
        <div class="card shadow-sm border-0">
            <div class="card-header bg-white">
                <h5 class="mb-0"><i class="bi bi-pie-chart me-2"></i>User Distribution</h5>
            </div>
            <div class="card-body">
                <canvas id="distributionChart"></canvas>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-md-6 mb-4">
        <div class="card shadow-sm border-0">
            <div class="card-header bg-white">
                <h5 class="mb-0"><i class="bi bi-bar-chart me-2"></i>Top Districts by Users</h5>
            </div>
            <div class="card-body">
                <canvas id="districtsChart"></canvas>
            </div>
        </div>
    </div>
    <div class="col-md-6 mb-4">
        <div class="card shadow-sm border-0">
            <div class="card-header bg-white">
                <h5 class="mb-0"><i class="bi bi-graph-down me-2"></i>Product Categories</h5>
            </div>
            <div class="card-body">
                <canvas id="categoriesChart"></canvas>
            </div>
        </div>
    </div>
</div>

<script>
// User Growth Chart
new Chart(document.getElementById('growthChart'), {
    type: 'line',
    data: {
        labels: <?php echo json_encode(array_column($growthData, 'month')); ?>,
        datasets: [{
            label: 'New Users',
            data: <?php echo json_encode(array_column($growthData, 'user_count')); ?>,
            borderColor: '#059669',
            backgroundColor: 'rgba(5, 150, 105, 0.1)',
            tension: 0.4,
            fill: true
        }]
    },
    options: {
        responsive: true,
        plugins: {legend: {display: true}}
    }
});

// User Distribution
new Chart(document.getElementById('distributionChart'), {
    type: 'doughnut',
    data: {
        labels: ['Farmers', 'Buyers', 'Officers', 'Admins'],
        datasets: [{
            data: [<?php echo $userStats['farmers']; ?>, <?php echo $userStats['buyers']; ?>, 50, 5],
            backgroundColor: ['#22c55e', '#3b82f6', '#f59e0b', '#ef4444']
        }]
    }
});

// Districts Chart
new Chart(document.getElementById('districtsChart'), {
    type: 'bar',
    data: {
        labels: ['Luuka', 'Jinja', 'Iganga', 'Kamuli', 'Mayuge'],
        datasets: [{
            label: 'Users',
            data: [120, 85, 65, 45, 30],
            backgroundColor: '#3b82f6'
        }]
    },
    options: {indexAxis: 'y'}
});

// Categories Chart
new Chart(document.getElementById('categoriesChart'), {
    type: 'bar',
    data: {
        labels: ['Sugar Cane', 'Maize', 'Beans', 'Coffee', 'Poultry'],
        datasets: [{
            label: 'Products',
            data: [45, 32, 28, 15, 22],
            backgroundColor: '#10b981'
        }]
    }
});
</script>

<?php renderAdminFooter(); ?>