<?php

namespace App\Filament\Widgets;

use Filament\Widgets\ChartWidget;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Carbon;

class UploadsPerDayChart extends ChartWidget
{
    protected ?string $heading = 'Uploads (14 days)';
    protected ?string $maxHeight = '220px';
    protected ?string $pollingInterval = '60s';

    protected function getData(): array
    {
        // Build last 14 days labels
        $labels = [];
        $start = Carbon::now()->startOfDay()->subDays(13);
        for ($i = 0; $i < 14; $i++) {
            $labels[] = $start->copy()->addDays($i)->format('Y-m-d');
        }

        // SQLite-friendly group by date
        $rows = DB::table('photos')
            ->selectRaw("strftime('%Y-%m-%d', created_at) as d, count(*) as c")
            ->where('created_at', '>=', $start)
            ->groupBy('d')
            ->orderBy('d')
            ->get();
        $map = collect($rows)->keyBy('d');
        $data = array_map(fn ($d) => (int) ($map[$d]->c ?? 0), $labels);

        return [
            'labels' => $labels,
            'datasets' => [
                [
                    'label' => 'Uploads',
                    'data' => $data,
                    'borderColor' => '#f59e0b',
                    'backgroundColor' => 'rgba(245, 158, 11, 0.2)',
                    'tension' => 0.3,
                ],
            ],
        ];
    }

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