<?php

namespace App\Filament\Widgets\Ruko;

use App\Models\Location;
use Filament\Widgets\ChartWidget;

class OccupancyByLocationChart extends ChartWidget
{
    protected static ?string $heading = 'Okupansi per Lokasi';

    protected function getData(): array
    {
        $labels = [];
        $data = [];

        $locations = Location::query()->withCount([
            'units as total_units' => fn ($q) => $q->where('is_active', true),
            // asumsi relasi: Location->leases lewat units atau ada relasi khusus
        ])->get();

        foreach ($locations as $loc) {
            $labels[] = $loc->name;

            // Sesuaikan cara hitung occupied di lokasimu:
            $occupied = $loc->units()
                ->where('is_active', true)
                ->whereHas('leases', function ($q) {
                    $q->whereIn('status', ['active'])
                      ->whereDate('start_date', '<=', now()->toDateString())
                      ->where(function ($qq) {
                          $qq->whereNull('end_date')->orWhereDate('end_date', '>=', now()->toDateString());
                      });
                })
                ->count();

            $total = $loc->units()->where('is_active', true)->count();
            $pct = $total > 0 ? round(($occupied / $total) * 100, 1) : 0;

            $data[] = $pct;
        }

        return [
            'datasets' => [
                [
                    'label' => '% Okupansi',
                    'data' => $data,
                ],
            ],
            'labels' => $labels,
        ];
    }

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