<?php

namespace App\Filament\Widgets;

use App\Models\CashRecord;
use Filament\Widgets\StatsOverviewWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;
use Illuminate\Support\Carbon;

class CashStatsWidget extends StatsOverviewWidget
{
    protected int | string | array $columnSpan = 'full';

    public static function canView(): bool
    {
        return request()->routeIs('filament.admin.resources.cash-records.index');
    }

    protected function getStats(): array
    {
        $saldo = fn ($query) => $query
            ->whereNotNull('verified_at')
            ->join('cash_categories', 'cash_records.category_id', '=', 'cash_categories.id')
            ->selectRaw("SUM(CASE WHEN cash_categories.type = 'pemasukan' THEN amount ELSE -amount END) as saldo")
            ->value('saldo') ?? 0;

        $bulanIni   = now()->startOfMonth();
        $bulanLalu  = now()->subMonth()->startOfMonth();

        $totalSaldo      = $saldo(CashRecord::query());
        $pemasukanBulanIni  = CashRecord::whereNotNull('verified_at')
            ->join('cash_categories', 'cash_records.category_id', '=', 'cash_categories.id')
            ->where('cash_categories.type', 'pemasukan')
            ->whereMonth('date', $bulanIni->month)->whereYear('date', $bulanIni->year)
            ->sum('amount');
        $pengeluaranBulanIni = CashRecord::whereNotNull('verified_at')
            ->join('cash_categories', 'cash_records.category_id', '=', 'cash_categories.id')
            ->where('cash_categories.type', 'pengeluaran')
            ->whereMonth('date', $bulanIni->month)->whereYear('date', $bulanIni->year)
            ->sum('amount');
        $saldoBulanLalu  = $saldo(CashRecord::query()->where('date', '<', $bulanIni));

        return [
            Stat::make('Total Saldo', 'Rp ' . number_format($totalSaldo, 0, ',', '.'))
                ->description('Akumulasi semua transaksi')
                ->color($totalSaldo >= 0 ? 'success' : 'danger')
                ->icon('heroicon-o-banknotes'),

            Stat::make('Pemasukan ' . $bulanIni->translatedFormat('F Y'), 'Rp ' . number_format($pemasukanBulanIni, 0, ',', '.'))
                ->description('Total pemasukan bulan ini')
                ->color('success')
                ->icon('heroicon-o-arrow-trending-up'),

            Stat::make('Pengeluaran ' . $bulanIni->translatedFormat('F Y'), 'Rp ' . number_format($pengeluaranBulanIni, 0, ',', '.'))
                ->description('Total pengeluaran bulan ini')
                ->color('danger')
                ->icon('heroicon-o-arrow-trending-down'),

            Stat::make('Saldo Bulan Lalu', 'Rp ' . number_format($saldoBulanLalu, 0, ',', '.'))
                ->description($bulanLalu->translatedFormat('F Y'))
                ->color($saldoBulanLalu >= 0 ? 'info' : 'warning')
                ->icon('heroicon-o-clock'),
        ];
    }
}
