<?php

namespace App\Filament\Widgets;

use App\Models\Expense;
use App\Models\FeedPurchase;
use App\Models\Order;
use BezhanSalleh\FilamentShield\Traits\HasWidgetShield;
use Filament\Widgets\ChartWidget;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

class RevenueExpenseChart extends ChartWidget
{
    use HasWidgetShield;

    protected ?string $heading = 'Pendapatan vs Pengeluaran (6 Bulan Terakhir)';

    protected static ?int $sort = 3;

    protected function getData(): array
    {
        $months = collect(range(5, 0))->reverse()->map(function ($i) {
            return now()->subMonths($i)->format('Y-m');
        });

        $revenues = Order::select(
            DB::raw("DATE_FORMAT(order_date, '%Y-%m') as month"),
            DB::raw('SUM(total_amount) as total')
        )
            ->where('order_date', '>=', now()->subMonths(5)->startOfMonth())
            ->groupBy('month')
            ->get()
            ->pluck('total', 'month');

        $expenses = Expense::select(
            DB::raw("DATE_FORMAT(expense_date, '%Y-%m') as month"),
            DB::raw('SUM(amount) as total')
        )
            ->where('expense_date', '>=', now()->subMonths(5)->startOfMonth())
            ->groupBy('month')
            ->get()
            ->pluck('total', 'month');

        $feedPurchases = FeedPurchase::select(
            DB::raw("DATE_FORMAT(purchase_date, '%Y-%m') as month"),
            DB::raw('SUM(total_price) as total')
        )
            ->where('purchase_date', '>=', now()->subMonths(5)->startOfMonth())
            ->groupBy('month')
            ->get()
            ->pluck('total', 'month');

        $revenueData = $months->map(fn ($month) => (int) $revenues->get($month, 0));
        $expenseData = $months->map(fn ($month) => (int) ($expenses->get($month, 0) + $feedPurchases->get($month, 0)));

        return [
            'datasets' => [
                [
                    'label' => 'Pendapatan (Order)',
                    'data' => $revenueData->values()->toArray(),
                    'backgroundColor' => '#10b981',
                    'borderColor' => '#10b981',
                ],
                [
                    'label' => 'Pengeluaran (Operasional + Pakan)',
                    'data' => $expenseData->values()->toArray(),
                    'backgroundColor' => '#ef4444',
                    'borderColor' => '#ef4444',
                ],
            ],
            'labels' => $months->values()->map(fn ($month) => Carbon::parse($month)->translatedFormat('M Y'))->toArray(),
        ];
    }

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