<?php

namespace App\Filament\Tenant\Widgets;

use App\Models\Tenant\Expense;
use App\Models\Tenant\Payment;
use App\Models\Tenant\WorkOrder;
use Filament\Widgets\StatsOverviewWidget as BaseWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;

class FinanceOverview extends BaseWidget
{
    protected static ?int $sort = 2;

    protected function getStats(): array
    {
        $start = now()->startOfMonth();
        $end = now()->endOfMonth();

        $income = (float) Payment::whereBetween('paid_at', [$start, $end])->sum('amount');
        $expenses = (float) Expense::whereBetween('paid_at', [$start, $end])->sum('amount');
        $profit = $income - $expenses;

        $debtTotal = (float) WorkOrder::where('pay_status', '!=', 'paid')
            ->whereNotIn('status', ['cancelled'])
            ->sum('total');
        $paidOnDebt = (float) Payment::whereIn('work_order_id',
                WorkOrder::where('pay_status', '!=', 'paid')->pluck('id')
            )->sum('amount');
        $debt = max(0, $debtTotal - $paidOnDebt);

        return [
            Stat::make('Încasări (luna)', number_format($income, 2, '.', ' ') . ' MDL')
                ->icon('heroicon-o-arrow-trending-up')
                ->color('success')
                ->description(now()->translatedFormat('F Y')),

            Stat::make('Cheltuieli (luna)', number_format($expenses, 2, '.', ' ') . ' MDL')
                ->icon('heroicon-o-arrow-trending-down')
                ->color('danger'),

            Stat::make('Profit (luna)', number_format($profit, 2, '.', ' ') . ' MDL')
                ->icon('heroicon-o-banknotes')
                ->color($profit >= 0 ? 'success' : 'danger'),

            Stat::make('Datorii clienți', number_format($debt, 2, '.', ' ') . ' MDL')
                ->icon('heroicon-o-exclamation-circle')
                ->color($debt > 0 ? 'warning' : 'success'),
        ];
    }
}
