<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Pembelian;
use App\Models\Employee;
use App\Models\History;
use App\Models\Gaji;
use Carbon\Carbon;

class LabarugiController extends Controller
{
    public function index(Request $request)
    {
        $month = $request->input('month', Carbon::now()->month);
        $year = $request->input('year', Carbon::now()->year);

        // Fetch pendapatan for the selected month
        $pendapatan = History::whereYear('created_at', $year)
            ->whereMonth('created_at', $month)
            ->get();

        $totalPendapatan = $pendapatan->sum('harga_total');

        // Fetch pembelian for the selected month
        $pembelians = Pembelian::whereYear('created_at', $year)
            ->whereMonth('created_at', $month)
            ->get();

        // Calculate total beban for pembelians
        $totalBebanPembelian = $pembelians->sum(function ($item) {
            return $item->harga_average * $item->jumlah_barang;
        });

        // Fetch gaji for the selected month
        $gajis = Gaji::whereYear('created_at', $year)
            ->whereMonth('created_at', $month)
            ->get();

        // Calculate total gaji pegawai
        $gajiPegawai = $gajis->sum('gaji');

        // Fetch employees with their latest gaji record
        $employees = Employee::with(['gaji' => function ($query) use ($month, $year) {
            $query->whereYear('created_at', $year)
                ->whereMonth('created_at', $month)
                ->latest('created_at');
        }])->get();

        // Calculate total beban (total expenses)
        $totalBeban = $totalBebanPembelian + $gajiPegawai;

        // Calculate laba bersih (net profit)
        $labaBersih = $totalPendapatan - $totalBeban;

        return view('labarugi', [
            'title' => 'Laba Rugi',
            'active' => 'labarugi',
            'pendapatan' => $pendapatan,
            'pembelians' => $pembelians,
            'employees' => $employees,
            'gajis' => $gajis,
            'totalPendapatan' => $totalPendapatan,
            'totalBeban' => $totalBeban,
            'labaBersih' => $labaBersih,
            'selectedMonth' => $month,
            'selectedYear' => $year,
        ]);
    }
}
