<?php

namespace App\Http\Controllers;

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

class NeracaSaldoController extends Controller
{
    public function index(Request $request)
    {
        // Get the selected month and year from the request, default to the current month and year
        $month = $request->input('month', Carbon::now()->month);
        $year = $request->input('year', Carbon::now()->year);

        // Fetch the data for the selected month and year
        $akuns = NeracaSaldo::whereYear('created_at', $year)
            ->whereMonth('created_at', $month)
            ->get();

        $history = History::with('customer')
            ->whereYear('created_at', $year)
            ->whereMonth('created_at', $month)
            ->get();

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

        $gaji = collect(); // Initialize an empty collection for gaji

        foreach ($employees as $employee) {
            if ($employee->currentGaji) {
                $gaji->push($employee->currentGaji);
            }
        }

        $pembelian = Pembelian::whereYear('created_at', $year)
            ->whereMonth('created_at', $month)
            ->get();

        // Calculate totals
        $totalDebit = $akuns->where('tipe_akun', 'debit')->sum('nominal') +
                      $history->sum('harga_total');

        $totalKredit = $akuns->where('tipe_akun', 'kredit')->sum('nominal') +
                       $pembelian->sum('harga_total') +
                       $gaji->sum('gaji');  // Gaji entries are credit

        return view('neracaSaldo', compact('akuns', 'month', 'year', 'history', 'gaji', 'pembelian', 'totalDebit', 'totalKredit'));
    }

    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'nama_akun' => 'required|string|max:255',
            'tipe_akun' => 'required|in:debit,kredit',
            'nominal' => 'required|numeric',
        ]);

        NeracaSaldo::create($validatedData);

        return redirect()->route('laporan.neraca-saldo');
    }
}
