<?php

namespace App\Filament\Widgets;

use App\Models\Customer;
use Filament\Widgets\ChartWidget;
use Illuminate\Support\Facades\DB;

class CustomerEventsChart extends ChartWidget
{
    protected ?string $heading = 'Monthly Celebrations (Birthdays & Anniversaries)';
    
    protected static ?int $sort = 2;

    protected function getData(): array
    {
        // Initialize arrays for all 12 months with 0
        $birthdays = array_fill(1, 12, 0);
        $anniversaries = array_fill(1, 12, 0);

        // SQLite uses strftime('%m', column)
        $birthdayCounts = Customer::select(DB::raw("strftime('%m', dob) as month"), DB::raw('count(*) as count'))
            ->whereNotNull('dob')
            ->groupBy('month')
            ->pluck('count', 'month')
            ->toArray();

        $anniversaryCounts = Customer::select(DB::raw("strftime('%m', anniversary_date) as month"), DB::raw('count(*) as count'))
            ->whereNotNull('anniversary_date')
            ->groupBy('month')
            ->pluck('count', 'month')
            ->toArray();

        // Fill the data
        foreach ($birthdayCounts as $month => $count) {
            $birthdays[(int)$month] = $count;
        }
        foreach ($anniversaryCounts as $month => $count) {
            $anniversaries[(int)$month] = $count;
        }

        return [
            'datasets' => [
                [
                    'label' => 'Birthdays',
                    'data' => array_values($birthdays),
                    'backgroundColor' => '#3B82F6', // Blue
                    'borderColor' => '#3B82F6',
                ],
                [
                    'label' => 'Anniversaries',
                    'data' => array_values($anniversaries),
                    'backgroundColor' => '#EC4899', // Pink
                    'borderColor' => '#EC4899',
                ],
            ],
            'labels' => ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
        ];
    }

    protected function getType(): string
    {
        return 'bar';
    }
}
