<?php

namespace App\Filament\Widgets;

use App\Models\CampaignLog;
use Filament\Widgets\ChartWidget;
use Flowframe\Trend\Trend;
use Flowframe\Trend\TrendValue;
use Illuminate\Support\Facades\Auth;

class CampaignsChart extends ChartWidget
{
    protected static ?string $heading = 'نشاط الإرسال (آخر 7 أيام)';
    
    // يأتي تحت شريط الإحصائيات ويأخذ كامل العرض
    protected static ?int $sort = 2;
    protected int | string | array $columnSpan = 'full';

    protected function getData(): array
    {
        $data = Trend::query(
                CampaignLog::whereHas('campaign', function ($q) {
                    $q->where('user_id', Auth::id());
                })->where('status', 'sent')
            )
            ->between(
                start: now()->subDays(7),
                end: now(),
            )
            ->perDay()
            ->count();

        return [
            'datasets' => [
                [
                    'label' => 'رسائل تم إرسالها',
                    'data' => $data->map(fn (TrendValue $value) => $value->aggregate),
                    'backgroundColor' => '#36A2EB',
                    'borderColor' => '#9BD0F5',
                ],
            ],
            'labels' => $data->map(fn (TrendValue $value) => $value->date),
        ];
    }

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