<?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\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', 'beli_aset'];

                // 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) {
                $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)"));
            },
            // 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)"));
            }
        ])->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 + $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']);
                    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']);

                    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;
        }

        // 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', '<>', 'service');
        })->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', '<>', '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->where('nonmoney', 'out');
        })->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())]);
        }

        $piutangjualcredit = Credit::whereNotNull('cashin_id');
        $piutangjualcredit->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');

        // persedian
        $persediaanmasuk = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', '<>', 'service');
        })->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', '<>', 'service');
        })->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', '<>', 'service');
        })->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', '<>', '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('hpp');

        $persediaankeluar = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', '<>', 'service');
        })->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', '<>', 'service');
        })->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', '<>', 'service');
        })->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', '<>', 'service');
        })->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;

        $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('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::where('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->where('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');

        $hutangpembelianasettetapcredit = CreditCashTransaction::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');

        // 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;

        //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);
        Log::info('Retur Penjualan: ' . -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;

        $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;

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

        $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;

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

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

        $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;
                            // Log::info($valuedata->name . ' => ' . $valuedata->total);
                        }
                    }
                    akunRekursif($valuedata->children, $total);
                } else {
                    foreach ($total as $key => $valuetotal) {
                        if ($valuedata->name == $valuetotal->name) {
                            $valuedata->total = $valuedata->total + $valuetotal->total;
                            // Log::info($valuedata->name . ' => ' . $valuedata->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);
                }
            }
        }

        // 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, $akunHpp);
        array_push($akun, $akunPiutangJual);
        array_push($akun, $akunPersediaan);
        array_push($akun, $akunPesanBeli);
        array_push($akun, $akunPesanJual);
        array_push($akun, $akunPembelian);
        array_push($akun, $akunbiayaharusdibayar);
        array_push($akun, $akunhutangpembelianasettetap);
        array_push($akun, $akuncadanganwajib);
        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();

        $LTB->total = ($pdptn[0]->total - $hpp[0]->total - $biaya[0]->total)
            - $labaDitahan
            - $return_out_price_diff_lt
            + $return_out_price_diff_gt
            - ($cwltb * 2)
            + $tcwltb;

        Log::info('Laba Tahun Berjalan: ', [
            'pendapatan' => $pdptn[0]->total,
            'hpp' => $hpp[0]->total,
            'biaya' => $biaya[0]->total,
            'laba ditahan' => $labaDitahan,
            'return out price diff lt' => $return_out_price_diff_lt,
            'return out price diff gt' => $return_out_price_diff_gt,
            'cadangan wajib x2' => $cwltb * 2,
            'tarik cadangan wajib' => $tcwltb,
            'total' => $LTB->total,
        ]);

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

        // Log::info('Laba Ditahan: ', [
        //     'laba ditahan' => $labaDitahan,
        //     'cadangan wajib x2' => $cwldt * 2,
        //     'tarik cadangan wajib' => $tcwldt,
        //     'total' => $LD->total,
        // ]);

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

        akunRekursif($data, $akun);
        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', 'beli_aset'];

                // 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) {
                $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)"));
            },
            // 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)"));
            }
        ])->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 + $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']);
                    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']);

                    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;
        }

        // 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', '<>', 'service');
        })->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', '<>', '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');

        // 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"))]);
        }

        $piutangjualcredit = Credit::whereNotNull('cashin_id');
        $piutangjualcredit->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');

        // persedian
        $persediaanmasuk = Substocktransaction::whereHas('product', function ($product) {
            $product->where('category', '<>', 'service');
        })->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', '<>', 'service');
        })->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', '<>', 'service');
        })->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', '<>', '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) {
            $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', '<>', 'service');
        })->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', '<>', 'service');
        })->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', '<>', 'service');
        })->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;

        $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 * 2);
        // $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('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::where('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->where('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');

        $hutangpembelianasettetapcredit = CreditCashTransaction::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');

        // 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;

        //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;

        $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;

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

        $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;

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

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

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

        function akunRekursif3($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;
                        }
                    }
                    akunRekursif3($valuedata->children, $total);
                } else {
                    foreach ($total as $key => $valuetotal) {
                        if ($valuedata->name == $valuetotal->name) {
                            $valuedata->total = $valuedata->total + $valuetotal->total;
                        }
                    }
                }
            }
        }
        function rekursifTotal3($data)
        {
            foreach ($data as $key => $value) {
                if (!empty($value->children)) {
                    rekursifTotal3($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, $akunRetur);
        array_push($akun, $akunBarang);
        array_push($akun, $akunBarangRugi);
        array_push($akun, $akunPotonganBeli);
        array_push($akun, $akunPotonganJual);
        array_push($akun, $akunModalAwal);
        array_push($akun, $akunHpp);
        array_push($akun, $akunPiutangJual);
        array_push($akun, $akunPersediaan);
        array_push($akun, $akunPesanBeli);
        array_push($akun, $akunPesanJual);
        array_push($akun, $akunPembelian);
        array_push($akun, $akunbiayaharusdibayar);
        array_push($akun, $akunhutangpembelianasettetap);
        array_push($akun, $akuncadanganwajib);
        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();
        akunRekursif3($pdptn, $akun);
        akunRekursif3($hpp, $akun);
        akunRekursif3($biaya, $akun);
        rekursifTotal3($pdptn);
        rekursifTotal3($hpp);
        rekursifTotal3($biaya);

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

        $LTB->total = ($pdptn[0]->total - $hpp[0]->total - $biaya[0]->total)
            - $return_out_price_diff_lt
            + $return_out_price_diff_gt
            - ($cwltb * 2)
            + $tcwltb;

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

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

        akunRekursif3($data, $akun);
        rekursifTotal3($data);

        // Log::info('Laba Neraca: ', [
        //     'LTB' => $LTB->total,
        //     'LD' => $LD->total,
        // ]);

        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;
        }

        // 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('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', '<>', 'service');
        })->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', '<>', 'service');
        })->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);
        // Log::info('Laba Tahun Berjalan: ', [
        //     'pendapatan' => $pdptn[0]->total,
        //     'hpp' => $hpp[0]->total,
        //     'biaya' => $biaya[0]->total,
        //     'total' => $LTB->total,
        // ]);

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