<?php

namespace App\Filament\Widgets;

use App\Models\Client;
use Leandrocfe\FilamentApexCharts\Widgets\ApexChartWidget;

class ClientsByCityChart extends ApexChartWidget
{
    protected static ?string $chartId = 'clientsByCityChart';

    protected static ?string $heading = 'العملاء حسب المدينة';

    protected static ?string $subheading = 'توزيع العملاء الجغرافي';

    protected static ?int $sort = 6;

    protected ?string $pollingInterval = '60s';
    
    // إخفاء الـ widget من Dashboard
    protected static bool $isDiscovered = false;

    protected function getOptions(): array
    {
        $clientsByCity = Client::where('is_active', true)
            ->whereNotNull('city')
            ->selectRaw('city, count(*) as count')
            ->groupBy('city')
            ->orderByDesc('count')
            ->get();

        $labels = $clientsByCity->pluck('city')->toArray();
        $counts = $clientsByCity->pluck('count')->toArray();

        $colors = ['#f59e0b', '#3b82f6', '#10b981', '#8b5cf6', '#ef4444', '#ec4899', '#14b8a6', '#f97316'];

        return [
            'chart' => [
                'type' => 'pie',
                'height' => 320,
            ],
            'series' => $counts,
            'labels' => $labels,
            'colors' => array_slice($colors, 0, count($labels)),
            'legend' => [
                'position' => 'bottom',
                'fontFamily' => 'inherit',
                'fontSize' => '14px',
            ],
            'dataLabels' => [
                'enabled' => true,
                'style' => [
                    'fontFamily' => 'inherit',
                    'fontWeight' => 600,
                    'fontSize' => '14px',
                ],
            ],
            'plotOptions' => [
                'pie' => [
                    'expandOnClick' => true,
                    'dataLabels' => [
                        'offset' => -5,
                    ],
                ],
            ],
            'responsive' => [
                [
                    'breakpoint' => 480,
                    'options' => [
                        'chart' => [
                            'width' => 300,
                        ],
                        'legend' => [
                            'position' => 'bottom',
                        ],
                    ],
                ],
            ],
        ];
    }
}

