<?php
/**
 * ============================================================================
 * dashboard/widgets/sales-chart.php
 * Sales Chart Widget - Shows monthly sales data
 * ============================================================================
 */
?>
<?php
$userId = getUserId();
$database = new Database();
$db = $database->getConnection();

// Fetch monthly sales data for the last 6 months
$sql = "SELECT 
            DATE_FORMAT(updated_at, '%b') as month,
            COUNT(*) as sales_count,
            COALESCE(SUM(price_per_unit * quantity), 0) as revenue
        FROM products
        WHERE seller_id = ? AND status = 'sold'
        AND updated_at >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH)
        GROUP BY MONTH(updated_at), YEAR(updated_at)
        ORDER BY updated_at ASC";
$stmt = $db->prepare($sql);
$stmt->execute([$userId]);
$salesData = $stmt->fetchAll();

// Prepare data for Chart.js
$months = [];
$revenues = [];
$counts = [];

foreach ($salesData as $data) {
    $months[] = $data['month'];
    $revenues[] = $data['revenue'];
    $counts[] = $data['sales_count'];
}
?>

<div class="card border-0 shadow-sm">
    <div class="card-header bg-white border-0 py-3">
        <h5 class="mb-0 fw-bold">
            <i class="bi bi-graph-up text-success me-2"></i>Sales Overview
        </h5>
    </div>
    <div class="card-body">
        <canvas id="salesChart" height="80"></canvas>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const ctx = document.getElementById('salesChart');
    if (ctx) {
        new Chart(ctx, {
            type: 'line',
            data: {
                labels: <?php echo json_encode($months); ?>,
                datasets: [{
                    label: 'Revenue (UGX)',
                    data: <?php echo json_encode($revenues); ?>,
                    borderColor: '#059669',
                    backgroundColor: 'rgba(5, 150, 105, 0.1)',
                    tension: 0.4,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return 'UGX ' + context.parsed.y.toLocaleString();
                            }
                        }
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: function(value) {
                                return 'UGX ' + value.toLocaleString();
                            }
                        }
                    }
                }
            }
        });
    }
});
</script>