<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Stocktransaction;
use App\Models\Substocktransaction;
use App\Models\Product;
use App\Models\Akun;
use App\Models\Cashtransaction;
use App\Models\Credit;
use App\Models\Contact;
use App\Models\CorporateIncomeTax;
use App\Models\CreditCashTransaction;
use App\Models\Language;
use App\Models\Licence;
use App\Models\Subcashtransaction;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ReportNeracaController extends Controller
{
    public static function getActiveLanguage()
    {
        return Language::where('status', true)->first();
    }

    private function loadTypeMapping($langCode = 'id')
    {
        $jsonPath = config_path("lang/{$langCode}/neraca.json");

        // Fallback ke bahasa Indonesia jika file tidak ditemukan
        if (!file_exists($jsonPath)) {
            $jsonPath = config_path('lang/id/neraca.json');
        }

        if (!file_exists($jsonPath)) {
            return [];
        }

        return json_decode(file_get_contents($jsonPath), true) ?? [];
    }

    private function translateAccountName($accountName, $entityType, $namaMappingData)
    {
        // Prioritaskan translasi berdasarkan tipe entitas
        if (isset($namaMappingData[$entityType][$accountName])) {
            return $namaMappingData[$entityType][$accountName];
        }

        // Fallback ke translasi umum
        if (isset($namaMappingData['akun_umum'][$accountName])) {
            return $namaMappingData['akun_umum'][$accountName];
        }

        // Jika tidak ditemukan, kembalikan nama asli
        return $accountName;
    }

    function tambahNamaAkunWithTranslation(&$data, $mapping, $entityType, $namaMappingData)
    {
        $translateNestedItems = function (&$items) use (&$translateNestedItems, $mapping, $entityType, $namaMappingData) {
            foreach ($items as &$item) {
                // Translate current item
                if (isset($mapping[$item->name])) {
                    $item->rename = $mapping[$item->name];
                } else {
                    $item->rename = $this->translateAccountName($item->name, $entityType, $namaMappingData);
                }

                // Recursively translate children if they exist
                if (isset($item->children)) {
                    // Convert to collection if it's array
                    if (is_array($item->children)) {
                        $item->children = collect($item->children);
                    }

                    // Process children recursively
                    if ($item->children instanceof Collection && $item->children->isNotEmpty()) {
                        $translateNestedItems($item->children);
                    }
                }
            }
        };

        $translateNestedItems($data);
    }

    public function AkunReportNeraca(Request $request)
    {

        $licence = Licence::first();
        $isKoperasi = $licence && $licence->company_type === 'koperasi';
        $isPT = $licence && $licence->company_type === 'pt';
        $isCV = $licence && $licence->company_type === 'cv';
        $isFirma = $licence && $licence->company_type === 'firma';
        $isYayasan = $licence && $licence->company_type === 'yayasan';
        $isPerorangan = $licence && $licence->company_type === 'perorangan';
        $isBumdes = $licence && $licence->company_type === 'bumdes';
        $isLainnya = $licence && $licence->company_type === 'lainnya';

        Akun::whereNotNull('name')->update(array('total' => 0));

        // CREDIT STOCK MASUK = menghitung uang masuk dari stock
        $cash = Akun::withCount([
            'creditin as sum_stockin' => function ($credit) use ($request) {
                $credit->whereHas('stocktransaction', function ($stock) {
                    $stock->whereNotNull('cashin_id')->whereNull('pending');
                });

                if (!empty($request->start_date) && !empty($request->end_date)) {
                    $start_date = date('Y-m-d', strtotime($request->start_date));
                    $end_date = date('Y-m-d', strtotime($request->end_date));
                    $credit->whereBetween('date', [$start_date, $end_date]);
                } else {
                    $credit->whereBetween('date', ['1111-01-01', date('Y-m-d')]);
                }

                $credit->select(DB::raw("SUM(total)"));
            },
            // CREDIT STOCK KELUAR = menghitung uang keluar dari stock
            'creditout as sum_stockout' => function ($credit) use ($request) {
                $credit->whereHas('stocktransaction', function ($stock) {
                    $stock->whereNotNull('cashout_id')->whereNull('pending');
                });

                if (!empty($request->start_date) && !empty($request->end_date)) {
                    $start_date = date('Y-m-d', strtotime($request->start_date));
                    $end_date = date('Y-m-d', strtotime($request->end_date));
                    $credit->whereBetween('date', [$start_date, $end_date]);
                } else {
                    $credit->whereBetween('date', ['1111-01-01', date('Y-m-d')]);
                }

                $credit->select(DB::raw("SUM(total)"));
            },
            // CREDIT STOCK KELUAR = menghitung uang keluar dari stock credit
            'creditout as sum_creditcashcreditout' => function ($credit) use ($request) {
                $credit->whereHas('stocktransaction', function ($stock) {
                    $stock->whereNotNull('cashout_id')->whereNull('pending');
                });

                if (!empty($request->start_date) && !empty($request->end_date)) {
                    $start_date = date('Y-m-d', strtotime($request->start_date));
                    $end_date = date('Y-m-d', strtotime($request->end_date));
                    $credit->whereBetween('date', [$start_date, $end_date]);
                } else {
                    $credit->whereBetween('date', ['1111-01-01', date('Y-m-d')]);
                }

                $credit->select(DB::raw("SUM(cash_credit)"));
            },
            // CREDIT STOCK MASUK = menghitung uang masuk dari stock credit
            'creditin as sum_creditcashcreditin' => function ($credit) use ($request) {
                $credit->whereHas('stocktransaction', function ($stock) {
                    $stock->whereNotNull('cashin_id')->whereNull('pending');
                });

                if (!empty($request->start_date) && !empty($request->end_date)) {
                    $start_date = date('Y-m-d', strtotime($request->start_date));
                    $end_date = date('Y-m-d', strtotime($request->end_date));
                    $credit->whereBetween('date', [$start_date, $end_date]);
                } else {
                    $credit->whereBetween('date', ['1111-01-01', date('Y-m-d')]);
                }

                $credit->select(DB::raw("SUM(cash_credit)"));
            },
            // return_credit in
            'stocktransactioncashout as sum_returncreditcashout' => function ($credit) use ($request) {
                $credit->whereNotNull('return_credit_cash')->whereNull('pending');
                if (!empty($request->start_date) && !empty($request->end_date)) {
                    $start_date = date('Y-m-d', strtotime($request->start_date));
                    $end_date = date('Y-m-d', strtotime($request->end_date));
                    $credit->whereBetween('date', [$start_date, $end_date]);
                } else {
                    $credit->whereBetween('date', ['1111-01-01', date('Y-m-d')]);
                }
                return $credit->select(DB::raw("SUM(return_credit_cash)"));
            },
            // return_credit out
            'stocktransactioncashin as sum_returncreditcashin' => function ($credit) use ($request) {
                $credit->whereNotNull('return_credit_cash')->whereNull('pending');
                if (!empty($request->start_date) && !empty($request->end_date)) {
                    $start_date = date('Y-m-d', strtotime($request->start_date));
                    $end_date = date('Y-m-d', strtotime($request->end_date));
                    $credit->whereBetween('date', [$start_date, $end_date]);
                } else {
                    $credit->whereBetween('date', ['1111-01-01', date('Y-m-d')]);
                }
                return $credit->select(DB::raw("SUM(return_credit_cash)"));
            },
            // CASH FROM = menghitung cash sebagai akun
            'cashtransactionfrom as sum_cashfrom' => function ($cash) use ($request) {
                $excludedCategories = ['biaya', 'bayar_pajak_final', 'bayar_pajak_final', 'bayar_hutang_pph21', 'beli_aset', 'tarik_dividen', 'biaya_produksi_aktual', 'cicil_pph25', 'deposit_coretax', 'bayar_hutang_pph'];

                // Ambil semua ID transaksi yang memiliki kategori 'biaya' atau 'beli_aset'
                $transactionsWithExcludedCategories = DB::table('cashtransactions')
                    ->whereIn('transaction_category', $excludedCategories)
                    ->pluck('id')
                    ->toArray();

                // Ambil ID yang benar-benar ada di credit_cashtransactions
                $validTransactionIds = DB::table('credit_cashtransactions')
                    ->whereIn('cashtransaction_id', $transactionsWithExcludedCategories)
                    ->pluck('cashtransaction_id')
                    ->toArray();

                // Jika hanya transaksi tertentu yang memiliki pasangan di credit_cashtransactions, exclude berdasarkan ID
                if (!empty($validTransactionIds)) {
                    $cash->whereNotIn('id', $validTransactionIds);
                }

                // Pengecekan tanggal
                if (!empty($request->start_date) && !empty($request->end_date)) {
                    $start_date = date('Y-m-d', strtotime($request->start_date));
                    $end_date = date('Y-m-d', strtotime($request->end_date));
                    $cash->whereBetween('date', [$start_date, $end_date]);
                } else {
                    $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
                }

                // Sum dari cashout + transfer
                $cash->select(DB::raw("SUM(cashout + transfer)"));
            },
            // CASH TO = menghitung cash sebagai akun
            'cashtransactionto as sum_cashto' => function ($cash) use ($request) {
                $excludedCategories = ['simpanan_wajib', 'pendapatan', 'jual_aset'];
                $cash->whereNotIn('transaction_category', $excludedCategories);

                if (!empty($request->start_date) && !empty($request->end_date)) {
                    $start_date = date('Y-m-d', strtotime($request->start_date));
                    $end_date = date('Y-m-d', strtotime($request->end_date));
                    $cash->whereBetween('date', [$start_date, $end_date]);
                } else {
                    $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
                }
                $cash->select(DB::raw("SUM(cashin+transfer)"));
            },
            // CASH TO SIMPANAN WAJIB
            'cashtransactionto as sum_simwa' => function ($cash) use ($request) {
                $cash->where('transaction_category', 'simpanan_wajib');

                if (!empty($request->start_date) && !empty($request->end_date)) {
                    $start_date = date('Y-m-d', strtotime($request->start_date));
                    $end_date = date('Y-m-d', strtotime($request->end_date));
                    $cash->whereBetween('date', [$start_date, $end_date]);
                } else {
                    $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
                }
                $cash->select(DB::raw("SUM(cashin+transfer)"));
            },
            // CREDIT CASH
            'creditCashFrom as sum_creditcashfrom' => function ($credit) use ($request) {
                if (!empty($request->start_date) && !empty($request->end_date)) {
                    $start_date = date('Y-m-d', strtotime($request->start_date));
                    $end_date = date('Y-m-d', strtotime($request->end_date));
                    $credit->whereBetween('date', [$start_date, $end_date]);
                } else {
                    $credit = $credit->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
                }
                $credit->select(DB::raw("SUM(total)"));
            },
            'creditCashTo as sum_creditcashto' => function ($credit) use ($request) {
                if (!empty($request->start_date) && !empty($request->end_date)) {
                    $start_date = date('Y-m-d', strtotime($request->start_date));
                    $end_date = date('Y-m-d', strtotime($request->end_date));
                    $credit->whereBetween('date', [$start_date, $end_date]);
                } else {
                    $credit = $credit->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
                }
                $credit->select(DB::raw("SUM(total)"));
            }
        ])->where('iscash', true)->get();

        foreach ($cash as $key => $value) {
            $simwa = $isKoperasi ? $value->sum_simwa : 0;
            $value->total = ($value->sum_stockin - $value->sum_stockout) + ($value->sum_cashto - $value->sum_cashfrom) + $value->sum_returncreditcashout - $value->sum_returncreditcashin - $value->sum_creditcashcreditout + $value->sum_creditcashcreditin - $value->sum_creditcashfrom + $value->sum_creditcashto + $simwa;
        }
        $pendingCash = Akun::withCount([
            'creditin as sum_stockin' => function ($credit) use ($request) {
                $credit->whereHas('stocktransaction', function ($stock) use ($request) {
                    $stock = $stock->whereNotNull('cashin_id')->whereNotNull('pending');
                    if (!empty($request->start_date) && !empty($request->end_date)) {
                        $start_date = date('Y-m-d', strtotime($request->start_date));
                        $end_date = date('Y-m-d', strtotime($request->end_date));
                        $stock->whereBetween('date', [$start_date, $end_date]);
                    } else {
                        $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
                    }
                })->select(DB::raw("SUM(total)"));
            },
            // CREDIT STOCK KELUAR = menghitung uang keluar dari stock
            'creditout as sum_stockout' => function ($credit) use ($request) {
                $credit->whereHas('stocktransaction', function ($stock) use ($request) {
                    $stock = $stock->whereNotNull('cashout_id')->whereNotNull('pending');
                    if (!empty($request->start_date) && !empty($request->end_date)) {
                        $start_date = date('Y-m-d', strtotime($request->start_date));
                        $end_date = date('Y-m-d', strtotime($request->end_date));
                        $stock->whereBetween('date', [$start_date, $end_date]);
                    } else {
                        $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
                    }
                })->select(DB::raw("SUM(total)"));
            }
        ])->where('iscash', true)->get();

        foreach ($pendingCash as $key => $value) {
            $value->total = $value->sum_stockin - $value->sum_stockout;
        }
        // SUB CASH IN = menghitung cash sebagai akun
        $cashin = Akun::withCount([
            'subcashtransaction as sum_subcash' => function ($sub) use ($request) {
                $sub->select(DB::raw("SUM(total)"))->whereHas('cashtransaction', function ($cash) use ($request) {
                    $cash->whereNotNull('to')->where('transaction_category', '<>', ['refund_pesanan_pembelian', 'tarik_cadangan_wajib'])->whereNotIn('transaction_category', ['cadangan_wajib', 'utang_dividen']);
                    if (!empty($request->start_date) && !empty($request->end_date)) {
                        $start_date = date('Y-m-d', strtotime($request->start_date));
                        $end_date = date('Y-m-d', strtotime($request->end_date));
                        $cash->whereBetween('date', [$start_date, $end_date]);
                    } else {
                        $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
                    }
                });
            },
            // Saldo Awal
            'subcashtransaction as sum_beginningbalance' => function ($sub) use ($request) {
                $sub->select(DB::raw("SUM(total)"))->whereHas('cashtransaction', function ($cash) use ($request) {
                    // $cash->whereNotNull('beginning_balance')->whereIn('transaction_category', ['hutang', 'saldo_awal']);
                    $cash->whereNotNull('beginning_balance')->whereIn('transaction_category', ['saldo_awal']);
                    if (!empty($request->start_date) && !empty($request->end_date)) {
                        $start_date = date('Y-m-d', strtotime($request->start_date));
                        $end_date = date('Y-m-d', strtotime($request->end_date));
                        $cash->whereBetween('date', [$start_date, $end_date]);
                    } else {
                        $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
                    }
                });
            }
        ])->get();

        foreach ($cashin as $key => $value) {
            // Jika bukan koperasi dan nama adalah "Simpanan Wajib", skip item ini
            if (!$isKoperasi && $value->name === 'Simpanan Wajib') {
                continue;
            }

            $value->total = $value->sum_subcash + $value->sum_beginningbalance;
        }

        // SUB CASH OUT
        // Laba Ditahan = mengecek subcashtransaction yang akun_id nya itu 77 (laba ditahan)
        $cashout = Akun::withCount([
            'subcashtransaction as sum_subcash' => function ($sub) use ($request) {
                $sub->select(DB::raw("SUM(total)"))->whereHas('cashtransaction', function ($cash) use ($request) {
                    $cash->whereNotNull('from')->where('transaction_category', '<>', ['refund_pesanan_penjualan', 'biaya'])->whereNotIn('transaction_category', ['prive', 'tarik_laba', 'biaya_produksi_dibebankan', 'biaya_produksi_aktual', 'bayar_pajak_final']);

                    if (!empty($request->start_date) && !empty($request->end_date)) {
                        $start_date = date('Y-m-d', strtotime($request->start_date));
                        $end_date = date('Y-m-d', strtotime($request->end_date));
                        $cash->whereBetween('date', [$start_date, $end_date]);
                    } else {
                        $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
                    }
                });
            },
            // Saldo Awal piutang
            'subcashtransaction as sum_beginningbalance' => function ($sub) use ($request) {
                $sub->select(DB::raw("SUM(total)"))->whereHas('cashtransaction', function ($cash) use ($request) {
                    // $cash->whereNotNull('beginning_balance')->whereIn('transaction_category', ['biaya','catat_piutang']);
                    $cash->whereNotNull('beginning_balance')->whereIn('transaction_category', ['biaya']);
                    if (!empty($request->start_date) && !empty($request->end_date)) {
                        $start_date = date('Y-m-d', strtotime($request->start_date));
                        $end_date = date('Y-m-d', strtotime($request->end_date));
                        $cash->whereBetween('date', [$start_date, $end_date]);
                    } else {
                        $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
                    }
                });
            },
            // Saldo Awal biaya
            'subcashtransaction as sum_biaya' => function ($sub) use ($request) {
                $sub->select(DB::raw("SUM(total)"))->whereHas('cashtransaction', function ($cash) use ($request) {
                    $cash->whereNotNull('beginning_balance')->where('transaction_category', 'biaya');
                    if (!empty($request->start_date) && !empty($request->end_date)) {
                        $start_date = date('Y-m-d', strtotime($request->start_date));
                        $end_date = date('Y-m-d', strtotime($request->end_date));
                        $cash->whereBetween('date', [$start_date, $end_date]);
                    } else {
                        $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
                    }
                });
            }
        ])->get();

        foreach ($cashout as $key => $value) {
            // $value->total = $value->sum_subcash + $value->sum_beginningbalance - $value->sum_biaya;
            $value->total = $value->sum_subcash + $value->sum_beginningbalance;
        }

        // Credit Cashtransaction
        // credit pendapatan
        $cashpendapatanIds = CreditCashTransaction::whereHas('cashtransaction', function ($query) {
            $query->where('transaction_category', 'pendapatan');
        })
            ->pluck('cashtransaction_id')
            ->unique();

        $cashPendapatanQuery = CashTransaction::whereIn('id', $cashpendapatanIds);
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $cashPendapatanQuery->whereBetween('date', [$start_date, $end_date]);
        } else {
            $cashPendapatanQuery = $cashPendapatanQuery->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $totalPendapatan = (float) $cashPendapatanQuery->sum('total') + ($cashPendapatanQuery->sum('pph4_2_amount_v2') * 2);

        $creditpendapatan = CreditCashTransaction::whereHas('cashtransaction', function ($query) use ($request) {
            $query->whereIn('transaction_category', ['pendapatan']);
        });
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $creditpendapatan->whereBetween('date', [$start_date, $end_date]);
        } else {
            $creditpendapatan = $creditpendapatan->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $creditpendapatan = (float) $creditpendapatan->sum('total');

        // credit jual aset
        $cashjualasetIds = CreditCashTransaction::whereHas('cashtransaction', function ($query) {
            $query->where('transaction_category', 'jual_aset');
        })
            ->pluck('cashtransaction_id')
            ->unique();

        $cashjualasetQuery = CashTransaction::whereIn('id', $cashjualasetIds);
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $cashjualasetQuery->whereBetween('date', [$start_date, $end_date]);
        } else {
            $cashjualasetQuery = $cashjualasetQuery->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $totaljualaset = (float) $cashjualasetQuery->sum('total') + ($cashjualasetQuery->sum('pph4_2_amount_v2') * 2);

        $creditjualaset = CreditCashTransaction::whereHas('cashtransaction', function ($query) use ($request) {
            $query->whereIn('transaction_category', ['jual_aset']);
        });
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $creditjualaset->whereBetween('date', [$start_date, $end_date]);
        } else {
            $creditjualaset = $creditjualaset->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $creditjualaset = (float) $creditjualaset->sum('total');

        // Tarik Laba
        $tariklabaltb = Cashtransaction::where('transaction_category', 'tarik_laba')
            ->whereHas('subcashtransaction', function ($query) {
                $aknltb = Akun::where('name', 'Laba Tahun Berjalan')->first();
                if ($aknltb) {
                    $query->where('akun_id', $aknltb->id);
                }
            });
        $tariklabald = Cashtransaction::where('transaction_category', 'tarik_laba')
            ->whereHas('subcashtransaction', function ($query) {
                $akunld = Akun::where('name', 'Laba Ditahan')->first();
                if ($akunld) {
                    $query->where('akun_id', $akunld->id);
                }
            });

        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $tariklabaltb->whereBetween('date', [$start_date, $end_date]);
            $tariklabald->whereBetween('date', [$start_date, $end_date]);
        } else {
            $tariklabaltb->whereBetween('date', ['1111-01-01', now()->format('Y-m-d')]);
            $tariklabald->whereBetween('date', ['1111-01-01', now()->format('Y-m-d')]);
        }

        $tariklabaltb = (float) $tariklabaltb->sum('cashout');
        $tariklabald = (float) $tariklabald->sum('cashout');

        // PENDAPATAN
        $jasa = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'service');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('cashin_id')->whereNull('pending')->whereNull('return');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->sum('total');

        // penjualan
        $penjualan = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', '<>', 'service');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('cashin_id')->whereNull('pending')->whereNull('return')->whereNull('type');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->sum('total');

        $return_in = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', '<>', 'service');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('cashout_id')->whereNull('pending')->where('return', 'in');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->sum('total');

        $return_in_sell = Substocktransaction::whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('cashout_id')->whereNull('pending')->where('return', 'in');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->selectRaw('SUM(substocktransactions.selling_price * substocktransactions.qty) as total')->first()->total;

        $return_out = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', '<>', 'service');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('cashout_id')->whereNull('pending')->whereNull('return')->where('return', 'out');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->sum('total');

        // PENDAPATAN barang
        $barang = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('nonmoney', 'in')->whereNull('type');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->sum('total');

        // Kerugian barang
        $barangrugi = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('nonmoney', 'out');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->sum('hpp');

        // Potongan beli
        $potonganbeli = Stocktransaction::whereNotNull('cashout_id')->whereNull('pending')->whereNull('return');
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $potonganbeli->whereBetween('date', [$start_date, $end_date]);
        } else {
            $potonganbeli = $potonganbeli->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $potonganbeli = $potonganbeli->sum('discount');

        // Potongan jual
        $potonganjual = Stocktransaction::whereNotNull('cashin_id')->whereNull('pending')->whereNull('return');
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $potonganjual->whereBetween('date', [$start_date, $end_date]);
        } else {
            $potonganjual = $potonganjual->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $potonganjual = $potonganjual->sum('discount');

        // HPP

        $hpp = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', '<>', 'service');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
            $stock = $stock->whereNotNull('cashin_id');
        })->sum('hpp');

        // Piutang jual
        $piutangjualstock = Stocktransaction::whereNotNull('cashin_id')->whereNull('pending')->whereNull('return');
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $piutangjualstock->whereBetween('date', [$start_date, $end_date]);
        } else {
            $piutangjualstock = $piutangjualstock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }

        $akunPPh4_2 = Akun::where('name', 'Biaya_PPh_4_2')->first();
        $akunUtangPPh4_2 = Akun::where('name', 'Utang_PPh_Pasal_4_ayat_2')->first();
        $piutangjualcredit = Credit::whereNotNull('cashin_id')->whereNotIn('cashin_id', [$akunPPh4_2->id, $akunUtangPPh4_2->id])->wherehas('stocktransaction', function ($stock) {
            $stock->whereNotNull('cashin_id')->whereNull('pending')->whereNull('return');
        });
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $piutangjualcredit->whereBetween('date', [$start_date, $end_date]);
        } else {
            $piutangjualcredit = $piutangjualcredit->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }

        $piutangjualreturn = Stocktransaction::where('return', 'in')->whereNotNull('return_credit_cash');
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $piutangjualreturn->whereBetween('date', [$start_date, $end_date]);
        } else {
            $piutangjualreturn = $piutangjualreturn->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }

        $piutangjual = $piutangjualstock->sum('total') - $piutangjualstock->sum('discount') - $piutangjualcredit->sum('total') - $piutangjualreturn->sum('return_credit_cash');

        $akunpiutangpph23 = Akun::where('name', 'Piutang_PPh_Pasal_23')->first();
        $piutangstockpph23 = Credit::where('cashin_id', $akunpiutangpph23->id)->wherehas('stocktransaction', function ($stock) {
            $stock->whereNotNull('cashin_id')->whereNotNull('pph23_amount');
        });
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $piutangstockpph23->whereBetween('date', [$start_date, $end_date]);
        } else {
            $piutangstockpph23 = $piutangstockpph23->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $piutangcashpph23 = CreditCashTransaction::where('to_id', $akunpiutangpph23->id)->wherehas('cashtransaction', function ($stock) {
            $stock->whereNotNull('to')->whereNotNull('pph23_amount');
        });
        $piutangcashpph23normal = CreditCashTransaction::where('from_id', $akunpiutangpph23->id)->wherehas('corporateincome', function ($stock) {
            $stock->whereNotNull('tax_amount')->whereIn('transaction_category', ['normal']);
        });
        $piutangcashpph23sohoout = CreditCashTransaction::where('from_id', $akunpiutangpph23->id)->wherehas('corporateincome', function ($stock) {
            $stock->whereNotNull('tax_amount')->whereIn('transaction_category', ['soho_out']);
        });
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $piutangcashpph23->whereBetween('date', [$start_date, $end_date]);
            $piutangcashpph23normal->whereBetween('date', [$start_date, $end_date]);
            $piutangcashpph23sohoout->whereBetween('date', [$start_date, $end_date]);
        } else {
            $piutangcashpph23 = $piutangcashpph23->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            $piutangcashpph23normal = $piutangcashpph23normal->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            $piutangcashpph23sohoout = $piutangcashpph23sohoout->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $piutangcashpph23normal = $piutangcashpph23normal->sum('total');
        $piutangcashpph23sohoout = $piutangcashpph23sohoout->sum('total');
        $piutangpph23 = $piutangstockpph23->sum('total') + $piutangcashpph23->sum('total') - $piutangcashpph23normal - $piutangcashpph23sohoout;

        $akunpiutangpph25 = Akun::where('name', 'Piutang_PPh_Pasal_25')->first();
        $piutangpph25normal = CreditCashTransaction::where('from_id', $akunpiutangpph25->id)->wherehas('corporateincome', function ($stock) {
            $stock->whereNotNull('tax_amount')->whereIn('transaction_category', ['normal']);
        });
        $piutangpph25sohoout = CreditCashTransaction::where('from_id', $akunpiutangpph25->id)->wherehas('corporateincome', function ($stock) {
            $stock->whereNotNull('tax_amount')->whereIn('transaction_category', ['soho_out']);
        });
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $piutangpph25normal->whereBetween('date', [$start_date, $end_date]);
            $piutangpph25sohoout->whereBetween('date', [$start_date, $end_date]);
        } else {
            $piutangpph25normal = $piutangpph25normal->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            $piutangpph25sohoout = $piutangpph25sohoout->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $piutangpph25 = -abs((float) $piutangpph25normal->sum('total'));
        $piutangpph25sohoout = -abs((float) $piutangpph25sohoout->sum('total'));

        $akunuangmukapph22 = Akun::where('name', 'Uang_Muka_PPh_22')->first();
        $uangmukastockpph22 = Credit::where('cashin_id', $akunuangmukapph22->id)->wherehas('stocktransaction', function ($stock) {
            $stock->whereNotNull('cashin_id')->whereNotNull('pph22_amount');
        });
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $uangmukastockpph22->whereBetween('date', [$start_date, $end_date]);
        } else {
            $uangmukastockpph22 = $uangmukastockpph22->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $uangmukacashpph22 = CreditCashTransaction::where('to_id', $akunuangmukapph22->id)->wherehas('cashtransaction', function ($stock) {
            $stock->whereNotNull('to')->whereNotNull('pph22_amount');
        });
        $uangmukacashpph22normal = CreditCashTransaction::where('from_id', $akunuangmukapph22->id)->wherehas('corporateincome', function ($stock) {
            $stock->whereNotNull('tax_amount')->whereIn('transaction_category', ['normal']);
        });
        $uangmukacashpph22sohoout = CreditCashTransaction::where('from_id', $akunuangmukapph22->id)->wherehas('corporateincome', function ($stock) {
            $stock->whereNotNull('tax_amount')->whereIn('transaction_category', ['soho_out']);
        });
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $uangmukacashpph22->whereBetween('date', [$start_date, $end_date]);
            $uangmukacashpph22normal->whereBetween('date', [$start_date, $end_date]);
            $uangmukacashpph22sohoout->whereBetween('date', [$start_date, $end_date]);
        } else {
            $uangmukacashpph22 = $uangmukacashpph22->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            $uangmukacashpph22normal = $uangmukacashpph22normal->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            $uangmukacashpph22sohoout = $uangmukacashpph22sohoout->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $uangmukacashpph22normal = $uangmukacashpph22normal->sum('total');
        $uangmukacashpph22sohoout = $uangmukacashpph22sohoout->sum('total');
        $uangmukapph22 = $uangmukastockpph22->sum('total') + $uangmukacashpph22->sum('total') - $uangmukacashpph22normal - $uangmukacashpph22sohoout;

        $akunpiutangpph21 = Akun::where('name', 'Piutang_PPh_21')->first();
        $piutangstockpph21 = Credit::where('cashin_id', $akunpiutangpph21->id)->wherehas('stocktransaction', function ($stock) {
            $stock->whereNotNull('cashin_id')->whereNotNull('pph21_amount');
        });
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $piutangstockpph21->whereBetween('date', [$start_date, $end_date]);
        } else {
            $piutangstockpph21 = $piutangstockpph21->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $piutangcashpph21 = CreditCashTransaction::where('to_id', $akunpiutangpph21->id)->wherehas('cashtransaction', function ($stock) {
            $stock->whereNotNull('to')->whereNotNull('pph21_amount');
        });
        $piutangcashpph21normal = CreditCashTransaction::where('from_id', $akunpiutangpph21->id)->wherehas('corporateincome', function ($stock) {
            $stock->whereNotNull('tax_amount')->whereIn('transaction_category', ['normal']);
        });
        $piutangcashpph21sohoout = CreditCashTransaction::where('from_id', $akunpiutangpph21->id)->wherehas('corporateincome', function ($stock) {
            $stock->whereNotNull('tax_amount')->whereIn('transaction_category', ['soho_out']);
        });
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $piutangcashpph21->whereBetween('date', [$start_date, $end_date]);
            $piutangcashpph21normal->whereBetween('date', [$start_date, $end_date]);
            $piutangcashpph21sohoout->whereBetween('date', [$start_date, $end_date]);
        } else {
            $piutangcashpph21->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            $piutangcashpph21normal->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            $piutangcashpph21sohoout->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $piutangcashpph21normal = $piutangcashpph21normal->sum('total');
        $piutangcashpph21sohoout = $piutangcashpph21sohoout->sum('total');
        $piutangpph21 = $piutangstockpph21->sum('total') + $piutangcashpph21->sum('total') - $piutangcashpph21normal - $piutangcashpph21sohoout;

        $akunpiutangpph4_2 = Akun::where('name', 'Biaya_PPh_4_2')->first();
        $biayastockpph4_2 = Credit::where('cashin_id', $akunpiutangpph4_2->id)->wherehas('stocktransaction', function ($stock) {
            $stock->whereNotNull('cashin_id')->whereNotNull('pph4_2_amount');
        });
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $biayastockpph4_2->whereBetween('date', [$start_date, $end_date]);
        } else {
            $biayastockpph4_2 = $biayastockpph4_2->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $biayacashpph4_2 = CreditCashTransaction::where('to_id', $akunpiutangpph4_2->id)
            ->whereHas('cashtransaction', function ($q) {
                $q->whereNotNull('to')
                    ->where(function ($pph) {
                        $pph->whereNotNull('pph4_2_amount')
                            ->orWhereNotNull('pph4_2_amount_v2');
                    });
            });
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $biayacashpph4_2->whereBetween('date', [$start_date, $end_date]);
        } else {
            $biayacashpph4_2 = $biayacashpph4_2->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $biayapph4_2 = $biayastockpph4_2->sum('total') + $biayacashpph4_2->sum('total');

        $akunpiutangpph28 = Akun::where('name', 'Piutang_PPh_28')->first();
        $piutangpph28in = CreditCashTransaction::where('to_id', $akunpiutangpph28->id)->wherehas('corporateincome', function ($stock) {
            $stock->whereNotNull('tax_amount')->whereIn('transaction_category', ['normal']);
        });
        $piutangpph28out = CreditCashTransaction::where('from_id', $akunpiutangpph28->id)->wherehas('corporateincome', function ($stock) {
            $stock->whereNotNull('tax_amount')->whereIn('transaction_category', ['normal']);
        });
        $piutangpph28transfer = CashTransaction::whereNotNull('transfer')->where('transaction_category', 'restitusi');
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $piutangpph28in->whereBetween('date', [$start_date, $end_date]);
            $piutangpph28out->whereBetween('date', [$start_date, $end_date]);
            $piutangpph28transfer->whereBetween('date', [$start_date, $end_date]);
        } else {
            $piutangpph28in->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            $piutangpph28out->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            $piutangpph28transfer->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $piutangpph28 = $piutangpph28in->sum('total') - $piutangpph28out->sum('total') - $piutangpph28transfer->sum('transfer');
        $piutangpph28inout = $piutangpph28in->sum('total') - $piutangpph28out->sum('total');

        $corporate_income_tax_soho = CorporateIncomeTax::where('transaction_category', 'soho');
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $corporate_income_tax_soho->whereBetween('date', [$start_date, $end_date]);
        } else {
            $corporate_income_tax_soho->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $corporate_income_tax_soho = $corporate_income_tax_soho->sum('tax_amount');

        $corporate_income_tax_normal = CorporateIncomeTax::where('transaction_category', 'normal');
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $corporate_income_tax_normal->whereBetween('date', [$start_date, $end_date]);
        } else {
            $corporate_income_tax_normal->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $corporate_income_tax_normal = $corporate_income_tax_normal->sum('tax_amount');

        $corporate_income_tax_sohoout = CorporateIncomeTax::where('transaction_category', 'soho_out');
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $corporate_income_tax_sohoout->whereBetween('date', [$start_date, $end_date]);
        } else {
            $corporate_income_tax_sohoout->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $corporate_income_tax_sohoout = $corporate_income_tax_sohoout->sum('tax_base');
        $corporate_income_tax = $corporate_income_tax_soho + $corporate_income_tax_normal + $corporate_income_tax_sohoout;

        $akundepositcoretax = Akun::where('name', 'Deposit_Pajak_Coretax')->first();
        $depositcoretaxfrom = CreditCashTransaction::where('from_id', $akundepositcoretax->id)->wherehas('cashtransaction', function ($stock) {
            $stock->whereNotNull('from');
        });
        $depositcoretaxto = CreditCashTransaction::where('to_id', $akundepositcoretax->id)->wherehas('cashtransaction', function ($stock) {
            $stock->whereNotNull('to');
        });
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $depositcoretaxfrom->whereBetween('date', [$start_date, $end_date]);
            $depositcoretaxto->whereBetween('date', [$start_date, $end_date]);
        } else {
            $depositcoretaxfrom = $depositcoretaxfrom->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            $depositcoretaxto = $depositcoretaxto->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $depositcoretax = $depositcoretaxto->sum('total') - $depositcoretaxfrom->sum('total');


        $akunutangpph23 = Akun::where('name', 'Utang_PPh_23')->first();
        $cashutangpph23 = CreditCashTransaction::where('from_id', $akunutangpph23->id)->wherehas('cashtransaction', function ($stock) {
            $stock->whereNotNull('from')->whereNotNull('pph23_amount');
        });
        $stockutangpph23 = Credit::where('cashout_id', $akunutangpph23->id)->wherehas('stocktransaction', function ($stock) {
            $stock->whereNotNull('cashout_id')->whereNotNull('pph23_amount');
        });
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $cashutangpph23->whereBetween('date', [$start_date, $end_date]);
            $stockutangpph23->whereBetween('date', [$start_date, $end_date]);
        } else {
            $cashutangpph23 = $cashutangpph23->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            $stockutangpph23 = $stockutangpph23->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $utangpph23 = $cashutangpph23->sum('total') + $stockutangpph23->sum('total');

        $akunutangpph21 = Akun::where('name', 'Utang_PPh_21')->first();
        $cashutangpph21 = CreditCashTransaction::where('from_id', $akunutangpph21->id)->wherehas('cashtransaction', function ($stock) {
            $stock->whereNotNull('from')->whereNotNull('pph21_amount');
        });
        $stockutangpph21 = Credit::where('cashout_id', $akunutangpph21->id)->wherehas('stocktransaction', function ($stock) {
            $stock->whereNotNull('cashout_id')->whereNotNull('pph21_amount');
        });
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $cashutangpph21->whereBetween('date', [$start_date, $end_date]);
            $stockutangpph21->whereBetween('date', [$start_date, $end_date]);
        } else {
            $cashutangpph21 = $cashutangpph21->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            $stockutangpph21 = $stockutangpph21->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $utangpph21 = $cashutangpph21->sum('total') + $stockutangpph21->sum('total');

        $akunutangpph4_2 = Akun::where('name', 'Utang_PPh_Pasal_4_ayat_2')->first();
        $cashutangpph4_2 = CreditCashTransaction::where('from_id', $akunutangpph4_2->id)->wherehas('cashtransaction', function ($stock) {
            $stock->whereNotNull('from')->whereNotNull('pph4_2_amount');
        });
        $cashutangpph4_2_v2 = CreditCashTransaction::where('to_id', $akunutangpph4_2->id)->wherehas('cashtransaction', function ($stock) {
            $stock->whereNotNull('to')->whereNotNull('pph4_2_amount_v2');
        });
        $stockutangpph4_2 = Credit::where('cashout_id', $akunutangpph4_2->id)->wherehas('stocktransaction', function ($stock) {
            $stock->whereNotNull('cashout_id')->whereNotNull('pph4_2_amount');
        });
        $stockutangpph4_2_v2 = Credit::where('cashin_id', $akunutangpph4_2->id)->wherehas('stocktransaction', function ($stock) {
            $stock->whereNotNull('cashin_id')->whereNotNull('pph4_2_amount_v2');
        });

        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $cashutangpph4_2->whereBetween('date', [$start_date, $end_date]);
            $cashutangpph4_2_v2->whereBetween('date', [$start_date, $end_date]);
            $stockutangpph4_2->whereBetween('date', [$start_date, $end_date]);
            $stockutangpph4_2_v2->whereBetween('date', [$start_date, $end_date]);
        } else {
            $cashutangpph4_2->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            $cashutangpph4_2_v2->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            $stockutangpph4_2->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            $stockutangpph4_2_v2->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $utangpph4_2 = $cashutangpph4_2->sum('total') + $cashutangpph4_2_v2->sum('total') + $stockutangpph4_2->sum('total') + $stockutangpph4_2_v2->sum('total');

        $akunutangpph22 = Akun::where('name', 'Utang_PPh_22')->first();
        $cashutangpph22 = CreditCashTransaction::where('from_id', $akunutangpph22->id)->wherehas('cashtransaction', function ($stock) {
            $stock->whereNotNull('from')->whereNotNull('pph22_amount');
        });
        $stockutangpph22 = Credit::where('cashout_id', $akunutangpph22->id)->wherehas('stocktransaction', function ($stock) {
            $stock->whereNotNull('cashout_id')->whereNotNull('pph22_amount');
        });
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $cashutangpph22->whereBetween('date', [$start_date, $end_date]);
            $stockutangpph22->whereBetween('date', [$start_date, $end_date]);
        } else {
            $cashutangpph22 = $cashutangpph22->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            $stockutangpph22 = $stockutangpph22->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $utangpph22 = $cashutangpph22->sum('total') + $stockutangpph22->sum('total');

        $akunutangpph26 = Akun::where('name', 'Utang_PPh_26')->first();
        $cashutangpph26 = CreditCashTransaction::where('from_id', $akunutangpph26->id)->wherehas('cashtransaction', function ($stock) {
            $stock->whereNotNull('from')->whereNotNull('pph26_amount');
        });
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $cashutangpph26->whereBetween('date', [$start_date, $end_date]);
        } else {
            $cashutangpph26 = $cashutangpph26->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $utangpph26 = $cashutangpph26->sum('total');

        $akunpiutangpph22 = Akun::where('name', 'Uang_Muka_PPh_22')->first();
        $piutangpph22 = CreditCashTransaction::where('from_id', $akunpiutangpph22->id)->wherehas('cashtransaction', function ($stock) {
            $stock->whereNotNull('from')->whereNotNull('pph22_amount_v2')->whereNotIn('transaction_category', ['beli_aset']);
        });
        $piutangpph22filter = CreditCashTransaction::where('from_id', $akunpiutangpph22->id)->wherehas('cashtransaction', function ($stock) {
            $stock->whereNotNull('from')->whereNotNull('pph22_amount_v2')->whereIn('transaction_category', ['beli_aset']);
        });
        $piutangpph22biaya = CreditCashTransaction::where('from_id', $akunpiutangpph22->id)->wherehas('cashtransaction', function ($stock) {
            $stock->whereNotNull('from')->whereNotNull('pph22_amount_v2')->whereIn('transaction_category', ['biaya']);
        });
        $piutangpph22normal = CreditCashTransaction::where('from_id', $akunpiutangpph22->id)->wherehas('corporateincome', function ($stock) {
            $stock->whereNotNull('tax_amount')->whereIn('transaction_category', ['normal']);
        });
        $piutangpph22sohoout = CreditCashTransaction::where('from_id', $akunpiutangpph22->id)->wherehas('corporateincome', function ($stock) {
            $stock->whereNotNull('tax_amount')->whereIn('transaction_category', ['soho_out']);
        });
        $piutangpph22stock = Credit::where('cashout_id', $akunpiutangpph22->id)->wherehas('stocktransaction', function ($stock) {
            $stock->whereNotNull('cashout_id')->whereNotNull('pph22_amount_v2');
        });
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $piutangpph22->whereBetween('date', [$start_date, $end_date]);
            $piutangpph22filter->whereBetween('date', [$start_date, $end_date]);
            $piutangpph22biaya->whereBetween('date', [$start_date, $end_date]);
            $piutangpph22normal->whereBetween('date', [$start_date, $end_date]);
            $piutangpph22sohoout->whereBetween('date', [$start_date, $end_date]);
            $piutangpph22stock->whereBetween('date', [$start_date, $end_date]);
        } else {
            $piutangpph22->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            $piutangpph22filter->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            $piutangpph22biaya->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            $piutangpph22normal->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            $piutangpph22sohoout->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            $piutangpph22stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $piutangpph22 = $piutangpph22->sum('total');
        $piutangpph22filter = $piutangpph22filter->sum('total');
        $piutangpph22biaya = $piutangpph22biaya->sum('total');
        $piutangpph22normal = $piutangpph22normal->sum('total');
        $piutangpph22sohoout = $piutangpph22sohoout->sum('total');
        $piutangpph22stock = $piutangpph22stock->sum('total');

        // persedian
        $persediaanmasuk = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('cashout_id')->whereNull('pending');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->sum('total');

        $itemmasuk = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('nonmoney', 'in');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->sum('total');

        // saldo awal produk
        $saldoawalproduk = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('beginning_balance');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->sum('total');

        // sum modal barang
        $modal_barang = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', '<>', 'service');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('nonmoney', 'in')->where('type', 'modal_barang');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->sum('total');

        $persediaanhpp = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('cashin_id')->whereNull('pending')->whereNull('return');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->sum('hpp');

        $persediaankeluar = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('nonmoney', 'out');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->sum('hpp');
        $return_pembelian = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('return', 'out');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->sum('total');

        // kurang dari (less than)
        $return_out_price_diff_lt = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('return', 'out');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->whereColumn('purchase_price', '<', 'original_purchase_price')->selectRaw('SUM(substocktransactions.original_purchase_price * substocktransactions.qty) - SUM(total) as total')->first()->total;

        // lebih dari (greater than)
        $return_out_price_diff_gt = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('return', 'out');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->whereColumn('purchase_price', '>', 'original_purchase_price')->selectRaw('SUM(total) - SUM(substocktransactions.original_purchase_price * substocktransactions.qty) as total')->first()->total;

        // (penjualan+item masuk)(item keluar+penjualan)
        $persediaan = ($persediaanmasuk + $itemmasuk + $return_out_price_diff_gt) - ($persediaankeluar + $persediaanhpp + $return_pembelian) - $return_out_price_diff_lt + $saldoawalproduk;

        // PERSEDIAAN BAHAN BAKU (MATERIALS PRODUCT)
        $persediaanmasuk_materials = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product_materials');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('cashout_id')->whereNull('pending');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->sum('total');

        $itemmasuk_materials = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product_materials');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('nonmoney', 'in');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->sum('total');

        $saldoawalproduk_materials = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product_materials');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('beginning_balance');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->sum('total');

        $persediaanhpp_materials = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product_materials');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('cashin_id')->whereNull('pending')->whereNull('return');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->sum('hpp');

        $persediaankeluar_materials = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product_materials');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('nonmoney', 'out');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->sum('hpp');

        $return_pembelian_materials = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product_materials');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('return', 'out');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->sum('total');

        $return_out_price_diff_lt_materials = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product_materials');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('return', 'out');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->whereColumn('purchase_price', '<', 'original_purchase_price')->selectRaw('SUM(substocktransactions.original_purchase_price * substocktransactions.qty) - SUM(total) as total')->first()->total;

        $return_out_price_diff_gt_materials = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product_materials');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('return', 'out');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->whereColumn('purchase_price', '>', 'original_purchase_price')->selectRaw('SUM(total) - SUM(substocktransactions.original_purchase_price * substocktransactions.qty) as total')->first()->total;

        $persediaan_materials = ($persediaanmasuk_materials + $itemmasuk_materials + $return_out_price_diff_gt_materials) - ($persediaankeluar_materials + $persediaanhpp_materials + $return_pembelian_materials) - $return_out_price_diff_lt_materials + $saldoawalproduk_materials;

        // PERSEDIAAN BARANG JADI (FINISHED PRODUCT)
        $persediaanmasuk_finished = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product_finished');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('cashout_id')->whereNull('pending');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->sum('total');

        $itemmasuk_finished = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product_finished');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('nonmoney', 'in')->whereNull('production_id');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->sum('total');

        $itemmasuk_type_produksi = Substocktransaction::whereHas('product', function ($product) {
            $product->whereIn('category', ['product_finished', 'product_materials']);
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('nonmoney', 'in')->whereNull('production_id')->whereNull('type');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->sum('total');

        $saldoawalproduk_finished = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product_finished');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('beginning_balance');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->sum('total');

        $persediaanhpp_finished = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product_finished');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('cashin_id')->whereNull('pending')->whereNull('return');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->sum('hpp');

        $persediaankeluar_finished = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product_finished');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('nonmoney', 'out')->whereNull('production_id');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->sum('hpp');

        $itemkeluar_type_produksi = Substocktransaction::whereHas('product', function ($product) {
            $product->whereIn('category', ['product_finished', 'product_materials']);
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('nonmoney', 'out')->whereNull('production_id');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->sum('hpp');

        $proses_finished = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product_finished');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('nonmoney', 'in')->whereNotNull('production_id');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->sum('total');

        $subtotal_keluar_finished = $persediaankeluar_finished + $persediaanhpp_finished;
        $persediaan_finished = ($persediaanmasuk_finished + $itemmasuk_finished + $proses_finished) - $subtotal_keluar_finished + $saldoawalproduk_finished;

        $prosesproduksi = Substocktransaction::whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('nonmoney', 'out')->whereNotNull('production_id');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $stock->whereBetween('date', [$start_date, $end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->sum('hpp');

        $pesananbeli = Stocktransaction::whereNotNull('cashout_id')->whereNotNull('pending');
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $pesananbeli->whereBetween('date', [$start_date, $end_date]);
        } else {
            $pesananbeli = $pesananbeli->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $pesananbeli = $pesananbeli->sum('paid');

        $akunuangmuka = Akun::where('name', '=', 'Uang Muka Pesanan Pembelian')->first();
        $belibeli = Credit::where('cashout_id', $akunuangmuka->id);
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $belibeli->whereBetween('date', [$start_date, $end_date]);
        } else {
            $belibeli = $belibeli->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $belibeli = $belibeli->sum('total');

        $kembalianbeli = Cashtransaction::where('transaction_category', 'pengembalian_uang_muka');
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $kembalianbeli->whereBetween('date', [$start_date, $end_date]);
        } else {
            $kembalianbeli = $kembalianbeli->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $kembalianbeli = $kembalianbeli->sum('cashin');

        $refundbeli = Cashtransaction::where('transaction_category', 'refund_pesanan_pembelian');
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $refundbeli->whereBetween('date', [$start_date, $end_date]);
        } else {
            $refundbeli = $refundbeli->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $refundbeli = $refundbeli->sum('cashin');

        $kekuranganbeli = Cashtransaction::where('transaction_category', 'kekurangan_pesanan_pembelian');
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $kekuranganbeli->whereBetween('date', [$start_date, $end_date]);
        } else {
            $kekuranganbeli = $kekuranganbeli->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $kekuranganbeli = $kekuranganbeli->sum('cashout');

        $uangmukabeli = $pesananbeli - $belibeli - $refundbeli - ($kembalianbeli * 2);
        // $uangmukabeli = $pesananbeli - $belibeli - $refundbeli - ($kembalianbeli * 2) + $kekuranganbeli;

        $pesananjual = Stocktransaction::whereNotNull('cashin_id')->whereNotNull('pending');
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $pesananjual->whereBetween('date', [$start_date, $end_date]);
        } else {
            $pesananjual = $pesananjual->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $pesananjual = $pesananjual->sum('paid');

        $akunhutangpesananpenjualan = Akun::where('name', '=', 'Hutang Pesanan Penjualan')->first();
        $jualjual = Credit::where('cashin_id', $akunhutangpesananpenjualan->id);
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $jualjual->whereBetween('date', [$start_date, $end_date]);
        } else {
            $jualjual = $jualjual->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $jualjual = $jualjual->sum('total');

        $kembalianjual = Cashtransaction::where('transaction_category', 'pengembalian_hutang_pesanan_penjualan');
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $kembalianjual->whereBetween('date', [$start_date, $end_date]);
        } else {
            $kembalianjual = $kembalianjual->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $kembalianjual = $kembalianjual->sum('cashout');

        $refundjual = Cashtransaction::where('transaction_category', 'refund_pesanan_penjualan');
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $refundjual->whereBetween('date', [$start_date, $end_date]);
        } else {
            $refundjual = $refundjual->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $refundjual = $refundjual->sum('cashout');

        $kekuranganjual = Cashtransaction::where('transaction_category', 'kekurangan_pesanan_penjualan');
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $kekuranganjual->whereBetween('date', [$start_date, $end_date]);
        } else {
            $kekuranganjual = $kekuranganjual->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $kekuranganjual = $kekuranganjual->sum('cashin');

        $pesanjual = $pesananjual - $jualjual - $refundjual - $kembalianjual;
        // $pesanjual = $pesananjual - $jualjual - $refundjual - ($kembalianjual * 2) + $kekuranganjual;

        $hutangbelistock = Stocktransaction::whereNotNull('cashout_id')->whereNull('pending')->whereNull('return');
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $hutangbelistock->whereBetween('date', [$start_date, $end_date]);
        } else {
            $hutangbelistock = $hutangbelistock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }

        $hutangbelicredit = Credit::whereNotNull('cashout_id');
        $hutangbelicredit->wherehas('stocktransaction', function ($stock) {
            $stock->whereNotNull('cashout_id')->whereNull('pending')->whereNull('return');
        });
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $hutangbelicredit->whereBetween('date', [$start_date, $end_date]);
        } else {
            $hutangbelicredit = $hutangbelicredit->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }

        $hutangbelireturn = Stocktransaction::where('return', 'out')->whereNotNull('return_credit_cash');
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $hutangbelireturn->whereBetween('date', [$start_date, $end_date]);
        } else {
            $hutangbelireturn = $hutangbelireturn->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }

        $hutangbeli = $hutangbelistock->sum('total') + $hutangbelistock->sum('pph22_amount_v2') - $hutangbelistock->sum('discount') - $hutangbelicredit->sum('total') - $hutangbelireturn->sum('return_credit_cash');

        // Biaya Lama
        $biayalama = Cashtransaction::where('transaction_category', 'biaya')->whereNull('total');
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $biayalama->whereBetween('date', [$start_date, $end_date]);
        } else {
            $biayalama->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $biayalama = (float) $biayalama->sum('cashout');


        // Biaya yang Masih Harus Dibayar
        $biayaharusdibayarcash = Cashtransaction::whereIn('transaction_category', ['biaya'])
            ->where('total', '>', 0);

        // Pengecekan tanggal
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $biayaharusdibayarcash->whereBetween('date', [$start_date, $end_date]);
        } else {
            $biayaharusdibayarcash->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $biayaharusdibayarcash = (float) $biayaharusdibayarcash->sum('total');

        $biayaharusdibayarcredit = CreditCashTransaction::wherehas('cashtransaction', function ($q) {
            $q->whereIn('transaction_category', ['biaya']);
        });

        // Pengecekan tanggal
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $biayaharusdibayarcredit->whereBetween('date', [$start_date, $end_date]);
        } else {
            $biayaharusdibayarcredit->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $biayaharusdibayarcredit = (float) $biayaharusdibayarcredit->sum('total');

        $biayaharusdibayar = $biayaharusdibayarcash - $biayaharusdibayarcredit;

        // ========================================================================

        // Pengecekan untuk kategori 'beli_aset'
        $hutangpembelianasettetapcash = Cashtransaction::where('transaction_category', 'beli_aset')
            ->where('total', '>', 0);

        // Pengecekan tanggal
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $hutangpembelianasettetapcash->whereBetween('date', [$start_date, $end_date]);
        } else {
            $hutangpembelianasettetapcash->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $hutangpembelianasettetapcash = $hutangpembelianasettetapcash->sum('total');

        $akunpph22 = Akun::where('name', 'Uang_Muka_PPh_22')->first();
        $hutangpembelianasettetapcredit = CreditCashTransaction::whereNotIn('from_id', [$akunpph22->id])->wherehas('cashtransaction', function ($q) {
            $q->where('transaction_category', 'beli_aset');
        });

        // Pengecekan tanggal
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $hutangpembelianasettetapcredit->whereBetween('date', [$start_date, $end_date]);
        } else {
            $hutangpembelianasettetapcredit->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $hutangpembelianasettetapcredit = $hutangpembelianasettetapcredit->sum('total');

        $hutangpembelianasettetap = $hutangpembelianasettetapcash - $hutangpembelianasettetapcredit;

        // Cadangan Wajib Laba Tahun Berjalan
        $aknltb = Akun::where('name', 'Laba Tahun Berjalan')->first();

        $cwltb = Cashtransaction::where('transaction_category', 'cadangan_wajib')
            ->whereHas('subcashtransaction', function ($query) use ($aknltb) {
                if ($aknltb) {
                    $query->where('akun_id', $aknltb->id);
                }
            });

        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $cwltb->whereBetween('date', [$start_date, $end_date]);
        } else {
            $cwltb->whereBetween('date', ['1111-01-01', now()->format('Y-m-d')]);
        }

        $cwltb = (float) $cwltb->sum('total');

        // Cadangan Wajib Laba Ditahan
        $aknltb = Akun::where('name', 'Laba Ditahan')->first();

        $cwldt = Cashtransaction::where('transaction_category', 'cadangan_wajib')
            ->whereHas('subcashtransaction', function ($query) use ($aknltb) {
                if ($aknltb) {
                    $query->where('akun_id', $aknltb->id);
                }
            });

        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $cwldt->whereBetween('date', [$start_date, $end_date]);
        } else {
            $cwldt->whereBetween('date', ['1111-01-01', now()->format('Y-m-d')]);
        }

        $cwldt = (float) $cwldt->sum('total');

        // Tarik Cadangan Wajib Laba Tahun Berjalan
        $aknltb = Akun::where('name', 'Laba Tahun Berjalan')->first();

        $tcwltb = Cashtransaction::where('transaction_category', 'tarik_cadangan_wajib')
            ->where('to', $aknltb->id);

        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $tcwltb->whereBetween('date', [$start_date, $end_date]);
        } else {
            $tcwltb->whereBetween('date', ['1111-01-01', now()->format('Y-m-d')]);
        }

        $tcwltb = (float) $tcwltb->sum('total');

        // Tarik Cadangan Wajib Laba Ditahan
        $aknltb = Akun::where('name', 'Laba Ditahan')->first();

        $tcwldt = Cashtransaction::where('transaction_category', 'tarik_cadangan_wajib')
            ->where('to', $aknltb->id);

        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $tcwldt->whereBetween('date', [$start_date, $end_date]);
        } else {
            $tcwldt->whereBetween('date', ['1111-01-01', now()->format('Y-m-d')]);
        }

        $tcwldt = (float) $tcwldt->sum('total');

        // Utang Dividen
        $utangdividenltb = Cashtransaction::where('transaction_category', 'utang_dividen')
            ->whereHas('subcashtransaction', function ($query) use ($aknltb) {
                $aknltb = Akun::where('name', 'Laba Tahun Berjalan')->first();
                if ($aknltb) {
                    $query->where('akun_id', $aknltb->id);
                }
            });
        $utangdividenld = Cashtransaction::where('transaction_category', 'utang_dividen')
            ->whereHas('subcashtransaction', function ($query) use ($aknltb) {
                $akunld = Akun::where('name', 'Laba Ditahan')->first();
                if ($akunld) {
                    $query->where('akun_id', $akunld->id);
                }
            });

        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $utangdividenltb->whereBetween('date', [$start_date, $end_date]);
            $utangdividenld->whereBetween('date', [$start_date, $end_date]);
        } else {
            $utangdividenltb->whereBetween('date', ['1111-01-01', now()->format('Y-m-d')]);
            $utangdividenld->whereBetween('date', ['1111-01-01', now()->format('Y-m-d')]);
        }

        $utangdividenltb = (float) $utangdividenltb->sum('total');
        $utangdividenld = (float) $utangdividenld->sum('total');

        // Prive
        $prive = Subcashtransaction::whereHas('cashtransaction', function ($query) use ($request) {
            $query->where('transaction_category', 'prive');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $query->whereBetween('date', [$start_date, $end_date]);
            } else {
                $query->whereBetween('date', ['1111-01-01', now()->format('Y-m-d')]);
            }
        });
        $prive = ($isCV || $isFirma || $isPerorangan) ? $prive->sum('total') : 0;

        // Produksi
        $produksi = Akun::withCount([
            'subcashtransaction as sum_subcash' => function ($sub) use ($request) {
                $akunSelisihTenagaKerja = DB::table('akuns')->where('name', 'selisih_tenaga_kerja_langsung')->first();
                $akunOverheadDibebankan = DB::table('akuns')->where('name', 'biaya_overhead_pabrik_dibebankan')->first();
                $excludeIds = [];
                if ($akunSelisihTenagaKerja) {
                    $childrenIds = DB::table('akuns')
                        ->where('perent_id', $akunSelisihTenagaKerja->id)
                        ->pluck('id')
                        ->map(function ($id) {
                            return (int)$id;
                        })
                        ->toArray();
                    $excludeIds = array_merge($excludeIds, $childrenIds);
                }
                if ($akunOverheadDibebankan) {
                    $childrenIds = DB::table('akuns')
                        ->where('perent_id', $akunOverheadDibebankan->id)
                        ->pluck('id')
                        ->map(function ($id) {
                            return (int)$id;
                        })
                        ->toArray();
                    $excludeIds = array_merge($excludeIds, $childrenIds);
                }
                if (!empty($excludeIds)) {
                    $sub->whereNotIn('akun_id', $excludeIds);
                }
                $sub->select(DB::raw("SUM(total)"))->whereHas('cashtransaction', function ($cash) use ($request) {
                    $cash->where('transaction_category', 'biaya_produksi_aktual');
                    if (!empty($request->start_date) && !empty($request->end_date)) {
                        $start_date = date('Y-m-d', strtotime($request->start_date));
                        $end_date = date('Y-m-d', strtotime($request->end_date));
                        $cash->whereBetween('date', [$start_date, $end_date]);
                    } else {
                        $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
                    }
                });
            },
            'subcashtransaction as sum_subtenaga' => function ($sub) use ($request) {
                $akunbtkldibebankan = Akun::where('name', 'biaya_tenaga_kerja_langsung_aktual')->first();
                $sub->select(DB::raw("SUM(total)"))->where('akun_id', $akunbtkldibebankan->id)->whereHas('cashtransaction', function ($cash) use ($request) {
                    $cash->where('transaction_category', 'biaya_produksi_aktual');
                    if (!empty($request->start_date) && !empty($request->end_date)) {
                        $start_date = date('Y-m-d', strtotime($request->start_date));
                        $end_date = date('Y-m-d', strtotime($request->end_date));
                        $cash->whereBetween('date', [$start_date, $end_date]);
                    } else {
                        $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
                    }
                });
            }
        ])->get();

        foreach ($produksi as $key => $value) {
            $value->total = -abs($value->sum_subcash) + $value->sum_subtenaga;
        }

        // Biaya Produksi Dibebankan
        $produksidibebankan = Akun::withCount([
            'subcashtransaction as sum_subcash' => function ($sub) use ($request) {
                $akunOverheadDibebankan = DB::table('akuns')->where('name', 'biaya_overhead_pabrik_dibebankan')->first();
                if ($akunOverheadDibebankan) {
                    $childrenIds = DB::table('akuns')
                        ->where('perent_id', $akunOverheadDibebankan->id)
                        ->pluck('id')
                        ->map(function ($id) {
                            return (int)$id;
                        })
                        ->toArray();
                    if (!empty($childrenIds)) {
                        $sub->whereIn('akun_id', $childrenIds);
                    }
                }
                $sub->select(DB::raw("SUM(total)"))->whereHas('cashtransaction', function ($cash) use ($request) {
                    $cash->where('transaction_category', 'biaya_produksi_dibebankan');
                    if (!empty($request->start_date) && !empty($request->end_date)) {
                        $start_date = date('Y-m-d', strtotime($request->start_date));
                        $end_date = date('Y-m-d', strtotime($request->end_date));
                        $cash->whereBetween('date', [$start_date, $end_date]);
                    } else {
                        $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
                    }
                });
            }
        ])->get();

        foreach ($produksidibebankan as $key => $value) {
            $value->total = $value->sum_subcash + $value->sum_subasset;
        }

        $akunbtkldibebankan = Akun::where('name', 'biaya_tenaga_kerja_langsung_dibebankan')->first();
        $btkldibebankan = Subcashtransaction::where('akun_id', $akunbtkldibebankan->id)
            ->whereHas('cashtransaction', function ($query) use ($request) {
                $query->where('transaction_category', 'biaya_produksi_dibebankan');
                if (!empty($request->start_date) && !empty($request->end_date)) {
                    $start_date = date('Y-m-d', strtotime($request->start_date));
                    $end_date = date('Y-m-d', strtotime($request->end_date));
                    $query->whereBetween('date', [$start_date, $end_date]);
                } else {
                    $query->whereBetween('date', ['1111-01-01', now()->format('Y-m-d')]);
                }
            })->sum('total');

        $assets = Akun::where('is_productionasset', true)->pluck('id')->toArray();
        $assetsproduksi = Subcashtransaction::whereHas('cashtransaction', function ($query) use ($request) {
            $query->where('transaction_category', 'biaya_produksi_dibebankan');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $query->whereBetween('date', [$start_date, $end_date]);
            } else {
                $query->whereBetween('date', ['1111-01-01', now()->format('Y-m-d')]);
            }
        })->whereIn('akun_id', $assets)->sum('total');

        // Hutang tenaga kerja produksi
        $akunbtklaktual = Akun::where('name', 'biaya_tenaga_kerja_langsung_aktual')->first();
        $totalhutangtenagakerja = Subcashtransaction::where('akun_id', $akunbtklaktual->id)->whereHas('cashtransaction', function ($query) use ($request) {
            $query->where('transaction_category', 'biaya_produksi_aktual');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $query->whereBetween('date', [$start_date, $end_date]);
            } else {
                $query->whereBetween('date', ['1111-01-01', now()->format('Y-m-d')]);
            }
        })->sum('total');

        $hutangtenagakerja = CreditCashTransaction::whereHas('cashtransaction', function ($q) {
            $q->where('transaction_category', 'biaya_produksi_aktual')->whereHas('subcashtransaction', function ($sub) {
                $akunbtklaktual = Akun::where('name', 'biaya_tenaga_kerja_langsung_aktual')->first();
                $sub->where('akun_id', $akunbtklaktual->id);
            });
        });

        // Pengecekan tanggal
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $hutangtenagakerja->whereBetween('date', [$start_date, $end_date]);
        } else {
            $hutangtenagakerja->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $hutangtenagakerja = (float) $totalhutangtenagakerja - (float) $hutangtenagakerja->sum('total');

        // Hutang Overhead produksi
        $akunOverheadAktual = DB::table('akuns')->where('name', 'biaya_overhead_pabrik_aktual')->first();
        $overheadChildrenIds = [];
        if ($akunOverheadAktual) {
            $overheadChildrenIds = DB::table('akuns')
                ->where('perent_id', $akunOverheadAktual->id)
                ->pluck('id')
                ->map(function ($id) {
                    return (int)$id;
                })
                ->toArray();
        }

        $totalhutangoverhead = Subcashtransaction::whereIn('akun_id', $overheadChildrenIds)->whereHas('cashtransaction', function ($query) use ($request) {
            $query->where('transaction_category', 'biaya_produksi_aktual');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $start_date = date('Y-m-d', strtotime($request->start_date));
                $end_date = date('Y-m-d', strtotime($request->end_date));
                $query->whereBetween('date', [$start_date, $end_date]);
            } else {
                $query->whereBetween('date', ['1111-01-01', now()->format('Y-m-d')]);
            }
        })->sum('total');

        $akunpph22 = Akun::where('name', 'Uang_Muka_PPh_22')->first();
        $hutangoverhead = CreditCashTransaction::whereNotIn('from_id', [$akunpph22->id])->whereHas('cashtransaction', function ($q) use ($overheadChildrenIds) {
            $q->where('transaction_category', 'biaya_produksi_aktual')->whereHas('subcashtransaction', function ($sub) use ($overheadChildrenIds) {
                $sub->whereIn('akun_id', $overheadChildrenIds);
            });
        });
        $hutangoverheadpph = CreditCashTransaction::whereIn('from_id', [$akunpph22->id])->whereHas('cashtransaction', function ($q) use ($overheadChildrenIds) {
            $q->where('transaction_category', 'biaya_produksi_aktual')->whereHas('subcashtransaction', function ($sub) use ($overheadChildrenIds) {
                $sub->whereIn('akun_id', $overheadChildrenIds);
            });
        });

        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $hutangoverhead->whereBetween('date', [$start_date, $end_date]);
            $hutangoverheadpph->whereBetween('date', [$start_date, $end_date]);
        } else {
            $hutangoverhead->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            $hutangoverheadpph->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $hutangoverhead = (float) $totalhutangoverhead + (float) $hutangoverheadpph->sum('total') - (float) $hutangoverhead->sum('total');

        $productioncosts = Cashtransaction::where('transaction_category', 'biaya_produksi_dibebankan');
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $productioncosts->whereBetween('date', [$start_date, $end_date]);
        } else {
            $productioncosts->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $productioncosts = (float) $productioncosts->sum('total');

        // Pajak
        $biayapajakfinal = Cashtransaction::where('transaction_category', 'bayar_pajak_final');
        if (!empty($request->start_date) && !empty($request->end_date)) {
            $start_date = date('Y-m-d', strtotime($request->start_date));
            $end_date = date('Y-m-d', strtotime($request->end_date));
            $biayapajakfinal->whereBetween('date', [$start_date, $end_date]);
        } else {
            $biayapajakfinal->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
        }
        $biayapajakfinal = (float) $biayapajakfinal->sum('total');

        //AKUN BERNAMA ;
        $akunJasa = Akun::where('name', '=', 'Pendapatan Jasa')->first();
        $akunJasa->total = $jasa;

        $penjualan = $penjualan;
        $akunPenjualan = Akun::where('name', '=', 'Pendapatan Penjualan')->first();
        $akunPenjualan->total = $penjualan;

        $akunRetur = Akun::where('name', '=', 'Retur Penjualan')->first();
        $akunRetur->total = -abs((float) $return_in_sell);

        $akunBarang = Akun::where('name', '=', 'Pendapatan Barang')->first();
        $akunBarang->total = $barang;

        $akunBarangRugi = Akun::where('name', '=', 'Kerugian Barang Keluar Tanpa Penjualan')->first();
        $akunBarangRugi->total = $barangrugi;

        $akunPotonganBeli = Akun::where('name', '=', 'Potongan Pembelian')->first();
        $akunPotonganBeli->total = $potonganbeli;

        $hpp = $hpp - $return_in;
        $akunHpp = Akun::where('name', '=', 'Harga Pokok Penjualan')->first();
        $akunHpp->total = $hpp;

        $akunPotonganJual = Akun::where('name', '=', 'Potongan Penjualan')->first();
        $akunPotonganJual->total = $potonganjual > 0 ? -$potonganjual : 0;

        $akunPiutangJual = Akun::where('name', '=', 'Piutang Penjualan')->first();
        $akunPiutangJual->total = $piutangjual;

        $akunPiutangPph23 = Akun::where('name', '=', 'Piutang_PPh_Pasal_23')->first();
        $akunPiutangPph23->total = $piutangpph23;

        $akunpiutangpph25 = Akun::where('name', 'Piutang_PPh_Pasal_25')->first();
        $akunpiutangpph25->total = $piutangpph25 + $piutangpph25sohoout;

        $akunUangMukaPPh22 = Akun::where('name', '=', 'Uang_Muka_PPh_22')->first();
        $akunUangMukaPPh22->total = $uangmukapph22 + $piutangpph22 + $piutangpph22filter + $piutangpph22stock;

        $akunPiutangPph21 = Akun::where('name', '=', 'Piutang_PPh_21')->first();
        $akunPiutangPph21->total = $piutangpph21;

        $akunPiutangPph28 = Akun::where('name', '=', 'Piutang_PPh_28')->first();
        $akunPiutangPph28->total = $piutangpph28;

        $akunDepositCoreTax = Akun::where('name', '=', 'Deposit_Pajak_Coretax')->first();
        $akunDepositCoreTax->total = $depositcoretax;

        $akunPersediaan = Akun::where('name', '=', 'Persediaan Barang')->first();
        $akunPersediaan->total = $persediaan;

        $akunPersediaanBahanBaku = Akun::where('name', '=', 'Persediaan Bahan Baku')->first();
        $akunPersediaanBahanBaku->total = $persediaan_materials;

        $akunPersediaanProses = Akun::where('name', '=', 'Persediaan Barang Dalam Proses')->first();
        $akunPersediaanProses->total = $prosesproduksi + $productioncosts - $proses_finished;

        $akunPersediaanFinished = Akun::where('name', '=', 'Persediaan Barang Jadi')->first();
        $akunPersediaanFinished->total = $persediaan_finished;

        $akunHutangUpahProduksi = Akun::where('name', '=', 'hutang_upah_produksi_v1')->first();
        $akunHutangUpahProduksi->total = $hutangtenagakerja;

        $akunHutangOverhead = Akun::where('name', '=', 'hutang_biaya_overhead_v1')->first();
        $akunHutangOverhead->total = $hutangoverhead;

        $akunPesanBeli = Akun::where('name', '=', 'Uang Muka Pesanan Pembelian')->first();
        $akunPesanBeli->total = $uangmukabeli;

        $akunPesanJual = Akun::where('name', '=', 'Hutang Pesanan Penjualan')->first();
        $akunPesanJual->total = $pesanjual;

        $akunModalAwal = Akun::where('name', '=', 'Modal Awal')->first();
        $akunModalAwal->total = $modal_barang;

        $akunpendapatancredit = Akun::where('name', '=', 'pendapatan_yang_masih_harus_diterima')->first();
        $akunpendapatancredit->total = $totalPendapatan - $creditpendapatan;

        $akunjualasetcredit = Akun::where('name', '=', 'piutang_penjualan_aset_tetap')->first();
        $akunjualasetcredit->total = $totaljualaset - $creditjualaset;

        $akunPembelian = Akun::where('name', '=', 'Hutang Pembelian Non Tunai')->first();
        $akunPembelian->total = $hutangbeli;

        $akunbiayaharusdibayar = Akun::where('name', '=', 'Biaya yang Masih Harus Dibayar')->first();
        $akunbiayaharusdibayar->total = $biayaharusdibayar + $piutangpph22biaya;

        $akunhutangpembelianasettetap = Akun::where('name', '=', 'Hutang Pembelian Aset Tetap')->first();
        $akunhutangpembelianasettetap->total = $hutangpembelianasettetap;

        $akunutangpph23 = Akun::where('name', '=', 'Utang_PPh_23')->first();
        $akunutangpph23->total = $utangpph23;

        $akunutangpph21 = Akun::where('name', '=', 'Utang_PPh_21')->first();
        $akunutangpph21->total = $utangpph21;

        $akunutangpph22 = Akun::where('name', '=', 'Utang_PPh_22')->first();
        $akunutangpph22->total = $utangpph22;

        $akunutangpph26 = Akun::where('name', '=', 'Utang_PPh_26')->first();
        $akunutangpph26->total = $utangpph26;

        $akunutangpph4_2 = Akun::where('name', '=', 'Utang_PPh_Pasal_4_ayat_2')->first();
        $akunutangpph4_2->total = $utangpph4_2;

        $akunUtangPphFinalUMKM = Akun::where('name', '=', 'Utang_PPh_Final_UMKM')->first();
        $akunUtangPphFinalUMKM->total = $corporate_income_tax_soho;

        $akunutanpphbadan = Akun::where('name', '=', 'Utang_PPh_Badan')->first();
        $akunutanpphbadan->total = $corporate_income_tax_normal + $piutangpph28inout - (
            $piutangcashpph23normal +
            $piutangpph25 +
            $uangmukacashpph22normal +
            $piutangcashpph21normal
        );

        $akuncadanganwajib = Akun::where('name', '=', 'Cadangan Wajib')->first();
        $akuncadanganwajib->total = $cwltb + $cwldt - ($tcwltb * 2) - ($tcwldt * 2);

        $akunutangdividen = Akun::where('name', '=', 'Utang_Dividen')->first();
        $akunutangdividen->total = $utangdividenltb + $utangdividenld;

        $akunprive = Akun::where('name', '=', 'Prive')->first();
        $akunprive->total = $prive;
        //TOTAL KABEH
        $data = Akun::where('name', $request->name)->with(str_repeat('children.', 10))->get();

        function ubahNamaAkun(&$data, $mapping)
        {
            foreach ($data as &$item) {
                if (isset($mapping[$item->name])) {
                    $item->name = $mapping[$item->name];
                }

                if (!empty($item->children)) {
                    ubahNamaAkun($item->children, $mapping);
                }
            }
        }

        function tambahNamaAkun(&$data, $mapping)
        {
            foreach ($data as &$item) {
                if (isset($mapping[$item->name])) {
                    $item->rename = $mapping[$item->name];
                } else {
                    $item->rename = $item->name;
                }

                if (!empty($item->children)) {
                    tambahNamaAkun($item->children, $mapping);
                }
            }
        }

        function akunRekursif($data, $total)
        {
            foreach ($data as $key => $valuedata) {
                if (!empty($valuedata->children)) {
                    foreach ($total as $key => $valuetotal) {
                        if ($valuedata->name == $valuetotal->name) {
                            $valuedata->total = $valuedata->total + $valuetotal->total;
                        }
                    }
                    akunRekursif($valuedata->children, $total);
                } else {
                    foreach ($total as $key => $valuetotal) {
                        if ($valuedata->name == $valuetotal->name) {
                            $valuedata->total = $valuedata->total + $valuetotal->total;
                        }
                    }
                }
            }
        }

        function rekursifTotal($data)
        {
            foreach ($data as $key => $value) {
                if (!empty($value->children)) {
                    rekursifTotal($value->children);
                    foreach ($value->children as $key => $value2) {
                        $value->total += $value2->total;
                    }
                }
            }
        }

        function hapusAkun(&$data, $namesToExclude)
        {
            foreach ($data as $key => &$value) {
                if (in_array($value->name, $namesToExclude)) {
                    unset($data[$key]);
                    continue;
                }

                if (!empty($value->children)) {
                    hapusAkun($value->children, $namesToExclude);
                }
            }
        }

        function pindahAkunPerent(&$data, $targetParentNames, $childNames)
        {
            $targetParent = null;

            $findTarget = function (&$items) use (&$findTarget, $targetParentNames, &$targetParent) {
                foreach ($items as &$item) {
                    if (in_array($item->name, $targetParentNames)) {
                        $targetParent = $item;
                        return true;
                    }
                    if (!empty($item->children)) {
                        if ($findTarget($item->children)) {
                            return true;
                        }
                    }
                }
                return false;
            };

            $findTarget($data);
            if (!$targetParent) {
                return;
            }

            if (!($targetParent->children instanceof \Illuminate\Support\Collection)) {
                $targetParent->children = collect($targetParent->children ?? []);
            }

            $moveFromContainers = function (&$items) use (&$moveFromContainers, $childNames, &$targetParent) {
                if (is_array($items)) {
                    $items = collect($items);
                }
                foreach ($items as $index => $item) {
                    if (in_array($item->name, $childNames)) {
                        $already = $targetParent->children->firstWhere('name', $item->name);
                        if (!$already) {
                            $moved = $items->pull($index);
                            $targetParent->children->push($moved);
                        }
                    } else {
                        if (!empty($item->children)) {
                            $moveFromContainers($item->children);
                        }
                    }
                }
            };

            $moveFromContainers($data);
        }

        // masukin produksi
        $inputproduksi = [];
        foreach ($produksi as $key => $value) {
            array_push($inputproduksi, $value);
        }

        foreach ($produksidibebankan as $key => $value) {
            array_push($inputproduksi, $value);
        }
        $selisihtenagakerja = Akun::where('name', 'selisih_tenaga_kerja_langsung')->with(str_repeat('children.', 10))->get();
        $selisihoverhead = Akun::where('name', 'selisih_overhead_pabrik')->with(str_repeat('children.', 10))->get();
        akunRekursif($selisihtenagakerja, $inputproduksi);
        akunRekursif($selisihoverhead, $inputproduksi);
        rekursifTotal($selisihtenagakerja);
        rekursifTotal($selisihoverhead);

        // masukin
        $akun = [];
        foreach ($cash as $key => $value) {
            array_push($akun, $value);
        }

        foreach ($cashin as $key => $value) {
            array_push($akun, $value);
        }

        foreach ($cashout as $key => $value) {
            array_push($akun, $value);
        }

        foreach ($pendingCash as $key => $value) {
            array_push($akun, $value);
        }
        array_push($akun, $akunJasa);
        array_push($akun, $akunPenjualan);
        array_push($akun, $akunRetur);
        array_push($akun, $akunBarang);
        array_push($akun, $akunBarangRugi);
        array_push($akun, $akunPotonganBeli);
        array_push($akun, $akunPotonganJual);
        array_push($akun, $akunModalAwal);
        array_push($akun, $akunpendapatancredit);
        array_push($akun, $akunjualasetcredit);
        array_push($akun, $akunHpp);
        array_push($akun, $akunPiutangJual);
        array_push($akun, $akunPiutangPph23);
        array_push($akun, $akunpiutangpph25);
        array_push($akun, $akunUangMukaPPh22);
        array_push($akun, $akunPiutangPph21);
        array_push($akun, $akunPiutangPph28);
        array_push($akun, $akunDepositCoreTax);
        array_push($akun, $akunPersediaan);
        array_push($akun, $akunPersediaanBahanBaku);
        array_push($akun, $akunPersediaanProses);
        array_push($akun, $akunPersediaanFinished);
        array_push($akun, $akunHutangUpahProduksi);
        array_push($akun, $akunHutangOverhead);
        array_push($akun, $akunPesanBeli);
        array_push($akun, $akunPesanJual);
        array_push($akun, $akunPembelian);
        array_push($akun, $akunutangpph23);
        array_push($akun, $akunutangpph21);
        array_push($akun, $akunutangpph22);
        array_push($akun, $akunutangpph26);
        array_push($akun, $akunutangpph4_2);
        array_push($akun, $akunUtangPphFinalUMKM);
        array_push($akun, $akunutanpphbadan);
        array_push($akun, $akunbiayaharusdibayar);
        array_push($akun, $akunhutangpembelianasettetap);
        array_push($akun, $akuncadanganwajib);
        array_push($akun, $akunutangdividen);
        array_push($akun, $akunprive);
        $pdptn = Akun::where('name', 'Pendapatan')->with(str_repeat('children.', 10))->get();
        $hpp = Akun::where('name', 'Hpp')->with(str_repeat('children.', 10))->get();
        $biaya = Akun::where('name', 'Biaya')->with(str_repeat('children.', 10))->get();
        akunRekursif($pdptn, $akun);
        akunRekursif($hpp, $akun);
        akunRekursif($biaya, $akun);
        rekursifTotal($pdptn);
        rekursifTotal($hpp);
        rekursifTotal($biaya);

        // laba ditahan = diambil dari fungsi (labaBerjalan) yang didalamnya itu memiliki rumus dibawah ini
        // $labaDitahan = $this->labaBerjalan($request);
        $labaDitahan = $this->LabaNeraca($request);
        $LTB = Akun::where('name', '=', 'Laba Tahun Berjalan')->first();

        $biayaproduksi = ($selisihoverhead[0]->total + $btkldibebankan + $assetsproduksi) - $selisihtenagakerja[0]->total;

        $LTB->total = ($pdptn[0]->total - $hpp[0]->total - $biaya[0]->total)
            - $labaDitahan
            - $return_out_price_diff_lt
            + $return_out_price_diff_gt
            - $cwltb
            + $tcwltb
            - $tariklabaltb
            + $itemmasuk_type_produksi
            - $itemkeluar_type_produksi
            + $biayaproduksi
            - $utangdividenltb
            - $biayapph4_2
            - $corporate_income_tax
            - $biayapajakfinal;

        $LD = Akun::where('name', '=', 'Laba Ditahan')->first();
        $LD->total = $labaDitahan - $cwldt + $tcwldt - $tariklabald - $utangdividenld;

        array_push($akun, $LTB);
        array_push($akun, $LD);

        akunRekursif($data, $akun);

        pindahAkunPerent(
            $data,
            ['Persediaan'],
            ['Persediaan Barang', 'Persediaan Bahan Baku', 'Persediaan Barang Dalam Proses', 'Persediaan Barang Jadi']
        );

        rekursifTotal($data);
        tambahNamaAkun($data, []);

        if (!$isKoperasi) {
            hapusAkun($data, ['Simpanan Wajib']);
        }

        if (!$isCV && !$isFirma && !$isPerorangan) {
            hapusAkun($data, ['Prive']);
        }

        $lang = self::getActiveLanguage();
        $langCode = $lang->code ?? 'id';

        $namaMappingData = $this->loadTypeMapping($langCode);

        // Proses setiap tipe entitas dengan translasi
        if ($isKoperasi && isset($namaMappingData['koperasi'])) {
            $this->tambahNamaAkunWithTranslation($data, $namaMappingData['koperasi'], 'koperasi', $namaMappingData);
        }

        if ($isPT && isset($namaMappingData['pt'])) {
            $this->tambahNamaAkunWithTranslation($data, $namaMappingData['pt'], 'pt', $namaMappingData);
        }

        if ($isCV && isset($namaMappingData['cv'])) {
            $this->tambahNamaAkunWithTranslation($data, $namaMappingData['cv'], 'cv', $namaMappingData);
        }

        if ($isFirma && isset($namaMappingData['firma'])) {
            $this->tambahNamaAkunWithTranslation($data, $namaMappingData['firma'], 'firma', $namaMappingData);
        }

        if ($isYayasan && isset($namaMappingData['yayasan'])) {
            $this->tambahNamaAkunWithTranslation($data, $namaMappingData['yayasan'], 'yayasan', $namaMappingData);

            foreach ($data as &$akunModal) {
                // Gunakan translasi untuk nama "Modal"
                $modalTranslated = $this->translateAccountName('Modal', 'yayasan', $namaMappingData);

                if ($akunModal->name === 'Modal' || $akunModal->rename === $modalTranslated) {
                    if (!($akunModal->children instanceof Collection)) {
                        $akunModal->children = collect($akunModal->children);
                    }

                    $danaConfig = $namaMappingData['yayasan']['dana_config'] ?? null;

                    if ($danaConfig) {
                        $danaTidakTerikatConfig = $danaConfig['dana_tidak_terikat'] ?? null;
                        $danaTerikatConfig = $danaConfig['dana_terikat'] ?? null;

                        // Gunakan translasi untuk nama dana
                        $danaTidakTerikatName = $danaTidakTerikatConfig['name'] ?? 'Dana Tidak Terikat';
                        $danaTidakTerikatRename = $this->translateAccountName(
                            $danaTidakTerikatConfig['rename'] ?? $danaTidakTerikatName,
                            'yayasan',
                            $namaMappingData
                        );

                        $danaTerikatName = $danaTerikatConfig['name'] ?? 'Dana Terikat';
                        $danaTerikatRename = $this->translateAccountName(
                            $danaTerikatConfig['rename'] ?? $danaTerikatName,
                            'yayasan',
                            $namaMappingData
                        );

                        $akunToTidakTerikat = $danaTidakTerikatConfig['akun_items'] ?? ['Modal Awal', 'Laba Ditahan', 'Laba Tahun Berjalan'];

                        $danaTidakTerikat = $akunModal->children->firstWhere('name', $danaTidakTerikatName);
                        if (!$danaTidakTerikat) {
                            $danaTidakTerikat = (object)[
                                'name' => $danaTidakTerikatName,
                                'rename' => $danaTidakTerikatRename,
                                'total' => 0,
                                'children' => collect()
                            ];
                            $akunModal->children->push($danaTidakTerikat);
                        }

                        $danaTerkait = $akunModal->children->firstWhere('name', $danaTerikatName);
                        if (!$danaTerkait) {
                            $danaTerkait = (object)[
                                'name' => $danaTerikatName,
                                'rename' => $danaTerikatRename,
                                'total' => 0,
                                'children' => collect()
                            ];
                            $akunModal->children->push($danaTerkait);
                        }

                        $originalChildren = $akunModal->children->whereNotIn('name', [$danaTidakTerikatName, $danaTerikatName])->values();

                        foreach ($originalChildren as $child) {
                            $index = $akunModal->children->search(fn($c) => $c->name === $child->name);

                            if ($index !== false) {
                                $akunPindah = $akunModal->children->pull($index);

                                // Translate nama akun yang dipindahkan
                                $akunPindah->rename = $this->translateAccountName($akunPindah->name, 'yayasan', $namaMappingData);

                                if (in_array($akunPindah->name, $akunToTidakTerikat)) {
                                    $danaTidakTerikat->children->push($akunPindah);
                                } else {
                                    $danaTerkait->children->push($akunPindah);
                                }
                            }
                        }

                        rekursifTotal([$danaTidakTerikat]);
                        rekursifTotal([$danaTerkait]);
                    }

                    break;
                }
            }
        }

        if ($isBumdes && isset($namaMappingData['bumdes'])) {
            $this->tambahNamaAkunWithTranslation($data, $namaMappingData['bumdes'], 'bumdes', $namaMappingData);
        }

        if ($isPerorangan) {
            $this->tambahNamaAkunWithTranslation($data, [], 'perorangan', $namaMappingData);
        }

        if ($isLainnya) {
            $this->tambahNamaAkunWithTranslation($data, [], 'lainnya', $namaMappingData);
        }

        // Translasi untuk akun-akun yang tidak termasuk dalam mapping spesifik
        foreach ($data as &$item) {
            if (!isset($item->rename)) {
                $item->rename = $this->translateAccountName($item->name, 'general', $namaMappingData);
            }

            // Translasi recursive untuk semua children
            if (isset($item->children) && (is_array($item->children) || $item->children instanceof Collection)) {
                foreach ($item->children as &$child) {
                    if (!isset($child->rename)) {
                        $child->rename = $this->translateAccountName($child->name, 'general', $namaMappingData);
                    }
                }
            }
        }

        $response = [
            'success' => true,
            'akun' => $data,
        ];

        return response($response, 200);
    }

    // Fungsi menghitung Laba Ditahan yang Baru
    public function LabaNeraca(Request $request)
    {

        $licence = Licence::first();
        $isKoperasi = $licence && $licence->company_type === 'koperasi';
        $isPT = $licence && $licence->company_type === 'pt';
        $isCV = $licence && $licence->company_type === 'cv';
        $isFirma = $licence && $licence->company_type === 'firma';
        $isYayasan = $licence && $licence->company_type === 'yayasan';
        $isPerorangan = $licence && $licence->company_type === 'perorangan';
        $isBumdes = $licence && $licence->company_type === 'bumdes';
        $isLainnya = $licence && $licence->company_type === 'lainnya';

        // CREDIT STOCK MASUK = menghitung uang masuk dari stock
        $cash = Akun::withCount([
            'creditin as sum_stockin' => function ($credit) use ($request) {
                $credit->whereHas('stocktransaction', function ($stock) {
                    $stock->whereNotNull('cashin_id')->whereNull('pending');
                });

                if (!empty($request->end_date)) {
                    $credit = $credit->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
                } else {
                    $credit = $credit->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
                }

                $credit->select(DB::raw("SUM(total)"));
            },
            // CREDIT STOCK KELUAR = menghitung uang keluar dari stock
            'creditout as sum_stockout' => function ($credit) use ($request) {
                $credit->whereHas('stocktransaction', function ($stock) {
                    $stock->whereNotNull('cashout_id')->whereNull('pending');
                });

                if (!empty($request->end_date)) {
                    $credit = $credit->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
                } else {
                    $credit = $credit->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
                }

                $credit->select(DB::raw("SUM(total)"));
            },
            // CREDIT STOCK KELUAR = menghitung uang keluar dari stock credit
            'creditout as sum_creditcashcreditout' => function ($credit) use ($request) {
                $credit->whereHas('stocktransaction', function ($stock) {
                    $stock->whereNotNull('cashout_id')->whereNull('pending');
                });

                if (!empty($request->end_date)) {
                    $credit = $credit->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
                } else {
                    $credit = $credit->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
                }

                $credit->select(DB::raw("SUM(cash_credit)"));
            },
            // CREDIT STOCK MASUK = menghitung uang masuk dari stock credit
            'creditin as sum_creditcashcreditin' => function ($credit) use ($request) {
                $credit->whereHas('stocktransaction', function ($stock) {
                    $stock->whereNotNull('cashin_id')->whereNull('pending');
                });

                if (!empty($request->end_date)) {
                    $credit = $credit->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
                } else {
                    $credit = $credit->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
                }

                $credit->select(DB::raw("SUM(cash_credit)"));
            },
            // return_credit in
            'stocktransactioncashout as sum_returncreditcashout' => function ($credit) use ($request) {
                $credit->whereNotNull('return_credit_cash')->whereNull('pending');
                if (!empty($request->end_date)) {
                    $credit = $credit->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
                } else {
                    $credit = $credit->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
                }
                return $credit->select(DB::raw("SUM(return_credit_cash)"));
            },
            // return_credit out
            'stocktransactioncashin as sum_returncreditcashin' => function ($credit) use ($request) {
                $credit->whereNotNull('return_credit_cash')->whereNull('pending');
                if (!empty($request->end_date)) {
                    $credit = $credit->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
                } else {
                    $credit = $credit->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
                }
                return $credit->select(DB::raw("SUM(return_credit_cash)"));
            },
            // CASH FROM = menghitung cash sebagai akun
            'cashtransactionfrom as sum_cashfrom' => function ($cash) use ($request) {
                $excludedCategories = ['biaya', 'bayar_pajak_final', 'bayar_pajak_final', 'bayar_hutang_pph21', 'beli_aset', 'tarik_dividen', 'biaya_produksi_aktual', 'cicil_pph25', 'deposit_coretax', 'bayar_hutang_pph22'];

                // Ambil semua ID transaksi yang memiliki kategori 'biaya' atau 'beli_aset'
                $transactionsWithExcludedCategories = DB::table('cashtransactions')
                    ->whereIn('transaction_category', $excludedCategories)
                    ->pluck('id')
                    ->toArray();

                // Ambil ID yang benar-benar ada di credit_cashtransactions
                $validTransactionIds = DB::table('credit_cashtransactions')
                    ->whereIn('cashtransaction_id', $transactionsWithExcludedCategories)
                    ->pluck('cashtransaction_id')
                    ->toArray();

                // Jika hanya transaksi tertentu yang memiliki pasangan di credit_cashtransactions, exclude berdasarkan ID
                if (!empty($validTransactionIds)) {
                    $cash->whereNotIn('id', $validTransactionIds);
                }

                // Pengecekan tanggal
                if (!empty($request->end_date)) {
                    $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
                } else {
                    $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
                }

                // Sum dari cashout + transfer
                $cash->select(DB::raw("SUM(cashout + transfer)"));
            },
            // CASH TO = menghitung cash sebagai akun
            'cashtransactionto as sum_cashto' => function ($cash) use ($request) {
                $excludedCategories = ['simpanan_wajib', 'pendapatan', 'jual_aset'];
                $cash->whereNotIn('transaction_category', $excludedCategories);

                if (!empty($request->end_date)) {
                    $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
                } else {
                    $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
                }
                $cash->select(DB::raw("SUM(cashin+transfer)"));
            },
            // CASH TO SIMPANAN WAJIB
            'cashtransactionto as sum_simwa' => function ($cash) use ($request) {
                $cash->where('transaction_category', 'simpanan_wajib');

                if (!empty($request->end_date)) {
                    $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
                } else {
                    $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
                }
                $cash->select(DB::raw("SUM(cashin+transfer)"));
            },
            // CREDIT CASH
            'creditCashFrom as sum_creditcashfrom' => function ($credit) use ($request) {
                if (!empty($request->end_date)) {
                    $credit = $credit->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
                } else {
                    $credit = $credit->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
                }
                $credit->select(DB::raw("SUM(total)"));
            },
            // CREDIT CASH TO = menghitung credit cash sebagai akun
            'creditCashTo as sum_creditcashto' => function ($credit) use ($request) {
                if (!empty($request->end_date)) {
                    $credit = $credit->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
                } else {
                    $credit = $credit->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
                }
                $credit->select(DB::raw("SUM(total)"));
            },
        ])->where('iscash', true)->get();

        foreach ($cash as $key => $value) {
            $simwa = $isKoperasi ? $value->sum_simwa : 0;
            $value->total = ($value->sum_stockin - $value->sum_stockout) + ($value->sum_cashto - $value->sum_cashfrom) + $value->sum_returncreditcashout - $value->sum_returncreditcashin - $value->sum_creditcashcreditout + $value->sum_creditcashcreditin - $value->sum_creditcashfrom + $value->sum_creditcashto + $simwa;
        }
        $pendingCash = Akun::withCount([
            'creditin as sum_stockin' => function ($credit) use ($request) {
                $credit->whereHas('stocktransaction', function ($stock) use ($request) {
                    $stock = $stock->whereNotNull('cashin_id')->whereNotNull('pending');
                    if (!empty($request->end_date)) {
                        $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
                    } else {
                        $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
                    }
                })->select(DB::raw("SUM(total)"));
            },
            // CREDIT STOCK KELUAR = menghitung uang keluar dari stock
            'creditout as sum_stockout' => function ($credit) use ($request) {
                $credit->whereHas('stocktransaction', function ($stock) use ($request) {
                    $stock = $stock->whereNotNull('cashout_id')->whereNotNull('pending');
                    if (!empty($request->end_date)) {
                        $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
                    } else {
                        $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
                    }
                })->select(DB::raw("SUM(total)"));
            }
        ])->where('iscash', true)->get();

        foreach ($pendingCash as $key => $value) {
            $value->total = $value->sum_stockin - $value->sum_stockout;
        }
        // SUB CASH IN = menghitung cash sebagai akun
        $cashin = Akun::withCount([
            'subcashtransaction as sum_subcash' => function ($sub) use ($request) {
                $sub->select(DB::raw("SUM(total)"))->whereHas('cashtransaction', function ($cash) use ($request) {
                    $cash->whereNotNull('to')->where('transaction_category', '<>', ['refund_pesanan_pembelian', 'tarik_cadangan_wajib'])->whereNotIn('transaction_category', ['cadangan_wajib', 'utang_dividen']);
                    if (!empty($request->end_date)) {
                        $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
                    } else {
                        $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
                    }
                });
            },
            // Saldo Awal
            'subcashtransaction as sum_beginningbalance' => function ($sub) use ($request) {
                $sub->select(DB::raw("SUM(total)"))->whereHas('cashtransaction', function ($cash) use ($request) {
                    // $cash->whereNotNull('beginning_balance')->whereIn('transaction_category', ['hutang', 'saldo_awal']);
                    $cash->whereNotNull('beginning_balance')->whereIn('transaction_category', ['saldo_awal']);
                    if (!empty($request->end_date)) {
                        $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
                    } else {
                        $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
                    }
                });
            }
        ])->get();

        foreach ($cashin as $key => $value) {
            // Jika bukan koperasi dan nama adalah "Simpanan Wajib", skip item ini
            if (!$isKoperasi && $value->name === 'Simpanan Wajib') {
                continue;
            }

            $value->total = $value->sum_subcash + $value->sum_beginningbalance;
        }

        // SUB CASH OUT
        // Laba Ditahan = mengecek subcashtransaction yang akun_id nya itu 77 (laba ditahan)
        $cashout = Akun::withCount([
            'subcashtransaction as sum_subcash' => function ($sub) use ($request) {
                $sub->select(DB::raw("SUM(total)"))->whereHas('cashtransaction', function ($cash) use ($request) {
                    $cash->whereNotNull('from')->where('transaction_category', '<>', ['refund_pesanan_penjualan', 'biaya'])->whereNotIn('transaction_category', ['prive', 'tarik_laba', 'biaya_produksi_dibebankan', 'biaya_produksi_aktual', 'bayar_pajak_final']);

                    if (!empty($request->end_date)) {
                        $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
                    } else {
                        $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
                    }
                });
            },
            // Saldo Awal piutang
            'subcashtransaction as sum_beginningbalance' => function ($sub) use ($request) {
                $sub->select(DB::raw("SUM(total)"))->whereHas('cashtransaction', function ($cash) use ($request) {
                    // $cash->whereNotNull('beginning_balance')->whereIn('transaction_category', ['biaya','catat_piutang']);
                    $cash->whereNotNull('beginning_balance')->whereIn('transaction_category', ['biaya']);
                    if (!empty($request->end_date)) {
                        $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
                    } else {
                        $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
                    }
                });
            },
            // Saldo Awal biaya
            'subcashtransaction as sum_biaya' => function ($sub) use ($request) {
                $sub->select(DB::raw("SUM(total)"))->whereHas('cashtransaction', function ($cash) use ($request) {
                    $cash->whereNotNull('beginning_balance')->where('transaction_category', 'biaya');
                    if (!empty($request->end_date)) {
                        $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
                    } else {
                        $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
                    }
                });
            }
        ])->get();

        foreach ($cashout as $key => $value) {
            // $value->total = $value->sum_subcash + $value->sum_beginningbalance - $value->sum_biaya;
            $value->total = $value->sum_subcash + $value->sum_beginningbalance;
        }

        // Credit Cashtransaction
        // credit pendapatan
        $cashpendapatanIds = CreditCashTransaction::whereHas('cashtransaction', function ($query) {
            $query->where('transaction_category', 'pendapatan');
        })
            ->pluck('cashtransaction_id')
            ->unique();

        $cashPendapatanQuery = CashTransaction::whereIn('id', $cashpendapatanIds);
        if (!empty($request->end_date)) {
            $cashPendapatanQuery = $cashPendapatanQuery->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $cashPendapatanQuery = $cashPendapatanQuery->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $totalPendapatan = (float) $cashPendapatanQuery->sum('total') + ($cashPendapatanQuery->sum('pph4_2_amount_v2') * 2);

        $creditpendapatan = CreditCashTransaction::whereHas('cashtransaction', function ($query) use ($request) {
            $query->whereIn('transaction_category', ['pendapatan']);
        });
        if (!empty($request->end_date)) {
            $creditpendapatan = $creditpendapatan->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $creditpendapatan = $creditpendapatan->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $creditpendapatan = (float) $creditpendapatan->sum('total');

        // credit jual aset
        $cashjualasetIds = CreditCashTransaction::whereHas('cashtransaction', function ($query) {
            $query->where('transaction_category', 'jual_aset');
        })
            ->pluck('cashtransaction_id')
            ->unique();

        $cashjualasetQuery = CashTransaction::whereIn('id', $cashjualasetIds);
        if (!empty($request->end_date)) {
            $cashjualasetQuery = $cashjualasetQuery->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $cashjualasetQuery = $cashjualasetQuery->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $totaljualaset = (float) $cashjualasetQuery->sum('total') + ($cashjualasetQuery->sum('pph4_2_amount_v2') * 2);

        $creditjualaset = CreditCashTransaction::whereHas('cashtransaction', function ($query) use ($request) {
            $query->whereIn('transaction_category', ['jual_aset']);
        });
        if (!empty($request->end_date)) {
            $creditjualaset = $creditjualaset->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $creditjualaset = $creditjualaset->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $creditjualaset = (float) $creditjualaset->sum('total');

        // Tarik Laba
        $tariklabaltb = Cashtransaction::where('transaction_category', 'tarik_laba')
            ->whereHas('subcashtransaction', function ($query) {
                $aknltb = Akun::where('name', 'Laba Tahun Berjalan')->first();
                if ($aknltb) {
                    $query->where('akun_id', $aknltb->id);
                }
            });
        $tariklabald = Cashtransaction::where('transaction_category', 'tarik_laba')
            ->whereHas('subcashtransaction', function ($query) {
                $akunld = Akun::where('name', 'Laba Ditahan')->first();
                if ($akunld) {
                    $query->where('akun_id', $akunld->id);
                }
            });

        if (!empty($request->end_date)) {
            $tariklabaltb = $tariklabaltb->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            $tariklabald = $tariklabald->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $tariklabaltb = $tariklabaltb->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            $tariklabald = $tariklabald->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }

        $tariklabaltb = (float) $tariklabaltb->sum('cashout');
        $tariklabald = (float) $tariklabald->sum('cashout');

        // PENDAPATAN
        $jasa = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'service');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('cashin_id')->whereNull('pending')->whereNull('return');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('total');

        // penjualan
        $penjualan = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', '<>', 'service');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('cashin_id')->whereNull('pending')->whereNull('return')->whereNull('type');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('total');

        $return_in = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', '<>', 'service');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('cashout_id')->whereNull('pending')->where('return', 'in');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('total');

        $return_in_sell = Substocktransaction::whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('cashout_id')->whereNull('pending')->where('return', 'in');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->selectRaw('SUM(substocktransactions.selling_price * substocktransactions.qty) as total')->first()->total;

        $return_out = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', '<>', 'service');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('cashout_id')->whereNull('pending')->whereNull('return')->where('return', 'out');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('total');

        // PENDAPATAN barang
        $barang = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('nonmoney', 'in')->whereNull('type');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('total');

        // Kerugian barang
        $barangrugi = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('nonmoney', 'out');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('hpp');

        // Potongan beli
        $potonganbeli = Stocktransaction::whereNotNull('cashout_id')->whereNull('pending')->whereNull('return');
        if (!empty($request->end_date)) {
            $potonganbeli = $potonganbeli->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $potonganbeli = $potonganbeli->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $potonganbeli = $potonganbeli->sum('discount');

        // Potongan jual
        $potonganjual = Stocktransaction::whereNotNull('cashin_id')->whereNull('pending')->whereNull('return');
        if (!empty($request->end_date)) {
            $potonganjual = $potonganjual->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $potonganjual = $potonganjual->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $potonganjual = $potonganjual->sum('discount');

        // HPP

        $hpp = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', '<>', 'service');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
            $stock = $stock->whereNotNull('cashin_id');
        })->sum('hpp');

        // Piutang jual
        $piutangjualstock = Stocktransaction::whereNotNull('cashin_id')->whereNull('pending')->whereNull('return');
        if (!empty($request->end_date)) {
            $piutangjualstock = $piutangjualstock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $piutangjualstock = $piutangjualstock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }

        $akunPPh4_2 = Akun::where('name', 'Biaya_PPh_4_2')->first();
        $akunUtangPPh4_2 = Akun::where('name', 'Utang_PPh_Pasal_4_ayat_2')->first();
        $piutangjualcredit = Credit::whereNotNull('cashin_id')->whereNotIn('cashin_id', [$akunPPh4_2->id, $akunUtangPPh4_2->id])->wherehas('stocktransaction', function ($stock) {
            $stock->whereNotNull('cashin_id')->whereNull('pending')->whereNull('return');
        });
        if (!empty($request->end_date)) {
            $piutangjualcredit = $piutangjualcredit->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $piutangjualcredit = $piutangjualcredit->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }

        $piutangjualreturn = Stocktransaction::where('return', 'in')->whereNotNull('return_credit_cash');
        if (!empty($request->end_date)) {
            $piutangjualreturn = $piutangjualreturn->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $piutangjualreturn = $piutangjualreturn->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }

        $piutangjual = $piutangjualstock->sum('total') - $piutangjualstock->sum('discount') - $piutangjualcredit->sum('total') - $piutangjualreturn->sum('return_credit_cash');

        $akunpiutangpph23 = Akun::where('name', 'Piutang_PPh_Pasal_23')->first();
        $piutangstockpph23 = Credit::where('cashin_id', $akunpiutangpph23->id)->wherehas('stocktransaction', function ($stock) {
            $stock->whereNotNull('cashin_id')->whereNotNull('pph23_amount');
        });
        if (!empty($request->end_date)) {
            $piutangstockpph23 = $piutangstockpph23->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $piutangstockpph23 = $piutangstockpph23->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $piutangcashpph23 = CreditCashTransaction::where('to_id', $akunpiutangpph23->id)->wherehas('cashtransaction', function ($stock) {
            $stock->whereNotNull('to')->whereNotNull('pph23_amount');
        });
        $piutangcashpph23normal = CreditCashTransaction::where('from_id', $akunpiutangpph23->id)->wherehas('corporateincome', function ($stock) {
            $stock->whereNotNull('tax_amount')->whereIn('transaction_category', ['normal']);
        });
        $piutangcashpph23sohoout = CreditCashTransaction::where('from_id', $akunpiutangpph23->id)->wherehas('corporateincome', function ($stock) {
            $stock->whereNotNull('tax_amount')->whereIn('transaction_category', ['soho_out']);
        });
        if (!empty($request->end_date)) {
            $piutangcashpph23 = $piutangcashpph23->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            $piutangcashpph23normal = $piutangcashpph23normal->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            $piutangcashpph23sohoout = $piutangcashpph23sohoout->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $piutangcashpph23 = $piutangcashpph23->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            $piutangcashpph23normal = $piutangcashpph23normal->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            $piutangcashpph23sohoout = $piutangcashpph23sohoout->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $piutangcashpph23normal = $piutangcashpph23normal->sum('total');
        $piutangcashpph23sohoout = $piutangcashpph23sohoout->sum('total');
        $piutangpph23 = $piutangstockpph23->sum('total') + $piutangcashpph23->sum('total') - $piutangcashpph23normal - $piutangcashpph23sohoout;

        $akunpiutangpph25 = Akun::where('name', 'Piutang_PPh_Pasal_25')->first();
        $piutangpph25normal = CreditCashTransaction::where('from_id', $akunpiutangpph25->id)->wherehas('corporateincome', function ($stock) {
            $stock->whereNotNull('tax_amount')->whereIn('transaction_category', ['normal']);
        });
        $piutangpph25sohoout = CreditCashTransaction::where('from_id', $akunpiutangpph25->id)->wherehas('corporateincome', function ($stock) {
            $stock->whereNotNull('tax_amount')->whereIn('transaction_category', ['soho_out']);
        });
        if (!empty($request->end_date)) {
            $piutangpph25normal = $piutangpph25normal->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            $piutangpph25sohoout = $piutangpph25sohoout->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $piutangpph25normal = $piutangpph25normal->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            $piutangpph25sohoout = $piutangpph25sohoout->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $piutangpph25 = -abs((float) $piutangpph25normal->sum('total'));
        $piutangpph25sohoout = -abs((float) $piutangpph25sohoout->sum('total'));

        $akunuangmukapph22 = Akun::where('name', 'Uang_Muka_PPh_22')->first();
        $uangmukastockpph22 = Credit::where('cashin_id', $akunuangmukapph22->id)->wherehas('stocktransaction', function ($stock) {
            $stock->whereNotNull('cashin_id')->whereNotNull('pph22_amount');
        });
        if (!empty($request->end_date)) {
            $uangmukastockpph22 = $uangmukastockpph22->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $uangmukastockpph22 = $uangmukastockpph22->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $uangmukacashpph22 = CreditCashTransaction::where('to_id', $akunuangmukapph22->id)->wherehas('cashtransaction', function ($stock) {
            $stock->whereNotNull('to')->whereNotNull('pph22_amount');
        });
        $uangmukacashpph22normal = CreditCashTransaction::where('from_id', $akunuangmukapph22->id)->wherehas('corporateincome', function ($stock) {
            $stock->whereNotNull('tax_amount')->whereIn('transaction_category', ['normal']);
        });
        $uangmukacashpph22sohoout = CreditCashTransaction::where('from_id', $akunuangmukapph22->id)->wherehas('corporateincome', function ($stock) {
            $stock->whereNotNull('tax_amount')->whereIn('transaction_category', ['soho_out']);
        });
        if (!empty($request->end_date)) {
            $uangmukacashpph22 = $uangmukacashpph22->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            $uangmukacashpph22normal = $uangmukacashpph22normal->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            $uangmukacashpph22sohoout = $uangmukacashpph22sohoout->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $uangmukacashpph22 = $uangmukacashpph22->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            $uangmukacashpph22normal = $uangmukacashpph22normal->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            $uangmukacashpph22sohoout = $uangmukacashpph22sohoout->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $uangmukacashpph22normal = $uangmukacashpph22normal->sum('total');
        $uangmukacashpph22sohoout = $uangmukacashpph22sohoout->sum('total');
        $uangmukapph22 = $uangmukastockpph22->sum('total') + $uangmukacashpph22->sum('total') - $uangmukacashpph22normal - $uangmukacashpph22sohoout;

        $akunpiutangpph21 = Akun::where('name', 'Piutang_PPh_21')->first();
        $piutangstockpph21 = Credit::where('cashin_id', $akunpiutangpph21->id)->wherehas('stocktransaction', function ($stock) {
            $stock->whereNotNull('cashin_id')->whereNotNull('pph21_amount');
        });
        if (!empty($request->end_date)) {
            $piutangstockpph21 = $piutangstockpph21->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $piutangstockpph21 = $piutangstockpph21->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $piutangcashpph21 = CreditCashTransaction::where('to_id', $akunpiutangpph21->id)->wherehas('cashtransaction', function ($stock) {
            $stock->whereNotNull('to')->whereNotNull('pph21_amount');
        });
        $piutangcashpph21normal = CreditCashTransaction::where('from_id', $akunpiutangpph21->id)->wherehas('corporateincome', function ($stock) {
            $stock->whereNotNull('tax_amount')->whereIn('transaction_category', ['normal']);
        });
        $piutangcashpph21sohoout = CreditCashTransaction::where('from_id', $akunpiutangpph21->id)->wherehas('corporateincome', function ($stock) {
            $stock->whereNotNull('tax_amount')->whereIn('transaction_category', ['soho_out']);
        });
        if (!empty($request->end_date)) {
            $piutangcashpph21 = $piutangcashpph21->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            $piutangcashpph21normal = $piutangcashpph21normal->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            $piutangcashpph21sohoout = $piutangcashpph21sohoout->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $piutangcashpph21 = $piutangcashpph21->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            $piutangcashpph21normal = $piutangcashpph21normal->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            $piutangcashpph21sohoout = $piutangcashpph21sohoout->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $piutangcashpph21normal = $piutangcashpph21normal->sum('total');
        $piutangcashpph21sohoout = $piutangcashpph21sohoout->sum('total');
        $piutangpph21 = $piutangstockpph21->sum('total') + $piutangcashpph21->sum('total') - $piutangcashpph21normal - $piutangcashpph21sohoout;

        $akunpiutangpph4_2 = Akun::where('name', 'Biaya_PPh_4_2')->first();
        $biayastockpph4_2 = Credit::where('cashin_id', $akunpiutangpph4_2->id)->wherehas('stocktransaction', function ($stock) {
            $stock->whereNotNull('cashin_id')->whereNotNull('pph4_2_amount');
        });
        if (!empty($request->end_date)) {
            $biayastockpph4_2 = $biayastockpph4_2->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $biayastockpph4_2 = $biayastockpph4_2->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $biayacashpph4_2 = CreditCashTransaction::where('to_id', $akunpiutangpph4_2->id)
            ->whereHas('cashtransaction', function ($q) {
                $q->whereNotNull('to')
                    ->where(function ($pph) {
                        $pph->whereNotNull('pph4_2_amount')
                            ->orWhereNotNull('pph4_2_amount_v2');
                    });
            });
        if (!empty($request->end_date)) {
            $biayacashpph4_2 = $biayacashpph4_2->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $biayacashpph4_2 = $biayacashpph4_2->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $biayapph4_2 = $biayastockpph4_2->sum('total') + $biayacashpph4_2->sum('total');

        $akunpiutangpph28 = Akun::where('name', 'Piutang_PPh_28')->first();
        $piutangpph28in = CreditCashTransaction::where('to_id', $akunpiutangpph28->id)->wherehas('corporateincome', function ($stock) {
            $stock->whereNotNull('tax_amount')->whereIn('transaction_category', ['normal']);
        });
        $piutangpph28out = CreditCashTransaction::where('from_id', $akunpiutangpph28->id)->wherehas('corporateincome', function ($stock) {
            $stock->whereNotNull('tax_amount')->whereIn('transaction_category', ['normal']);
        });
        $piutangpph28transfer = CashTransaction::whereNotNull('transfer')->where('transaction_category', 'restitusi');
        if (!empty($request->end_date)) {
            $piutangpph28in = $piutangpph28in->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            $piutangpph28out = $piutangpph28out->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            $piutangpph28transfer = $piutangpph28transfer->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $piutangpph28in = $piutangpph28in->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            $piutangpph28out = $piutangpph28out->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            $piutangpph28transfer = $piutangpph28transfer->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $piutangpph28 = $piutangpph28in->sum('total') - $piutangpph28out->sum('total') - $piutangpph28transfer->sum('transfer');
        $piutangpph28inout = $piutangpph28in->sum('total') - $piutangpph28out->sum('total');

        $corporate_income_tax_soho = CorporateIncomeTax::where('transaction_category', 'soho');
        if (!empty($request->end_date)) {
            $corporate_income_tax_soho = $corporate_income_tax_soho->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $corporate_income_tax_soho = $corporate_income_tax_soho->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $corporate_income_tax_soho = $corporate_income_tax_soho->sum('tax_amount');

        $corporate_income_tax_normal = CorporateIncomeTax::where('transaction_category', 'normal');
        if (!empty($request->end_date)) {
            $corporate_income_tax_normal = $corporate_income_tax_normal->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $corporate_income_tax_normal = $corporate_income_tax_normal->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $corporate_income_tax_normal = $corporate_income_tax_normal->sum('tax_amount');

        $corporate_income_tax_sohoout = CorporateIncomeTax::where('transaction_category', 'soho_out');
        if (!empty($request->end_date)) {
            $corporate_income_tax_sohoout = $corporate_income_tax_sohoout->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $corporate_income_tax_sohoout = $corporate_income_tax_sohoout->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $corporate_income_tax_sohoout = $corporate_income_tax_sohoout->sum('tax_base');
        $corporate_income_tax = $corporate_income_tax_soho + $corporate_income_tax_normal + $corporate_income_tax_sohoout;


        $akundepositcoretax = Akun::where('name', 'Deposit_Pajak_Coretax')->first();
        $depositcoretaxfrom = CreditCashTransaction::where('from_id', $akundepositcoretax->id)->wherehas('cashtransaction', function ($stock) {
            $stock->whereNotNull('from');
        });
        $depositcoretaxto = CreditCashTransaction::where('to_id', $akundepositcoretax->id)->wherehas('cashtransaction', function ($stock) {
            $stock->whereNotNull('to');
        });
        if (!empty($request->end_date)) {
            $depositcoretaxfrom = $depositcoretaxfrom->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            $depositcoretaxto = $depositcoretaxto->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $depositcoretaxfrom = $depositcoretaxfrom->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            $depositcoretaxto = $depositcoretaxto->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $depositcoretax = $depositcoretaxto->sum('total') - $depositcoretaxfrom->sum('total');

        $akunutangpph23 = Akun::where('name', 'Utang_PPh_23')->first();
        $cashutangpph23 = CreditCashTransaction::where('from_id', $akunutangpph23->id)->wherehas('cashtransaction', function ($stock) {
            $stock->whereNotNull('from')->whereNotNull('pph23_amount');
        });
        $stockutangpph23 = Credit::where('cashout_id', $akunutangpph23->id)->wherehas('stocktransaction', function ($stock) {
            $stock->whereNotNull('cashout_id')->whereNotNull('pph23_amount');
        });
        if (!empty($request->end_date)) {
            $cashutangpph23 = $cashutangpph23->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            $stockutangpph23 = $stockutangpph23->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $cashutangpph23 = $cashutangpph23->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            $stockutangpph23 = $stockutangpph23->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $utangpph23 = $cashutangpph23->sum('total') + $stockutangpph23->sum('total');

        $akunutangpph21 = Akun::where('name', 'Utang_PPh_21')->first();
        $cashutangpph21 = CreditCashTransaction::where('from_id', $akunutangpph21->id)->wherehas('cashtransaction', function ($stock) {
            $stock->whereNotNull('from')->whereNotNull('pph21_amount');
        });
        $stockutangpph21 = Credit::where('cashout_id', $akunutangpph21->id)->wherehas('stocktransaction', function ($stock) {
            $stock->whereNotNull('cashout_id')->whereNotNull('pph21_amount');
        });
        if (!empty($request->end_date)) {
            $cashutangpph21 = $cashutangpph21->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            $stockutangpph21 = $stockutangpph21->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $cashutangpph21 = $cashutangpph21->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            $stockutangpph21 = $stockutangpph21->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $utangpph21 = $cashutangpph21->sum('total') + $stockutangpph21->sum('total');

        $akunutangpph4_2 = Akun::where('name', 'Utang_PPh_Pasal_4_ayat_2')->first();
        $cashutangpph4_2 = CreditCashTransaction::where('from_id', $akunutangpph4_2->id)->wherehas('cashtransaction', function ($stock) {
            $stock->whereNotNull('from')->whereNotNull('pph4_2_amount');
        });
        $cashutangpph4_2_v2 = CreditCashTransaction::where('to_id', $akunutangpph4_2->id)->wherehas('cashtransaction', function ($stock) {
            $stock->whereNotNull('to')->whereNotNull('pph4_2_amount_v2');
        });
        $stockutangpph4_2 = Credit::where('cashout_id', $akunutangpph4_2->id)->wherehas('stocktransaction', function ($stock) {
            $stock->whereNotNull('cashout_id')->whereNotNull('pph4_2_amount');
        });
        $stockutangpph4_2_v2 = Credit::where('cashin_id', $akunutangpph4_2->id)->wherehas('stocktransaction', function ($stock) {
            $stock->whereNotNull('cashin_id')->whereNotNull('pph4_2_amount_v2');
        });

        if (!empty($request->end_date)) {
            $cashutangpph4_2 = $cashutangpph4_2->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            $cashutangpph4_2_v2 = $cashutangpph4_2_v2->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            $stockutangpph4_2 = $stockutangpph4_2->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            $stockutangpph4_2_v2 = $stockutangpph4_2_v2->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $cashutangpph4_2 = $cashutangpph4_2->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            $cashutangpph4_2_v2 = $cashutangpph4_2_v2->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            $stockutangpph4_2 = $stockutangpph4_2->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            $stockutangpph4_2_v2 = $stockutangpph4_2_v2->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $utangpph4_2 = $cashutangpph4_2->sum('total') + $cashutangpph4_2_v2->sum('total') + $stockutangpph4_2->sum('total') + $stockutangpph4_2_v2->sum('total');

        $akunutangpph22 = Akun::where('name', 'Utang_PPh_22')->first();
        $cashutangpph22 = CreditCashTransaction::where('from_id', $akunutangpph22->id)->wherehas('cashtransaction', function ($stock) {
            $stock->whereNotNull('from')->whereNotNull('pph22_amount');
        });
        $stockutangpph22 = Credit::where('cashout_id', $akunutangpph22->id)->wherehas('stocktransaction', function ($stock) {
            $stock->whereNotNull('cashout_id')->whereNotNull('pph22_amount');
        });
        if (!empty($request->end_date)) {
            $cashutangpph22 = $cashutangpph22->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            $stockutangpph22 = $stockutangpph22->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $cashutangpph22 = $cashutangpph22->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            $stockutangpph22 = $stockutangpph22->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $utangpph22 = $cashutangpph22->sum('total') + $stockutangpph22->sum('total');

        $akunutangpph26 = Akun::where('name', 'Utang_PPh_26')->first();
        $cashutangpph26 = CreditCashTransaction::where('from_id', $akunutangpph26->id)->wherehas('cashtransaction', function ($stock) {
            $stock->whereNotNull('from')->whereNotNull('pph26_amount');
        });
        if (!empty($request->end_date)) {
            $cashutangpph26 = $cashutangpph26->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $cashutangpph26 = $cashutangpph26->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $utangpph26 = $cashutangpph26->sum('total');

        $akunpiutangpph22 = Akun::where('name', 'Uang_Muka_PPh_22')->first();
        $piutangpph22 = CreditCashTransaction::where('from_id', $akunpiutangpph22->id)->wherehas('cashtransaction', function ($stock) {
            $stock->whereNotNull('from')->whereNotNull('pph22_amount_v2')->whereNotIn('transaction_category', ['beli_aset']);
        });
        $piutangpph22filter = CreditCashTransaction::where('from_id', $akunpiutangpph22->id)->wherehas('cashtransaction', function ($stock) {
            $stock->whereNotNull('from')->whereNotNull('pph22_amount_v2')->whereIn('transaction_category', ['beli_aset']);
        });
        $piutangpph22biaya = CreditCashTransaction::where('from_id', $akunpiutangpph22->id)->wherehas('cashtransaction', function ($stock) {
            $stock->whereNotNull('from')->whereNotNull('pph22_amount_v2')->whereIn('transaction_category', ['biaya']);
        });
        $piutangpph22stock = Credit::where('cashout_id', $akunpiutangpph22->id)->wherehas('stocktransaction', function ($stock) {
            $stock->whereNotNull('cashout_id')->whereNotNull('pph22_amount_v2');
        });
        if (!empty($request->end_date)) {
            $piutangpph22 = $piutangpph22->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            $piutangpph22filter = $piutangpph22filter->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            $piutangpph22biaya = $piutangpph22biaya->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            $piutangpph22stock = $piutangpph22stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $piutangpph22 = $piutangpph22->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            $piutangpph22filter = $piutangpph22filter->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            $piutangpph22biaya = $piutangpph22biaya->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            $piutangpph22stock = $piutangpph22stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $piutangpph22 = $piutangpph22->sum('total');
        $piutangpph22filter = $piutangpph22filter->sum('total');
        $piutangpph22biaya = $piutangpph22biaya->sum('total');
        $piutangpph22stock = $piutangpph22stock->sum('total');

        // persedian
        $persediaanmasuk = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('cashout_id')->whereNull('pending');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('total');

        $itemmasuk = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('nonmoney', 'in');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('total');

        // saldo awal produk
        $saldoawalproduk = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('beginning_balance');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('total');

        // sum modal barang
        $modal_barang = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', '<>', 'service');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('nonmoney', 'in')->where('type', 'modal_barang');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('total');

        $persediaanhpp = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('cashin_id')->whereNull('pending')->whereNull('return');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('hpp');

        $persediaankeluar = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('nonmoney', 'out');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('hpp');
        $return_pembelian = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('return', 'out');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('total');

        // kurang dari (less than)
        $return_out_price_diff_lt = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('return', 'out');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->whereColumn('purchase_price', '<', 'original_purchase_price')->selectRaw('SUM(substocktransactions.original_purchase_price * substocktransactions.qty) - SUM(total) as total')->first()->total;

        // lebih dari (greater than)
        $return_out_price_diff_gt = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('return', 'out');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->whereColumn('purchase_price', '>', 'original_purchase_price')->selectRaw('SUM(total) - SUM(substocktransactions.original_purchase_price * substocktransactions.qty) as total')->first()->total;

        // (penjualan+item masuk)(item keluar+penjualan)
        $persediaan = ($persediaanmasuk + $itemmasuk + $return_out_price_diff_gt) - ($persediaankeluar + $persediaanhpp + $return_pembelian) - $return_out_price_diff_lt + $saldoawalproduk;

        // PERSEDIAAN BAHAN BAKU (MATERIALS PRODUCT)
        $persediaanmasuk_materials = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product_materials');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('cashout_id')->whereNull('pending');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('total');

        $itemmasuk_materials = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product_materials');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('nonmoney', 'in');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('total');

        $saldoawalproduk_materials = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product_materials');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('beginning_balance');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('total');

        $persediaanhpp_materials = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product_materials');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('cashin_id')->whereNull('pending')->whereNull('return');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('hpp');

        $persediaankeluar_materials = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product_materials');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('nonmoney', 'out');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('hpp');

        $return_pembelian_materials = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product_materials');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('return', 'out');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('total');

        $return_out_price_diff_lt_materials = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product_materials');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('return', 'out');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->whereColumn('purchase_price', '<', 'original_purchase_price')->selectRaw('SUM(substocktransactions.original_purchase_price * substocktransactions.qty) - SUM(total) as total')->first()->total;

        $return_out_price_diff_gt_materials = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product_materials');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('return', 'out');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->whereColumn('purchase_price', '>', 'original_purchase_price')->selectRaw('SUM(total) - SUM(substocktransactions.original_purchase_price * substocktransactions.qty) as total')->first()->total;

        $persediaan_materials = ($persediaanmasuk_materials + $itemmasuk_materials + $return_out_price_diff_gt_materials) - ($persediaankeluar_materials + $persediaanhpp_materials + $return_pembelian_materials) - $return_out_price_diff_lt_materials + $saldoawalproduk_materials;

        // PERSEDIAAN BARANG JADI (FINISHED PRODUCT)
        $persediaanmasuk_finished = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product_finished');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('cashout_id')->whereNull('pending');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('total');

        $itemmasuk_finished = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product_finished');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('nonmoney', 'in')->whereNull('production_id');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('total');

        $itemmasuk_type_produksi = Substocktransaction::whereHas('product', function ($product) {
            $product->whereIn('category', ['product_finished', 'product_materials']);
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('nonmoney', 'in')->whereNull('production_id')->whereNull('type');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('total');

        $saldoawalproduk_finished = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product_finished');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('beginning_balance');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('total');

        $persediaanhpp_finished = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product_finished');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('cashin_id')->whereNull('pending')->whereNull('return');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('hpp');

        $persediaankeluar_finished = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product_finished');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('nonmoney', 'out')->whereNull('production_id');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('hpp');

        $itemkeluar_type_produksi = Substocktransaction::whereHas('product', function ($product) {
            $product->whereIn('category', ['product_finished', 'product_materials']);
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('nonmoney', 'out')->whereNull('production_id');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('hpp');

        $proses_finished = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product_finished');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('nonmoney', 'in')->whereNotNull('production_id');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('total');

        $subtotal_keluar_finished = $persediaankeluar_finished + $persediaanhpp_finished;
        $persediaan_finished = ($persediaanmasuk_finished + $itemmasuk_finished + $proses_finished) - $subtotal_keluar_finished + $saldoawalproduk_finished;

        $prosesproduksi = Substocktransaction::whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('nonmoney', 'out')->whereNotNull('production_id');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('hpp');

        $pesananbeli = Stocktransaction::whereNotNull('cashout_id')->whereNotNull('pending');
        if (!empty($request->end_date)) {
            $pesananbeli = $pesananbeli->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $pesananbeli = $pesananbeli->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $pesananbeli = $pesananbeli->sum('paid');

        $akunuangmuka = Akun::where('name', '=', 'Uang Muka Pesanan Pembelian')->first();
        $belibeli = Credit::where('cashout_id', $akunuangmuka->id);
        if (!empty($request->end_date)) {
            $belibeli = $belibeli->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $belibeli = $belibeli->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $belibeli = $belibeli->sum('total');

        $kembalianbeli = Cashtransaction::where('transaction_category', 'pengembalian_uang_muka');
        if (!empty($request->end_date)) {
            $kembalianbeli = $kembalianbeli->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $kembalianbeli = $kembalianbeli->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $kembalianbeli = $kembalianbeli->sum('cashin');

        $refundbeli = Cashtransaction::where('transaction_category', 'refund_pesanan_pembelian');
        if (!empty($request->end_date)) {
            $refundbeli = $refundbeli->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $refundbeli = $refundbeli->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $refundbeli = $refundbeli->sum('cashin');

        $kekuranganbeli = Cashtransaction::where('transaction_category', 'kekurangan_pesanan_pembelian');
        if (!empty($request->end_date)) {
            $kekuranganbeli = $kekuranganbeli->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $kekuranganbeli = $kekuranganbeli->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $kekuranganbeli = $kekuranganbeli->sum('cashout');

        $uangmukabeli = $pesananbeli - $belibeli - $refundbeli - ($kembalianbeli * 2);
        // $uangmukabeli = $pesananbeli - $belibeli - $refundbeli - ($kembalianbeli * 2) + $kekuranganbeli;

        $pesananjual = Stocktransaction::whereNotNull('cashin_id')->whereNotNull('pending');
        if (!empty($request->end_date)) {
            $pesananjual = $pesananjual->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $pesananjual = $pesananjual->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $pesananjual = $pesananjual->sum('paid');

        $akunhutangpesananpenjualan = Akun::where('name', '=', 'Hutang Pesanan Penjualan')->first();
        $jualjual = Credit::where('cashin_id', $akunhutangpesananpenjualan->id);
        if (!empty($request->end_date)) {
            $jualjual = $jualjual->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $jualjual = $jualjual->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $jualjual = $jualjual->sum('total');

        $kembalianjual = Cashtransaction::where('transaction_category', 'pengembalian_hutang_pesanan_penjualan');
        if (!empty($request->end_date)) {
            $kembalianjual = $kembalianjual->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $kembalianjual = $kembalianjual->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $kembalianjual = $kembalianjual->sum('cashout');

        $refundjual = Cashtransaction::where('transaction_category', 'refund_pesanan_penjualan');
        if (!empty($request->end_date)) {
            $refundjual = $refundjual->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $refundjual = $refundjual->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $refundjual = $refundjual->sum('cashout');

        $kekuranganjual = Cashtransaction::where('transaction_category', 'kekurangan_pesanan_penjualan');
        if (!empty($request->end_date)) {
            $kekuranganjual = $kekuranganjual->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $kekuranganjual = $kekuranganjual->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $kekuranganjual = $kekuranganjual->sum('cashin');

        $pesanjual = $pesananjual - $jualjual - $refundjual - $kembalianjual;
        // $pesanjual = $pesananjual - $jualjual - $refundjual - ($kembalianjual * 2) + $kekuranganjual;

        $hutangbelistock = Stocktransaction::whereNotNull('cashout_id')->whereNull('pending')->whereNull('return');
        if (!empty($request->end_date)) {
            $hutangbelistock = $hutangbelistock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $hutangbelistock = $hutangbelistock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }

        $hutangbelicredit = Credit::whereNotNull('cashout_id');
        $hutangbelicredit->wherehas('stocktransaction', function ($stock) {
            $stock->whereNotNull('cashout_id')->whereNull('pending')->whereNull('return');
        });
        if (!empty($request->end_date)) {
            $hutangbelicredit = $hutangbelicredit->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $hutangbelicredit = $hutangbelicredit->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }

        $hutangbelireturn = Stocktransaction::where('return', 'out')->whereNotNull('return_credit_cash');
        if (!empty($request->end_date)) {
            $hutangbelireturn = $hutangbelireturn->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $hutangbelireturn = $hutangbelireturn->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }

        $hutangbeli = $hutangbelistock->sum('total') + $hutangbelistock->sum('pph22_amount_v2') - $hutangbelistock->sum('discount') - $hutangbelicredit->sum('total') - $hutangbelireturn->sum('return_credit_cash');

        // Biaya Lama
        $biayalama = Cashtransaction::where('transaction_category', 'biaya')->whereNull('total');
        if (!empty($request->end_date)) {
            $biayalama = $biayalama->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $biayalama = $biayalama->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $biayalama = (float) $biayalama->sum('cashout');


        // Biaya yang Masih Harus Dibayar
        $biayaharusdibayarcash = Cashtransaction::whereIn('transaction_category', ['biaya'])
            ->where('total', '>', 0);

        // Pengecekan tanggal
        if (!empty($request->end_date)) {
            $biayaharusdibayarcash = $biayaharusdibayarcash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $biayaharusdibayarcash = $biayaharusdibayarcash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $biayaharusdibayarcash = (float) $biayaharusdibayarcash->sum('total');

        $biayaharusdibayarcredit = CreditCashTransaction::wherehas('cashtransaction', function ($q) {
            $q->whereIn('transaction_category', ['biaya']);
        });

        // Pengecekan tanggal
        if (!empty($request->end_date)) {
            $biayaharusdibayarcredit = $biayaharusdibayarcredit->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $biayaharusdibayarcredit = $biayaharusdibayarcredit->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $biayaharusdibayarcredit = (float) $biayaharusdibayarcredit->sum('total');

        $biayaharusdibayar = $biayaharusdibayarcash - $biayaharusdibayarcredit;

        // ========================================================================

        // Pengecekan untuk kategori 'beli_aset'
        $hutangpembelianasettetapcash = Cashtransaction::where('transaction_category', 'beli_aset')
            ->where('total', '>', 0);

        // Pengecekan tanggal
        if (!empty($request->end_date)) {
            $hutangpembelianasettetapcash = $hutangpembelianasettetapcash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $hutangpembelianasettetapcash = $hutangpembelianasettetapcash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $hutangpembelianasettetapcash = $hutangpembelianasettetapcash->sum('total');

        $akunpph22 = Akun::where('name', 'Uang_Muka_PPh_22')->first();
        $hutangpembelianasettetapcredit = CreditCashTransaction::whereNotIn('from_id', [$akunpph22->id])->wherehas('cashtransaction', function ($q) {
            $q->where('transaction_category', 'beli_aset');
        });

        // Pengecekan tanggal
        if (!empty($request->end_date)) {
            $hutangpembelianasettetapcredit = $hutangpembelianasettetapcredit->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $hutangpembelianasettetapcredit = $hutangpembelianasettetapcredit->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $hutangpembelianasettetapcredit = $hutangpembelianasettetapcredit->sum('total');

        $hutangpembelianasettetap = $hutangpembelianasettetapcash - $hutangpembelianasettetapcredit;

        // Cadangan Wajib Laba Tahun Berjalan
        $aknltb = Akun::where('name', 'Laba Tahun Berjalan')->first();

        $cwltb = Cashtransaction::where('transaction_category', 'cadangan_wajib')
            ->whereHas('subcashtransaction', function ($query) use ($aknltb) {
                if ($aknltb) {
                    $query->where('akun_id', $aknltb->id);
                }
            });

        if (!empty($request->end_date)) {
            $cwltb = $cwltb->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $cwltb = $cwltb->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }

        $cwltb = (float) $cwltb->sum('total');

        // Cadangan Wajib Laba Ditahan
        $aknltb = Akun::where('name', 'Laba Ditahan')->first();

        $cwldt = Cashtransaction::where('transaction_category', 'cadangan_wajib')
            ->whereHas('subcashtransaction', function ($query) use ($aknltb) {
                if ($aknltb) {
                    $query->where('akun_id', $aknltb->id);
                }
            });

        if (!empty($request->end_date)) {
            $cwldt = $cwldt->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $cwldt = $cwldt->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }

        $cwldt = (float) $cwldt->sum('total');

        // Tarik Cadangan Wajib Laba Tahun Berjalan
        $aknltb = Akun::where('name', 'Laba Tahun Berjalan')->first();

        $tcwltb = Cashtransaction::where('transaction_category', 'tarik_cadangan_wajib')
            ->where('to', $aknltb->id);

        if (!empty($request->end_date)) {
            $tcwltb = $tcwltb->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $tcwltb = $tcwltb->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }

        $tcwltb = (float) $tcwltb->sum('total');

        // Tarik Cadangan Wajib Laba Ditahan
        $aknltb = Akun::where('name', 'Laba Ditahan')->first();

        $tcwldt = Cashtransaction::where('transaction_category', 'tarik_cadangan_wajib')
            ->where('to', $aknltb->id);

        if (!empty($request->end_date)) {
            $tcwldt = $tcwldt->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $tcwldt = $tcwldt->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }

        $tcwldt = (float) $tcwldt->sum('total');

        // Utang Dividen
        $utangdividenltb = Cashtransaction::where('transaction_category', 'utang_dividen')
            ->whereHas('subcashtransaction', function ($query) use ($aknltb) {
                $aknltb = Akun::where('name', 'Laba Tahun Berjalan')->first();
                if ($aknltb) {
                    $query->where('akun_id', $aknltb->id);
                }
            });
        $utangdividenld = Cashtransaction::where('transaction_category', 'utang_dividen')
            ->whereHas('subcashtransaction', function ($query) use ($aknltb) {
                $akunld = Akun::where('name', 'Laba Ditahan')->first();
                if ($akunld) {
                    $query->where('akun_id', $akunld->id);
                }
            });

        if (!empty($request->end_date)) {
            $utangdividenltb->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            $utangdividenld->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $utangdividenltb->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            $utangdividenld->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }

        $utangdividenltb = (float) $utangdividenltb->sum('total');
        $utangdividenld = (float) $utangdividenld->sum('total');

        // Prive
        $prive = Subcashtransaction::whereHas('cashtransaction', function ($query) use ($request) {
            $query->where('transaction_category', 'prive');
            if (!empty($request->end_date)) {
                $query->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $query->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        });
        $prive = ($isCV || $isFirma || $isPerorangan) ? $prive->sum('total') : 0;

        // Produksi
        $produksi = Akun::withCount([
            'subcashtransaction as sum_subcash' => function ($sub) use ($request) {
                $akunSelisihTenagaKerja = DB::table('akuns')->where('name', 'selisih_tenaga_kerja_langsung')->first();
                $akunOverheadDibebankan = DB::table('akuns')->where('name', 'biaya_overhead_pabrik_dibebankan')->first();
                $excludeIds = [];
                if ($akunSelisihTenagaKerja) {
                    $childrenIds = DB::table('akuns')
                        ->where('perent_id', $akunSelisihTenagaKerja->id)
                        ->pluck('id')
                        ->map(function ($id) {
                            return (int)$id;
                        })
                        ->toArray();
                    $excludeIds = array_merge($excludeIds, $childrenIds);
                }
                if ($akunOverheadDibebankan) {
                    $childrenIds = DB::table('akuns')
                        ->where('perent_id', $akunOverheadDibebankan->id)
                        ->pluck('id')
                        ->map(function ($id) {
                            return (int)$id;
                        })
                        ->toArray();
                    $excludeIds = array_merge($excludeIds, $childrenIds);
                }
                if (!empty($excludeIds)) {
                    $sub->whereNotIn('akun_id', $excludeIds);
                }
                $sub->select(DB::raw("SUM(total)"))->whereHas('cashtransaction', function ($cash) use ($request) {
                    $cash->where('transaction_category', 'biaya_produksi_aktual');
                    if (!empty($request->end_date)) {
                        $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
                    } else {
                        $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
                    }
                });
            },
            'subcashtransaction as sum_subtenaga' => function ($sub) use ($request) {
                $akunbtkldibebankan = Akun::where('name', 'biaya_tenaga_kerja_langsung_aktual')->first();
                $sub->select(DB::raw("SUM(total)"))->where('akun_id', $akunbtkldibebankan->id)->whereHas('cashtransaction', function ($cash) use ($request) {
                    $cash->where('transaction_category', 'biaya_produksi_aktual');
                    if (!empty($request->end_date)) {
                        $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
                    } else {
                        $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
                    }
                });
            }
        ])->get();

        foreach ($produksi as $key => $value) {
            $value->total = -abs($value->sum_subcash) + $value->sum_subtenaga;
        }

        // Biaya Produksi Dibebankan
        $produksidibebankan = Akun::withCount(['subcashtransaction as sum_subcash' => function ($sub) use ($request) {
            $akunOverheadDibebankan = DB::table('akuns')->where('name', 'biaya_overhead_pabrik_dibebankan')->first();
            if ($akunOverheadDibebankan) {
                $childrenIds = DB::table('akuns')
                    ->where('perent_id', $akunOverheadDibebankan->id)
                    ->pluck('id')
                    ->map(function ($id) {
                        return (int)$id;
                    })
                    ->toArray();
                if (!empty($childrenIds)) {
                    $sub->whereIn('akun_id', $childrenIds);
                }
            }
            $sub->select(DB::raw("SUM(total)"))->whereHas('cashtransaction', function ($cash) use ($request) {
                $cash->where('transaction_category', 'biaya_produksi_dibebankan');
                if (!empty($request->end_date)) {
                    $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
                } else {
                    $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
                }
            });
        }])->get();

        foreach ($produksidibebankan as $key => $value) {
            $value->total = $value->sum_subcash;
        }

        $akunbtkldibebankan = Akun::where('name', 'biaya_tenaga_kerja_langsung_dibebankan')->first();
        $btkldibebankan = Subcashtransaction::where('akun_id', $akunbtkldibebankan->id)
            ->whereHas('cashtransaction', function ($query) use ($request) {
                $query->where('transaction_category', 'biaya_produksi_dibebankan');
                if (!empty($request->end_date)) {
                    $query->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
                } else {
                    $query->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
                }
            })->sum('total');

        $assets = Akun::where('is_productionasset', true)->pluck('id')->toArray();
        $assetsproduksi = Subcashtransaction::whereHas('cashtransaction', function ($query) use ($request) {
            $query->where('transaction_category', 'biaya_produksi_dibebankan');
            if (!empty($request->end_date)) {
                $query->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $query->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->whereIn('akun_id', $assets)->sum('total');

        // Hutang tenaga kerja produksi
        $akunbtklaktual = Akun::where('name', 'biaya_tenaga_kerja_langsung_aktual')->first();
        $totalhutangtenagakerja = Subcashtransaction::where('akun_id', $akunbtklaktual->id)->whereHas('cashtransaction', function ($query) use ($request) {
            $query->where('transaction_category', 'biaya_produksi_aktual');
            if (!empty($request->end_date)) {
                $query->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $query->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('total');

        $hutangtenagakerja = CreditCashTransaction::whereHas('cashtransaction', function ($q) {
            $q->where('transaction_category', 'biaya_produksi_aktual')->whereHas('subcashtransaction', function ($sub) {
                $akunbtklaktual = Akun::where('name', 'biaya_tenaga_kerja_langsung_aktual')->first();
                $sub->where('akun_id', $akunbtklaktual->id);
            });
        });

        // Pengecekan tanggal
        if (!empty($request->end_date)) {
            $hutangtenagakerja = $hutangtenagakerja->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $hutangtenagakerja = $hutangtenagakerja->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $hutangtenagakerja = (float) $totalhutangtenagakerja - (float) $hutangtenagakerja->sum('total');

        // Hutang Overhead produksi
        $akunOverheadAktual = DB::table('akuns')->where('name', 'biaya_overhead_pabrik_aktual')->first();
        $overheadChildrenIds = [];
        if ($akunOverheadAktual) {
            $overheadChildrenIds = DB::table('akuns')
                ->where('perent_id', $akunOverheadAktual->id)
                ->pluck('id')
                ->map(function ($id) {
                    return (int)$id;
                })
                ->toArray();
        }

        $totalhutangoverhead = Subcashtransaction::whereIn('akun_id', $overheadChildrenIds)->whereHas('cashtransaction', function ($query) use ($request) {
            $query->where('transaction_category', 'biaya_produksi_aktual');
            if (!empty($request->end_date)) {
                $query->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $query->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('total');

        $akunpph22 = Akun::where('name', 'Uang_Muka_PPh_22')->first();
        $hutangoverhead = CreditCashTransaction::whereNotIn('from_id', [$akunpph22->id])->whereHas('cashtransaction', function ($q) use ($overheadChildrenIds) {
            $q->where('transaction_category', 'biaya_produksi_aktual')->whereHas('subcashtransaction', function ($sub) use ($overheadChildrenIds) {
                $sub->whereIn('akun_id', $overheadChildrenIds);
            });
        });
        $hutangoverheadpph = CreditCashTransaction::whereIn('from_id', [$akunpph22->id])->whereHas('cashtransaction', function ($q) use ($overheadChildrenIds) {
            $q->where('transaction_category', 'biaya_produksi_aktual')->whereHas('subcashtransaction', function ($sub) use ($overheadChildrenIds) {
                $sub->whereIn('akun_id', $overheadChildrenIds);
            });
        });

        if (!empty($request->end_date)) {
            $hutangoverhead->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            $hutangoverheadpph->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $hutangoverhead->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            $hutangoverheadpph->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $hutangoverhead = (float) $totalhutangoverhead + (float) $hutangoverheadpph->sum('total') - (float) $hutangoverhead->sum('total');

        $productioncosts = Cashtransaction::where('transaction_category', 'biaya_produksi_dibebankan');
        if (!empty($request->end_date)) {
            $productioncosts = $productioncosts->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $productioncosts = $productioncosts->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $productioncosts = (float) $productioncosts->sum('total');

        // Pajak
        $biayapajakfinal = Cashtransaction::where('transaction_category', 'bayar_pajak_final');
        if (!empty($request->end_date)) {
            $biayapajakfinal = $biayapajakfinal->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $biayapajakfinal = $biayapajakfinal->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $biayapajakfinal = (float) $biayapajakfinal->sum('total');

        //AKUN BERNAMA ;
        $akunJasa = Akun::where('name', '=', 'Pendapatan Jasa')->first();
        $akunJasa->total = $jasa;

        $penjualan = $penjualan;
        $akunPenjualan = Akun::where('name', '=', 'Pendapatan Penjualan')->first();
        $akunPenjualan->total = $penjualan;

        $akunRetur = Akun::where('name', '=', 'Retur Penjualan')->first();
        $akunRetur->total = -abs((float) $return_in_sell);

        $akunBarang = Akun::where('name', '=', 'Pendapatan Barang')->first();
        $akunBarang->total = $barang;

        $akunBarangRugi = Akun::where('name', '=', 'Kerugian Barang Keluar Tanpa Penjualan')->first();
        $akunBarangRugi->total = $barangrugi;

        $akunPotonganBeli = Akun::where('name', '=', 'Potongan Pembelian')->first();
        $akunPotonganBeli->total = $potonganbeli;

        $hpp = $hpp - $return_in;
        $akunHpp = Akun::where('name', '=', 'Harga Pokok Penjualan')->first();
        $akunHpp->total = $hpp;

        $akunPotonganJual = Akun::where('name', '=', 'Potongan Penjualan')->first();
        $akunPotonganJual->total = $potonganjual > 0 ? -$potonganjual : 0;

        $akunPiutangJual = Akun::where('name', '=', 'Piutang Penjualan')->first();
        $akunPiutangJual->total = $piutangjual;

        $akunPiutangPph23 = Akun::where('name', '=', 'Piutang_PPh_Pasal_23')->first();
        $akunPiutangPph23->total = $piutangpph23;

        $akunpiutangpph25 = Akun::where('name', 'Piutang_PPh_Pasal_25')->first();
        $akunpiutangpph25->total = $piutangpph25 + $piutangpph25sohoout;

        $akunUangMukaPPh22 = Akun::where('name', '=', 'Uang_Muka_PPh_22')->first();
        $akunUangMukaPPh22->total = $uangmukapph22 + $piutangpph22 + $piutangpph22filter + $piutangpph22stock;

        $akunPiutangPph21 = Akun::where('name', '=', 'Piutang_PPh_21')->first();
        $akunPiutangPph21->total = $piutangpph21;

        $akunPiutangPph28 = Akun::where('name', '=', 'Piutang_PPh_28')->first();
        $akunPiutangPph28->total = $piutangpph28;

        $akunDepositCoreTax = Akun::where('name', '=', 'Deposit_Pajak_Coretax')->first();
        $akunDepositCoreTax->total = $depositcoretax;

        $akunPersediaan = Akun::where('name', '=', 'Persediaan Barang')->first();
        $akunPersediaan->total = $persediaan;

        $akunPersediaanBahanBaku = Akun::where('name', '=', 'Persediaan Bahan Baku')->first();
        $akunPersediaanBahanBaku->total = $persediaan_materials;

        $akunPersediaanProses = Akun::where('name', '=', 'Persediaan Barang Dalam Proses')->first();
        $akunPersediaanProses->total = $prosesproduksi + $productioncosts - $proses_finished;

        $akunPersediaanFinished = Akun::where('name', '=', 'Persediaan Barang Jadi')->first();
        $akunPersediaanFinished->total = $persediaan_finished;

        $akunHutangUpahProduksi = Akun::where('name', '=', 'hutang_upah_produksi_v1')->first();
        $akunHutangUpahProduksi->total = $hutangtenagakerja;

        $akunHutangOverhead = Akun::where('name', '=', 'hutang_biaya_overhead_v1')->first();
        $akunHutangOverhead->total = $hutangoverhead;

        $akunPesanBeli = Akun::where('name', '=', 'Uang Muka Pesanan Pembelian')->first();
        $akunPesanBeli->total = $uangmukabeli;

        $akunPesanJual = Akun::where('name', '=', 'Hutang Pesanan Penjualan')->first();
        $akunPesanJual->total = $pesanjual;

        $akunModalAwal = Akun::where('name', '=', 'Modal Awal')->first();
        $akunModalAwal->total = $modal_barang;

        $akunpendapatancredit = Akun::where('name', '=', 'pendapatan_yang_masih_harus_diterima')->first();
        $akunpendapatancredit->total = $totalPendapatan - $creditpendapatan;

        $akunjualasetcredit = Akun::where('name', '=', 'piutang_penjualan_aset_tetap')->first();
        $akunjualasetcredit->total = $totaljualaset - $creditjualaset;

        $akunPembelian = Akun::where('name', '=', 'Hutang Pembelian Non Tunai')->first();
        $akunPembelian->total = $hutangbeli;

        $akunbiayaharusdibayar = Akun::where('name', '=', 'Biaya yang Masih Harus Dibayar')->first();
        $akunbiayaharusdibayar->total = $biayaharusdibayar + $piutangpph22biaya;

        $akunhutangpembelianasettetap = Akun::where('name', '=', 'Hutang Pembelian Aset Tetap')->first();
        $akunhutangpembelianasettetap->total = $hutangpembelianasettetap;

        $akunutangpph23 = Akun::where('name', '=', 'Utang_PPh_23')->first();
        $akunutangpph23->total = $utangpph23;

        $akunutangpph21 = Akun::where('name', '=', 'Utang_PPh_21')->first();
        $akunutangpph21->total = $utangpph21;

        $akunutangpph22 = Akun::where('name', '=', 'Utang_PPh_22')->first();
        $akunutangpph22->total = $utangpph22;

        $akunutangpph26 = Akun::where('name', '=', 'Utang_PPh_26')->first();
        $akunutangpph26->total = $utangpph26;

        $akunutangpph4_2 = Akun::where('name', '=', 'Utang_PPh_Pasal_4_ayat_2')->first();
        $akunutangpph4_2->total = $utangpph4_2 + $corporate_income_tax_soho;

        $akunUtangPphFinalUMKM = Akun::where('name', '=', 'Utang_PPh_Final_UMKM')->first();
        $akunUtangPphFinalUMKM->total = $corporate_income_tax_soho;

        $akunutanpphbadan = Akun::where('name', '=', 'Utang_PPh_Badan')->first();
        $akunutanpphbadan->total = $corporate_income_tax_normal + $piutangpph28inout - (
            $piutangcashpph23normal +
            $piutangpph25 +
            $uangmukacashpph22normal +
            $piutangcashpph21normal
        );

        $akuncadanganwajib = Akun::where('name', '=', 'Cadangan Wajib')->first();
        $akuncadanganwajib->total = $cwltb + $cwldt - ($tcwltb * 2) - ($tcwldt * 2);

        $akunutangdividen = Akun::where('name', '=', 'Utang_Dividen')->first();
        $akunutangdividen->total = $utangdividenltb + $utangdividenld;

        $akunprive = Akun::where('name', '=', 'Prive')->first();
        $akunprive->total = $prive;
        //TOTAL KABEH
        $data = Akun::where('name', $request->name)->with(str_repeat('children.', 10))->get();

        function akunRekursif2($data, $total)
        {
            foreach ($data as $key => $valuedata) {
                if (!empty($valuedata->children)) {
                    foreach ($total as $key => $valuetotal) {
                        if ($valuedata->name == $valuetotal->name) {
                            $valuedata->total = $valuedata->total + $valuetotal->total;
                        }
                    }
                    akunRekursif2($valuedata->children, $total);
                } else {
                    foreach ($total as $key => $valuetotal) {
                        if ($valuedata->name == $valuetotal->name) {
                            $valuedata->total = $valuedata->total + $valuetotal->total;
                        }
                    }
                }
            }
        }

        function rekursifTotal2($data)
        {
            foreach ($data as $key => $value) {
                if (!empty($value->children)) {
                    rekursifTotal2($value->children);
                    foreach ($value->children as $key => $value2) {
                        $value->total += $value2->total;
                    }
                }
            }
        }

        // masukin produksi
        $inputproduksi = [];
        foreach ($produksi as $key => $value) {
            array_push($inputproduksi, $value);
        }

        foreach ($produksidibebankan as $key => $value) {
            array_push($inputproduksi, $value);
        }
        $selisihtenagakerja = Akun::where('name', 'selisih_tenaga_kerja_langsung')->with(str_repeat('children.', 10))->get();
        $selisihoverhead = Akun::where('name', 'selisih_overhead_pabrik')->with(str_repeat('children.', 10))->get();
        akunRekursif($selisihtenagakerja, $inputproduksi);
        akunRekursif($selisihoverhead, $inputproduksi);
        rekursifTotal($selisihtenagakerja);
        rekursifTotal($selisihoverhead);

        // masukin
        $akun = [];
        foreach ($cash as $key => $value) {
            array_push($akun, $value);
        }

        foreach ($cashin as $key => $value) {
            array_push($akun, $value);
        }

        foreach ($cashout as $key => $value) {
            array_push($akun, $value);
        }

        foreach ($pendingCash as $key => $value) {
            array_push($akun, $value);
        }
        array_push($akun, $akunJasa);
        array_push($akun, $akunPenjualan);
        array_push($akun, $akunRetur);
        array_push($akun, $akunBarang);
        array_push($akun, $akunBarangRugi);
        array_push($akun, $akunPotonganBeli);
        array_push($akun, $akunPotonganJual);
        array_push($akun, $akunModalAwal);
        array_push($akun, $akunpendapatancredit);
        array_push($akun, $akunjualasetcredit);
        array_push($akun, $akunHpp);
        array_push($akun, $akunPiutangJual);
        array_push($akun, $akunPiutangPph23);
        array_push($akun, $akunpiutangpph25);
        array_push($akun, $akunUangMukaPPh22);
        array_push($akun, $akunPiutangPph21);
        array_push($akun, $akunPiutangPph28);
        array_push($akun, $akunDepositCoreTax);
        array_push($akun, $akunPersediaan);
        array_push($akun, $akunPersediaanBahanBaku);
        array_push($akun, $akunPersediaanProses);
        array_push($akun, $akunPersediaanFinished);
        array_push($akun, $akunHutangUpahProduksi);
        array_push($akun, $akunHutangOverhead);
        array_push($akun, $akunPesanBeli);
        array_push($akun, $akunPesanJual);
        array_push($akun, $akunPembelian);
        array_push($akun, $akunutangpph23);
        array_push($akun, $akunutangpph21);
        array_push($akun, $akunutangpph22);
        array_push($akun, $akunutangpph26);
        array_push($akun, $akunutangpph4_2);
        array_push($akun, $akunUtangPphFinalUMKM);
        array_push($akun, $akunutanpphbadan);
        array_push($akun, $akunbiayaharusdibayar);
        array_push($akun, $akunhutangpembelianasettetap);
        array_push($akun, $akuncadanganwajib);
        array_push($akun, $akunutangdividen);
        array_push($akun, $akunprive);
        $pdptn = Akun::where('name', 'Pendapatan')->with(str_repeat('children.', 10))->get();
        $hpp = Akun::where('name', 'Hpp')->with(str_repeat('children.', 10))->get();
        $biaya = Akun::where('name', 'Biaya')->with(str_repeat('children.', 10))->get();
        akunRekursif2($pdptn, $akun);
        akunRekursif2($hpp, $akun);
        akunRekursif2($biaya, $akun);
        rekursifTotal2($pdptn);
        rekursifTotal2($hpp);
        rekursifTotal2($biaya);

        $LTB = Akun::where('name', '=', 'Laba Tahun Berjalan')->first();

        $biayaproduksi = ($selisihoverhead[0]->total + $btkldibebankan + $assetsproduksi) - $selisihtenagakerja[0]->total;

        $LTB->total = ($pdptn[0]->total - $hpp[0]->total - $biaya[0]->total)
            - $return_out_price_diff_lt
            + $return_out_price_diff_gt
            - $cwltb
            + $tcwltb
            - $tariklabaltb
            + $itemmasuk_type_produksi
            - $itemkeluar_type_produksi
            + $biayaproduksi
            - $utangdividenltb
            - $biayapph4_2
            - $corporate_income_tax
            - $biayapajakfinal;

        $LD = Akun::where('name', '=', 'Laba Ditahan')->first();
        $LD->total = $cwldt + $tcwldt - $tariklabald - $utangdividenld;

        array_push($akun, $LTB);
        array_push($akun, $LD);

        akunRekursif2($data, $akun);

        return ($LTB->total);
    }

    // Fungsi menghitung Laba Ditahan yang Lama
    public function labaBerjalan($request)
    {
        // CREDIT STOCK MASUK = menghitung uang masuk dari stock
        $cash = Akun::withCount([
            'creditin as sum_stockin' => function ($credit) use ($request) {
                $credit->whereHas('stocktransaction', function ($stock) use ($request) {
                    $stock = $stock->whereNotNull('cashin_id')->whereNull('pending');
                    if (!empty($request->end_date)) {

                        $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
                    } else {
                        $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
                    }
                })->select(DB::raw("SUM(total)"));
            },
            // CREDIT STOCK KELUAR = menghitung uang keluar dari stock
            'creditout as sum_stockout' => function ($credit) use ($request) {
                $credit->whereHas('stocktransaction', function ($stock) use ($request) {
                    $stock = $stock->whereNotNull('cashout_id')->whereNull('pending');
                    if (!empty($request->end_date)) {
                        $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
                    } else {
                        $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
                    }
                })->select(DB::raw("SUM(total)"));
            },
            // CASH FROM = menghitung cash sebagai akun
            'cashtransactionfrom as sum_cashfrom' => function ($cash) use ($request) {
                if (!empty($request->end_date)) {
                    $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
                } else {
                    $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
                }
                $cash->select(DB::raw("SUM(cashout+transfer)"));
            },
            // CASH TO = menghitung cash sebagai akun
            'cashtransactionto as sum_cashto' => function ($cash) use ($request) {
                if (!empty($request->end_date)) {
                    $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
                } else {
                    $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
                }
                $cash->select(DB::raw("SUM(cashin+transfer)"));
            }
        ])->where('iscash', true)->get();

        foreach ($cash as $key => $value) {
            $value->total = ($value->sum_stockin - $value->sum_stockout) + ($value->sum_cashto - $value->sum_cashfrom);
        }

        $pendingCash = Akun::withCount([
            'creditin as sum_stockin' => function ($credit) use ($request) {
                $credit->whereHas('stocktransaction', function ($stock) use ($request) {
                    $stock = $stock->whereNotNull('cashin_id')->where('pending', 1);
                    if (!empty($request->start_date) && !empty($request->end_date)) {
                        $request->start_date = date('Y-m-d', strtotime($request->start_date));
                        $request->end_date = date('Y-m-d', strtotime($request->end_date));
                        $stock = $stock->whereBetween('date', [date('1111-01-01', time()), $request->end_date]);
                    } else {
                        $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
                    }
                })->select(DB::raw("SUM(total)"));
            },
            // CREDIT STOCK KELUAR = menghitung uang keluar dari stock
            'creditout as sum_stockout' => function ($credit) use ($request) {
                $credit->whereHas('stocktransaction', function ($stock) use ($request) {
                    $stock = $stock->whereNotNull('cashout_id')->where('pending', 1);
                    if (!empty($request->start_date) && !empty($request->end_date)) {
                        $request->start_date = date('Y-m-d', strtotime($request->start_date));
                        $request->end_date = date('Y-m-d', strtotime($request->end_date));
                        $stock = $stock->whereBetween('date', [date('1111-01-01', time()), $request->end_date]);
                    } else {
                        $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
                    }
                })->select(DB::raw("SUM(total)"));
            }
        ])->where('iscash', true)->get();

        foreach ($pendingCash as $key => $value) {
            $value->total = ($value->sum_stockin - $value->sum_stockout);
        }
        // SUB CASH IN = menghitung cash sebagai akun
        $cashin = Akun::withCount(['subcashtransaction as sum_subcash' => function ($sub) use ($request) {
            $sub->select(DB::raw("SUM(total)"))->whereHas('cashtransaction', function ($cash) use ($request) {
                $cash->whereNotNull('to');
                if (!empty($request->end_date)) {
                    $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
                } else {
                    $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
                }
            });
        }])->get();

        foreach ($cashin as $key => $value) {
            $value->total = $value->sum_subcash;
        }
        // SUB CASH OUT
        $cashout = Akun::withCount(['subcashtransaction as sum_subcash' => function ($sub) use ($request) {
            $sub->select(DB::raw("SUM(total)"))->whereHas('cashtransaction', function ($cash) use ($request) {
                $cash->whereNotNull('from');
                if (!empty($request->end_date)) {
                    $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
                } else {
                    $cash = $cash->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
                }
            });
        }])->get();

        foreach ($cashout as $key => $value) {
            $value->total = $value->sum_subcash;
        }

        // Tarik Laba
        $tarik_laba = Cashtransaction::where('transaction_category', 'tarik_laba');
        if (!empty($request->end_date)) { // PENDAPATAN
            $tarik_laba = $tarik_laba->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $tarik_laba = $tarik_laba->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $tarik_laba = $tarik_laba->sum('cashout');


        $jasa = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'service');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('cashin_id')->whereNull('pending')->whereNull('return');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('total');
        // penjualan 
        $penjualan = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', '<>', 'service');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('cashin_id')->whereNull('pending')->whereNull('return')->whereNull('type');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('total');
        $return_in = Substocktransaction::whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('cashout_id')->whereNull('pending')->where('return', 'in');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $request->start_date = date('Y-m-d', strtotime($request->start_date));
                $request->end_date = date('Y-m-d', strtotime($request->end_date));
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), $request->end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->sum('total');

        $return_out = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', '<>', 'service');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('cashout_id')->whereNull('pending')->whereNull('return')->where('return', 'out');
            if (!empty($request->start_date) && !empty($request->end_date)) {
                $request->start_date = date('Y-m-d', strtotime($request->start_date));
                $request->end_date = date('Y-m-d', strtotime($request->end_date));
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), $request->end_date]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-m-d', time())]);
            }
        })->sum('total');
        // PENDAPATAN barang
        $barang = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('nonmoney', 'in')->whereNull('type');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('total');

        // Kerugian barang
        $barangrugi = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', 'product');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->where('nonmoney', 'out');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('hpp');

        // Potongan beli
        $potonganbeli = Stocktransaction::whereNotNull('cashout_id');
        if (!empty($request->end_date)) {
            $potonganbeli = $potonganbeli->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $potonganbeli = $potonganbeli->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $potonganbeli = $potonganbeli->sum('discount');

        // Potongan jual

        $potonganjual = Stocktransaction::whereNotNull('cashin_id')->whereNull('pending')->whereNull('return');
        if (!empty($request->end_date)) {
            $potonganjual = $potonganjual->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $potonganjual = $potonganjual->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $potonganjual = $potonganjual->sum('discount');

        // HPP

        $hpp = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', '<>', 'service');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('cashin_id');
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('hpp');

        // Piutang jual

        $piutangjual = Stocktransaction::whereNotNull('cashin_id')->whereNull('pending')->whereNull('return');
        if (!empty($request->end_date)) {
            $piutangjual = $piutangjual->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $piutangjual = $piutangjual->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $piutangjual = $piutangjual->sum('total') - $piutangjual->sum('discount') - $piutangjual->sum('paid');

        // persedian

        $persediaanmasuk = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', '<>', 'service');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
            $stock = $stock->whereNotNull('cashout_id')->orWhere('nonmoney', 'in')->whereNull('pending');
        })->sum('total');

        $persediaanhpp = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', '<>', 'service');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            $stock = $stock->whereNotNull('cashin_id')->whereNull('pending')->whereNull('return');
            if (!empty($request->end_date)) {

                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
        })->sum('hpp');

        $persediaankeluar = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', '<>', 'service');
        })->whereHas('stocktransaction', function ($stock) use ($request) {
            if (!empty($request->end_date)) {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
            } else {
                $stock = $stock->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
            }
            $stock = $stock->where('nonmoney', 'out');
        })->sum('hpp');

        $persediaan = $persediaanmasuk - ($persediaankeluar + $persediaanhpp);

        $uangmukabeli = Stocktransaction::whereNotNull('cashout_id')->where('pending', 1);
        if (!empty($request->end_date)) {
            $uangmukabeli = $uangmukabeli->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $uangmukabeli = $uangmukabeli->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $uangmukabeli = $uangmukabeli->sum('paid');

        $pesanjual = Stocktransaction::whereNotNull('cashin_id')->where('pending', 1);
        if (!empty($request->end_date)) {
            $pesanjual = $pesanjual->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $pesanjual = $pesanjual->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $pesanjual = $pesanjual->sum('paid');

        $hutangbeli = Stocktransaction::whereNotNull('cashout_id')->whereNull('pending')->whereNull('return');
        if (!empty($request->end_date)) {
            $hutangbeli = $hutangbeli->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime($request->end_date . " -1 year"))]);
        } else {
            $hutangbeli = $hutangbeli->whereBetween('date', [date('1111-01-01', time()), date('Y-12-31', strtotime(date('Y-m-d') . " -1 year"))]);
        }
        $hutangbeli = $hutangbeli->sum('total') - $hutangbeli->sum('discount') - $hutangbeli->sum('paid');


        //AKUN BERNAMA ;
        $akunJasa = Akun::where('name', '=', 'Pendapatan Jasa')->first();
        $akunJasa->total = $jasa;

        $akunPenjualan = Akun::where('name', '=', 'Pendapatan Penjualan')->first();
        $akunPenjualan->total = $penjualan;

        $akunBarang = Akun::where('name', '=', 'Pendapatan Barang')->first();
        $akunBarang->total = $barang;

        $akunBarangRugi = Akun::where('name', '=', 'Kerugian Barang Keluar Tanpa Penjualan')->first();
        $akunBarangRugi->total = $barangrugi;

        $akunPotonganBeli = Akun::where('name', '=', 'Potongan Pembelian')->first();
        $akunPotonganBeli->total = $potonganbeli;


        $akunHpp = Akun::where('name', '=', 'Harga Pokok Penjualan')->first();
        $akunHpp->total = $hpp;

        $akunPotonganJual = Akun::where('name', '=', 'Potongan Penjualan')->first();
        $akunPotonganJual->total = $potonganjual;

        $akunPiutangJual = Akun::where('name', '=', 'Piutang Penjualan')->first();
        $akunPiutangJual->total = $piutangjual;

        $akunPersediaan = Akun::where('name', '=', 'Persediaan Barang')->first();
        $akunPersediaan->total = $persediaan;

        $akunPesanBeli = Akun::where('name', '=', 'Uang Muka Pesanan Pembelian')->first();
        $akunPesanBeli->total = $uangmukabeli;

        $akunPesanJual = Akun::where('name', '=', 'Hutang Pesanan Penjualan')->first();
        $akunPesanJual->total = $pesanjual;

        $akunPembelian = Akun::where('name', '=', 'Hutang Pembelian Non Tunai')->first();
        $akunPembelian->total = $hutangbeli;
        //TOTAL KABEH
        function akunRekursif2($data, $total)
        {
            foreach ($data as $key => $valuedata) {
                if (!empty($valuedata->children)) {
                    foreach ($total as $key => $valuetotal) {
                        if ($valuedata->name == $valuetotal->name) {
                            $valuedata->total = $valuedata->total + $valuetotal->total;
                        }
                    }
                    akunRekursif2($valuedata->children, $total);
                } else {
                    foreach ($total as $key => $valuetotal) {
                        if ($valuedata->name == $valuetotal->name) {
                            $valuedata->total = $valuedata->total + $valuetotal->total;
                        }
                    }
                }
            }
        }
        function rekursifTotal2($data)
        {
            foreach ($data as $key => $value) {
                if (!empty($value->children)) {
                    rekursifTotal2($value->children);
                    foreach ($value->children as $key => $value2) {
                        $value->total += $value2->total;
                    }
                }
            }
        }
        // masukin
        $akun = [];
        foreach ($cash as $key => $value) {
            array_push($akun, $value);
        }

        foreach ($cashin as $key => $value) {
            array_push($akun, $value);
        }

        foreach ($cashout as $key => $value) {
            array_push($akun, $value);
        }

        foreach ($pendingCash as $key => $value) {
            array_push($akun, $value);
        }
        array_push($akun, $akunJasa);
        array_push($akun, $akunPenjualan);
        array_push($akun, $akunBarang);
        array_push($akun, $akunBarangRugi);
        array_push($akun, $akunPotonganBeli);
        array_push($akun, $akunPotonganJual);
        array_push($akun, $akunHpp);
        array_push($akun, $akunPiutangJual);
        array_push($akun, $akunPersediaan);
        array_push($akun, $akunPesanBeli);
        array_push($akun, $akunPesanJual);
        array_push($akun, $akunPembelian);
        $pdptn = Akun::where('name', 'Pendapatan')->with(str_repeat('children.', 10))->get();
        $hpp = Akun::where('name', 'Hpp')->with(str_repeat('children.', 10))->get();
        $biaya = Akun::where('name', 'Biaya')->with(str_repeat('children.', 10))->get();
        akunRekursif2($pdptn, $akun);
        akunRekursif2($hpp, $akun);
        akunRekursif2($biaya, $akun);
        rekursifTotal2($pdptn);
        rekursifTotal2($hpp);
        rekursifTotal2($biaya);

        $LTB = Akun::where('name', '=', 'Laba Tahun Berjalan')->first();
        $LTB->total = ($pdptn[0]->total - $hpp[0]->total - $biaya[0]->total);
        array_push($akun, $LTB);

        $data = Akun::where('name', 'Laba Tahun Berjalan')->with(str_repeat('children.', 10))->get();
        akunRekursif($data, $akun);
        return ($data[0]->total);
    }
}
