<?php

namespace App\Filament\Pages;

use App\Models\Customer;
use App\Models\DelayedGood;
use App\Models\EggCollectionItem;
use App\Models\Expense;
use App\Models\FeedPurchase;
use App\Models\Order;
use App\Models\Payroll;
use BackedEnum;
use Filament\Pages\Page;
use Filament\Support\Icons\Heroicon;

class Analisys extends Page
{
    protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedChartPie;

    protected static ?string $navigationLabel = 'Analisis';

    protected static ?string $slug = 'analisys';

    protected static ?string $title = 'Analisis';

    protected string $view = 'filament.pages.analisys';

    public function getViewData(): array
    {
        $formatNumber = fn ($val) => number_format((float) $val, $val == floor($val) ? 0 : 2, ',', '.');

        // 1. Count customers
        $countPelanggan = Customer::count();

        // 2. Count total eggs (by unit)
        $totalEggsByUnit = EggCollectionItem::query()
            ->join('egg_collections', 'egg_collection_items.egg_collection_id', '=', 'egg_collections.id')
            ->join('units', 'egg_collection_items.unit_id', '=', 'units.id')
            ->whereNull('egg_collections.deleted_at')
            ->selectRaw('units.name as unit_name, 
                        sum(case when is_broken = 0 then quantity else 0 end) as total_good,
                        sum(case when is_broken = 1 then quantity else 0 end) as total_broken')
            ->groupBy('units.name')
            ->get()
            ->map(fn ($item) => [
                'unit_name' => $item->unit_name,
                'total_good' => $formatNumber($item->total_good),
                'total_broken' => $formatNumber($item->total_broken),
            ]);

        // 3. Count total orders
        $countPesanan = Order::count();

        // 4. Count total delayed goods (by unit)
        $totalDelayedByUnit = DelayedGood::query()
            ->join('units', 'delayed_goods.unit_id', '=', 'units.id')
            ->selectRaw('units.name as unit_name, sum(quantity) as total')
            ->groupBy('units.name')
            ->get()
            ->map(fn ($item) => [
                'unit_name' => $item->unit_name,
                'total' => $formatNumber($item->total),
            ]);

        // 5. Revenue (from orders and delayed goods)
        $pendapatanPesanan = Order::sum('total_amount');
        $pendapatanTertunda = DelayedGood::sum('total_amount');
        $totalPendapatan = $pendapatanPesanan + $pendapatanTertunda;

        // 6. Expenses
        $totalPengeluaran = Expense::sum('amount');

        // 7. Payroll
        $totalPenggajian = Payroll::sum('total_salary');

        // 8. Feed purchases
        $totalBelanjaPakan = FeedPurchase::sum('total_price');

        // 9. Gross profit (Revenue - COGS/Feed)
        $labaKotor = $totalPendapatan - $totalBelanjaPakan;

        // 10. Net profit (Gross Profit - Expenses - Payroll)
        $labaBersih = $labaKotor - $totalPengeluaran - $totalPenggajian;

        // 11. Unpaid accounts receivable (delayed goods)
        $totalPiutang = DelayedGood::sum('total_amount') - DelayedGood::sum('paid_amount');

        $mainStats = [
            ['label' => 'Total Pelanggan', 'desc' => 'Jumlah pelanggan terdaftar', 'value' => $countPelanggan, 'prefix' => ''],
            ['label' => 'Total Pesanan', 'desc' => 'Jumlah transaksi pesanan', 'value' => $countPesanan, 'prefix' => ''],
            ['label' => 'Laba Bersih', 'desc' => 'Setelah dikurangi beban operasional', 'value' => $formatNumber($labaBersih), 'prefix' => 'Rp'],
            ['label' => 'Total Piutang', 'desc' => 'Piutang barang tertunda', 'value' => $formatNumber($totalPiutang), 'prefix' => 'Rp'],
            ['label' => 'Total Pendapatan', 'desc' => 'Akumulasi semua pemasukan', 'value' => $formatNumber($totalPendapatan), 'prefix' => 'Rp'],
            ['label' => 'Laba Kotor', 'desc' => 'Pendapatan dikurangi biaya pakan', 'value' => $formatNumber($labaKotor), 'prefix' => 'Rp'],
            ['label' => 'Total Pengeluaran', 'desc' => 'Biaya operasional & umum', 'value' => $formatNumber($totalPengeluaran), 'prefix' => 'Rp'],
            ['label' => 'Total Penggajian', 'desc' => 'Total gaji karyawan', 'value' => $formatNumber($totalPenggajian), 'prefix' => 'Rp'],
            ['label' => 'Belanja Pakan', 'desc' => 'Total pembelian pakan ayam', 'value' => $formatNumber($totalBelanjaPakan), 'prefix' => 'Rp'],
        ];

        return [
            'mainStats' => $mainStats,
            'totalEggsByUnit' => $totalEggsByUnit,
            'totalDelayedByUnit' => $totalDelayedByUnit,
        ];
    }
}
