<?php

namespace App\Filament\Widgets\Ruko;

use App\Models\Invoice;
use App\Models\Payment;
use App\Models\Tenant;
use App\Models\Unit;
use App\Models\Lease; // sesuaikan jika beda
use Filament\Widgets\StatsOverviewWidget as BaseWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;

class RukoStatsOverview extends BaseWidget
{
    protected function getStats(): array
    {
        $startMonth = now()->startOfMonth();
        $endMonth   = now()->endOfMonth();

        // =========================
        // 1) Pendapatan (Cash In) bulan ini: dari payments
        // =========================
        $revenueThisMonth = (float) Payment::query()
            ->whereBetween('paid_at', [$startMonth, $endMonth])
            ->sum('total_amount');

        // =========================
        // 2) Tagihan jatuh tempo bulan ini (BRUTO): semua invoice due bulan ini (kecuali void)
        // =========================
        $dueGrossThisMonth = (float) Invoice::query()
            ->notVoid()
            ->dueBetween($startMonth, $endMonth)
            ->totalSum()
            ->value('agg');

        // =========================
        // 3) Sudah dibayar untuk invoice due bulan ini: sum(paid_amount) invoice yang due bulan ini
        // (ini bukan cash-in bulan ini, tapi berapa yang sudah lunas/cicil pada invoice2 due tsb)
        // =========================
        $duePaidThisMonth = (float) Invoice::query()
            ->notVoid()
            ->dueBetween($startMonth, $endMonth)
            ->paidSum()
            ->value('agg');

        // =========================
        // 4) Sisa tagihan jatuh tempo bulan ini (yang paling penting untuk ditagih)
        // hanya unpaid/partial + (total - paid)
        // =========================
        $dueOutstandingThisMonth = (float) Invoice::query()
            ->notVoid()
            ->dueBetween($startMonth, $endMonth)
            ->unpaidOrPartial()
            ->outstandingSum()
            ->value('agg');

        // =========================
        // 5) Total tunggakan aktif (overdue outstanding)
        // =========================
        $overdueOutstanding = (float) Invoice::query()
            ->notVoid()
            ->overdue()
            ->outstandingSum()
            ->value('agg');

        // =========================
        // 6) Invoice baru dibuat bulan ini (opsional)
        // =========================
        $invoicesIssuedThisMonth = (int) Invoice::query()
            ->notVoid()
            ->whereBetween('issued_at', [$startMonth, $endMonth])
            ->count();

        // =========================
        // 7) KPI okupansi
        // =========================
        $totalUnits = (int) Unit::query()
            ->where('is_active', true)
            ->count();

        $occupiedUnits = (int) Lease::query()
            ->whereDate('start_date', '<=', now()->toDateString())
            ->where(function ($q) {
                $q->whereNull('end_date')
                  ->orWhereDate('end_date', '>=', now()->toDateString());
            })
            ->whereIn('status', ['active'])
            ->distinct('unit_id')
            ->count('unit_id');

        $occupancyPct = $totalUnits > 0 ? round(($occupiedUnits / $totalUnits) * 100, 1) : 0;

        // =========================
        // 8) Tenant aktif
        // =========================
        $activeTenants = (int) Tenant::query()
            ->whereHas('leases', function ($q) {
                $q->whereDate('start_date', '<=', now()->toDateString())
                  ->where(function ($qq) {
                      $qq->whereNull('end_date')
                         ->orWhereDate('end_date', '>=', now()->toDateString());
                  })
                  ->whereIn('status', ['active']);
            })
            ->count();

        // =========================
        // Format angka rupiah
        // =========================
        $idr = fn ($n) => 'Rp ' . number_format((float) $n, 0, ',', '.');

        return [
            // CASH IN
            Stat::make('Pendapatan (Cash In) Bulan Ini', $idr($revenueThisMonth))
                ->description('Total pembayaran masuk bulan ini (dari Payments)')
                ->icon('heroicon-o-banknotes'),

            // DUE - GROSS
            Stat::make('Tagihan Jatuh Tempo Bulan Ini', $idr($dueGrossThisMonth))
                ->description('Total nilai invoice yang due bulan ini (exclude void)')
                ->icon('heroicon-o-calendar-days'),

            // DUE - OUTSTANDING (yang harus ditagih)
            Stat::make('Sisa Tagihan Due Bulan Ini', $idr($dueOutstandingThisMonth))
                ->description('Outstanding invoice due bulan ini (unpaid/partial)')
                ->icon('heroicon-o-exclamation-triangle'),

            // OVERDUE
            Stat::make('Tunggakan Aktif (Overdue)', $idr($overdueOutstanding))
                ->description('Outstanding invoice lewat jatuh tempo')
                ->icon('heroicon-o-shield-exclamation'),

            // OKUPANSI
            Stat::make('Okupansi', "{$occupiedUnits}/{$totalUnits} ({$occupancyPct}%)")
                ->description('Unit aktif terisi vs total unit aktif')
                ->icon('heroicon-o-building-storefront'),

            // Tenant aktif / invoice issued
            Stat::make('Tenant Aktif', (string) $activeTenants)
                ->description('Tenant yang punya lease aktif')
                ->icon('heroicon-o-user-group'),

            Stat::make('Invoice Terbit Bulan Ini', (string) $invoicesIssuedThisMonth)
                ->description('Jumlah invoice issued pada bulan ini')
                ->icon('heroicon-o-document-text'),
        ];
    }
}
