<?php

namespace App\Filament\AssociationAdmin\Widgets;

use App\Models\WellLicense;
use BezhanSalleh\FilamentShield\Traits\HasWidgetShield;
use Cheesegrits\FilamentGoogleMaps\Widgets\MapWidget;
use Illuminate\Support\Facades\Auth;

class AssociationWellLicensesMap extends MapWidget
{
    use HasWidgetShield;

    protected static ?string $heading = 'خريطة تراخيص الآبار';

    protected static ?int $sort = 1;

    protected static ?string $pollingInterval = null;

    protected static ?bool $clustering = true;

    protected static ?bool $fitToBounds = true;

    protected static ?int $zoom = 8;

    protected array $mapConfig = [
        'draggable' => false,
        'center' => [
            'lat' => 24.7136, // Default latitude (Riyadh)
            'lng' => 46.6753, // Default longitude (Riyadh)
        ],
        'zoom' => 8,
        'fit' => true,
        'gmaps' => '',
        'clustering' => true,
        'mapConfig' => [],
    ];

    protected int|string|array $columnSpan = 'full';

    protected function getData(): array
    {
        $user = Auth::user();
        
        $query = WellLicense::whereNotNull('lat')
            ->whereNotNull('lng');
            
        if ($user && $user->association_id) {
            $query->where('association_id', $user->association_id);
        } else {
            // If user has no association, show no licenses for security
            $query->whereRaw('1 = 0');
        }

        $locations = $query->get();

        $data = [];

        foreach ($locations as $location) {
            $data[] = [
                'location' => [
                    'lat' => $location->lat ? round(floatval($location->lat), static::$precision) : 0,
                    'lng' => $location->lng ? round(floatval($location->lng), static::$precision) : 0,
                ],

                'label' => '#'.$location->id.': '.$location->well_name,

                'id' => $location->getKey(),
            ];
        }

        return $data;
    }
}
