<?php

namespace App\Http\Controllers;

use App\Models\CostingProductionPlan;
use App\Models\CostingProductionPlanDetail;
use App\Models\ProductionPlan;
use App\Models\ProductionPlanDetail;
use App\Models\PengeluaranBahan;
use App\Models\PengeluaranBahanDetail;
use App\Models\ResultProcess;
use App\Models\ResultProcessDetail;
use App\Models\Process;
use App\Models\ItemDetail;
use App\Models\Company;
use App\Models\Department;
use App\Models\DeleteLog;
use App\Models\PenerimaanBahan;
use App\Models\PenerimaanBahanDetail;
use App\Models\CategoryEmployee;
use App\Models\Asset;
use App\Models\InventoryDetail;
use App\Models\Employee;
use App\Models\ElectricityPrice;
use App\Http\Controllers\Module;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class CostingProductionPlanController extends Controller
{
    public function store(Request $request)
    {
        try {
            Log::info('Memulai proses pembuatan Costing Production Plan', [
                'request_data' => $request->all()
            ]);

            $validated = Validator::make($request->all(), [
                'plan_id' => 'required|integer|exists:production_plans,id',
                'process_id' => 'required|integer|exists:process,id',
                'details' => 'nullable|array|min:1',
                'details.*.item_id' => 'required|integer|exists:items,id',
                'details.*.qty' => 'required|numeric|min:0',
                'details.*.unit' => 'required|integer|exists:item_units,id',
                'details.*.base_qty' => 'required|numeric|min:0',
                'details.*.base_unit' => 'required|integer|exists:item_units,id',
                'details.*.cost_per_unit' => 'nullable|numeric|min:0',
            ]);

            if ($validated->fails()) {
                Log::info('Validasi gagal', ['errors' => $validated->errors()]);
                return response()->json(['errors' => $validated->errors()], 422);
            }

            $validatedData = $validated->validated();
            Log::info('Data tervalidasi', ['validated_data' => $validatedData]);

            $total_labor_cost = 0;
            $total_overhead_cost = 0;
            $total_material_cost = 0;
            $qty_produced = 0;

            $company = Company::first();
            Log::info('Mengambil data perusahaan pertama', ['company' => $company ? $company->toArray() : null]);

            $plan = ProductionPlan::findOrFail($validatedData['plan_id']);
            Log::info('Mengambil rencana produksi', ['plan_id' => $validatedData['plan_id'], 'plan' => $plan->toArray()]);

            $department = Department::findOrFail($plan->department_id);
            Log::info('Mengambil data departemen', ['department_id' => $plan->department_id, 'department' => $department->toArray()]);

            $date = Carbon::now()->format('Y-m-d');
            $nobukti = Module::generateDocumentNumber($company->companyCode, $department->department_code, Carbon::now()->month, Carbon::now()->year, "CSTPP", 1);
            Log::info('Menghasilkan nomor dokumen', ['nobukti' => $nobukti, 'date' => $date]);

            $pengeluaran_bahans = PengeluaranBahan::where('plan_id', $validatedData['plan_id'])
                ->where('process_id', $validatedData['process_id'])
                ->pluck('pengeluaran_bahan_id')
                ->toArray();
            Log::info('Mengambil data pengeluaran bahan IDs', [
                'plan_id' => $validatedData['plan_id'],
                'process_id' => $validatedData['process_id'],
                'pengeluaran_bahans_count' => count($pengeluaran_bahans)
            ]);

            if (!empty($pengeluaran_bahans)) {
                $inventory_details = InventoryDetail::whereIn('document_number', $pengeluaran_bahans)
                    ->where('transaction_type', 'Production Penggunaan Bahan')
                    ->get();

                Log::info('Mengambil detail inventaris untuk perhitungan biaya bahan', [
                    'count' => $inventory_details->count(),
                    'plan_id' => $validatedData['plan_id'],
                    'process_id' => $validatedData['process_id']
                ]);

                foreach ($inventory_details as $inventory_detail) {
                    $material_cost = abs($inventory_detail->cogs ?? 0);
                    $total_material_cost += $material_cost;
                    $qty_produced += $inventory_detail->quantity;
                    Log::info('Menghitung biaya bahan untuk detail inventaris', [
                        'inventory_detail_id' => $inventory_detail->id,
                        'quantity' => $inventory_detail->quantity,
                        'cogs' => $inventory_detail->cogs,
                        'material_cost' => $material_cost
                    ]);
                }
            }

            $pengeluaran_bahans = PengeluaranBahan::where('plan_id', $validatedData['plan_id'])
                ->where('process_id', $validatedData['process_id'])
                ->with('details')
                ->get();
            Log::info('Mengambil data pengeluaran bahan', [
                'plan_id' => $validatedData['plan_id'],
                'process_id' => $validatedData['process_id'],
                'pengeluaran_bahans_count' => $pengeluaran_bahans->count()
            ]);

            $warehouse_id = null;
            foreach ($pengeluaran_bahans as $pengeluaran) {
                $pengeluaran_details = $pengeluaran->details;
                $pengeluaran_labor_cost = 0;
                Log::info('Memproses pengeluaran bahan', ['pengeluaran_bahan_id' => $pengeluaran->id]);

                $employee_results = json_decode($pengeluaran->employee_result ?? '[]', true);
                foreach ($employee_results as $employee_result) {
                    $employee_id = $employee_result['employee_id'] ?? null;
                    $qty = $employee_result['qty'] ?? 0;
                    $category_employee_code = $employee_result['category_employee_code'] ?? null;

                    $category = CategoryEmployee::where('category_employee_code', $category_employee_code)->first();
                    $labor_cost = 0;
                    if ($category) {
                        $labor_cost = $qty * ($category->category_employee_cost ?? 0);
                        $total_labor_cost += $labor_cost;
                        $pengeluaran_labor_cost += $labor_cost;
                        Log::info('Menghitung biaya tenaga kerja untuk pengeluaran bahan', [
                            'employee_id' => $employee_id,
                            'category_employee_code' => $category_employee_code,
                            'qty' => $qty,
                            'category_employee_cost' => $category->category_employee_cost,
                            'labor_cost' => $labor_cost
                        ]);
                    }
                }

                foreach ($pengeluaran_details as $detail) {
                    if (is_null($warehouse_id) && !is_null($pengeluaran->warehouse_id)) {
                        $warehouse_id = $pengeluaran->warehouse_id;
                    }
                    Log::info('Menghitung biaya bahan untuk pengeluaran bahan', [
                        'pengeluaran_bahan_id' => $pengeluaran->id,
                        'item_id' => $detail->item_id,
                        'qty' => $detail->qty,
                        'unit' => $detail->unit,
                        'warehouse_id' => $warehouse_id
                    ]);
                }
                Log::info('Total biaya tenaga kerja untuk pengeluaran bahan ini', [
                    'pengeluaran_bahan_id' => $pengeluaran->id,
                    'pengeluaran_labor_cost' => $pengeluaran_labor_cost
                ]);
            }

            $result_processes = ResultProcess::where('plan_id', $validatedData['plan_id'])
                ->where('process_id', $validatedData['process_id'])
                ->with('machine')
                ->get();
            Log::info('Mengambil data hasil proses', [
                'plan_id' => $validatedData['plan_id'],
                'process_id' => $validatedData['process_id'],
                'result_processes_count' => $result_processes->count()
            ]);

            foreach ($result_processes as $process) {
                $process_overhead_cost = 0;
                $process_labor_cost = 0;
                Log::info('Memproses hasil proses', ['result_process_id' => $process->id]);

                $employee_results = json_decode($process->employee_result ?? '[]', true);
                foreach ($employee_results as $employee_result) {
                    $employee_id = $employee_result['employee_id'] ?? null;
                    $qty = $employee_result['qty'] ?? 0;
                    $category_employee_code = $employee_result['category_employee_code'] ?? null;

                    $category = CategoryEmployee::where('category_employee_code', $category_employee_code)->first();
                    $labor_cost = 0;
                    if ($category) {
                        $labor_cost = $qty * ($category->category_employee_cost ?? 0);
                        $total_labor_cost += $labor_cost;
                        $process_labor_cost += $labor_cost;
                        Log::info('Menghitung biaya tenaga kerja untuk hasil proses', [
                            'result_process_id' => $process->id,
                            'employee_id' => $employee_id,
                            'category_employee_code' => $category_employee_code,
                            'qty' => $qty,
                            'category_employee_cost' => $category->category_employee_cost,
                            'labor_cost' => $labor_cost
                        ]);
                    }
                }

                if ($process->machine && $process->kwh_consumption) {
                    $asset = Asset::where('category_asset_id', function ($query) {
                        $query->select('id')
                            ->from('category_assets')
                            ->where('category_asset_code', 'MAC001')
                            ->first();
                    })
                        ->where('id', $process->machine)
                        ->first();

                    if ($asset) {
                        $latest_electricity_price = ElectricityPrice::orderBy('date', 'desc')->first()->price ?? 0;
                        $overhead_cost = $process->kwh_consumption * $latest_electricity_price;
                        $total_overhead_cost += $overhead_cost;
                        $process_overhead_cost += $overhead_cost;
                        Log::info('Menghitung biaya overhead untuk mesin', [
                            'result_process_id' => $process->id,
                            'machine_id' => $process->machine,
                            'kwh_consumption' => $process->kwh_consumption,
                            'electricity_price' => $latest_electricity_price,
                            'overhead_cost' => $overhead_cost
                        ]);
                    }
                }

                if ($process->overhead_result) {
                    $overhead_result = json_decode($process->overhead_result, true) ?? [];
                    foreach ($overhead_result as $overhead) {
                        $qty = $overhead['qty'] ?? 0;
                        $cost = $overhead['cost'] ?? 0;
                        $overhead_cost = $qty * $cost;
                        $total_overhead_cost += $overhead_cost;
                        $process_overhead_cost += $overhead_cost;
                        Log::info('Menghitung biaya overhead lainnya', [
                            'result_process_id' => $process->id,
                            'qty' => $qty,
                            'cost' => $cost,
                            'overhead_cost' => $overhead_cost
                        ]);
                    }
                }

                $process_details = ResultProcessDetail::where('result_process_id', $process->id)->get();
                foreach ($process_details as $detail) {
                    $qty_produced += $detail->qty ?? 0;
                    Log::info('Menghitung kuantitas yang dihasilkan untuk hasil proses', [
                        'result_process_id' => $process->id,
                        'item_id' => $detail->item_id,
                        'qty' => $detail->qty,
                        'unit' => $detail->unit
                    ]);
                }
                Log::info('Total biaya untuk hasil proses ini', [
                    'result_process_id' => $process->id,
                    'process_labor_cost' => $process_labor_cost,
                    'process_overhead_cost' => $process_overhead_cost
                ]);
            }

            $total_cost = $total_material_cost + $total_labor_cost + $total_overhead_cost;
            $cost_per_unit = $qty_produced > 0 ? $total_cost / $qty_produced : 0;
            Log::info('Menghitung total biaya dan biaya per unit', [
                'total_material_cost' => $total_material_cost,
                'total_labor_cost' => $total_labor_cost,
                'total_overhead_cost' => $total_overhead_cost,
                'total_cost' => $total_cost,
                'qty_produced' => $qty_produced,
                'cost_per_unit' => $cost_per_unit
            ]);

            DB::beginTransaction();
            Log::info('Memulai transaksi database');

            $costing = CostingProductionPlan::create([
                'costing_id' => $nobukti,
                'production_plan_id' => $validatedData['plan_id'],
                'process_id' => $validatedData['process_id'],
                'total_material_cost' => $total_material_cost,
                'total_labor_cost' => $total_labor_cost,
                'total_overhead_cost' => $total_overhead_cost,
                'total_cost' => $total_cost,
                'cost_per_unit' => $cost_per_unit,
                'created_by' => Auth::id(),
                'updated_by' => Auth::id(),
            ]);
            Log::info('Membuat entri CostingProductionPlan', [
                'costing_id' => $nobukti,
                'total_cost' => $total_cost,
                'cost_per_unit' => $cost_per_unit
            ]);

            $details = [];
            if (!empty($validatedData['details'])) {
                foreach ($validatedData['details'] as $detail) {
                    $item_detail = ItemDetail::where('item_id', $detail['item_id'])
                        ->where('unit_id', $detail['unit'])
                        ->first();
                    if (!$item_detail) {
                        throw new \Exception("Item detail not found for item_id: {$detail['item_id']}, unit_id: {$detail['unit']}");
                    }

                    $details[] = [
                        'costing_production_plan_id' => $costing->id,
                        'item_id' => $detail['item_id'],
                        'qty' => $detail['qty'],
                        'unit' => $detail['unit'],
                        'base_qty' => $detail['base_qty'],
                        'base_unit' => $detail['base_unit'],
                        'cost_per_unit' => $cost_per_unit,
                        'created_at' => now(),
                        'updated_at' => now(),
                    ];
                    Log::info('Menyiapkan detail costing production plan', [
                        'item_id' => $detail['item_id'],
                        'qty' => $detail['qty'],
                        'unit' => $detail['unit'],
                        'cost_per_unit' => $cost_per_unit
                    ]);
                }
                CostingProductionPlanDetail::insert($details);
                Log::info('Menyisipkan detail costing production plan', ['details_count' => count($details)]);
            }

            $penerimaan_bahans = PenerimaanBahan::where('plan_id', $validatedData['plan_id'])
                ->where('process_id', $validatedData['process_id'])
                ->pluck('penerimaan_bahan_id')
                ->toArray();
            Log::info('Mengambil data penerimaan bahan IDs', [
                'plan_id' => $validatedData['plan_id'],
                'process_id' => $validatedData['process_id'],
                'penerimaan_bahans_count' => count($penerimaan_bahans)
            ]);

            if (!empty($penerimaan_bahans)) {
                $inventory_details = InventoryDetail::whereIn('document_number', $penerimaan_bahans)
                    ->where('transaction_type', 'Production Pengambilan Bahan')
                    ->get();

                Log::info('Mengambil detail inventaris untuk pembaruan biaya', [
                    'count' => $inventory_details->count(),
                    'plan_id' => $validatedData['plan_id'],
                    'process_id' => $validatedData['process_id']
                ]);

                $total_qty = $inventory_details->sum('quantity');
                Log::info('Total kuantitas untuk pembagian biaya', [
                    'total_qty' => $total_qty,
                    'total_cost' => $total_cost
                ]);

                foreach ($inventory_details as $inventory_detail) {
                    if ($total_qty > 0) {
                        $proportion = $inventory_detail->quantity / $total_qty;
                        $allocated_cost = $total_cost * $proportion;
                    } else {
                        $allocated_cost = 0;
                    }

                    $inventory_detail->update([
                        'total' => $allocated_cost,
                        'cogs' => $allocated_cost,
                    ]);
                    Log::info('Memperbarui detail inventaris dengan biaya terbagi', [
                        'inventory_detail_id' => $inventory_detail->id,
                        'document_number' => $inventory_detail->document_number,
                        'quantity' => $inventory_detail->quantity,
                        'proportion' => $proportion ?? 0,
                        'allocated_cost' => $allocated_cost,
                        'total' => $allocated_cost,
                        'cogs' => $allocated_cost
                    ]);
                }
            }

            DB::commit();
            Log::info('Transaksi database berhasil diselesaikan');

            $response = $costing->load('details');
            Log::info('Mempersiapkan respons sukses', ['costing_id' => $costing->id]);
            return response()->json($response, 201);
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('Gagal membuat costing production plan', [
                'exception' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'request_data' => $request->all(),
            ]);
            return response()->json(['error' => 'Failed to create costing production plan'], 500);
        }
    }

    public function index(Request $request)
    {
        try {
            Log::info('Mengambil semua data CostingProductionPlan');
            $costings = CostingProductionPlan::with(['details.item', 'productionPlan.item', 'process'])->get();
            Log::info('Berhasil mengambil data CostingProductionPlan', ['count' => $costings->count()]);
            return response()->json($costings);
        } catch (\Exception $e) {
            Log::error('Gagal mengambil data CostingProductionPlan', [
                'exception' => $e->getMessage(),
                'stack_trace' => $e->getTraceAsString(),
                'request_data' => $request->all()
            ]);
            return response()->json(['error' => 'Failed to retrieve costing production plans'], 500);
        }
    }

    public function show($id)
    {
        try {
            if (!is_numeric($id) || $id <= 0) {
                Log::info('ID CostingProductionPlan tidak valid', ['id' => $id]);
                return response()->json(['error' => 'Invalid costing production plan ID'], 400);
            }

            Log::info('Mengambil data CostingProductionPlan', ['id' => $id]);
            $costing = CostingProductionPlan::with(['details.item', 'productionPlan.item', 'process'])->findOrFail($id);
            Log::info('Berhasil mengambil data CostingProductionPlan', ['id' => $id]);
            return response()->json($costing);
        } catch (\Exception $e) {
            Log::error('Gagal mengambil data CostingProductionPlan', [
                'costing_id' => $id,
                'exception' => $e->getMessage(),
                'stack_trace' => $e->getTraceAsString()
            ]);
            return response()->json(['error' => 'Failed to retrieve costing production plan'], 404);
        }
    }

    public function destroy($id)
    {
        try {
            if (!is_numeric($id) || $id <= 0) {
                Log::info('ID CostingProductionPlan tidak valid untuk penghapusan', ['id' => $id]);
                return response()->json(['error' => 'Invalid costing production plan ID'], 400);
            }

            Log::info('Memulai proses penghapusan CostingProductionPlan', ['id' => $id]);
            $costing = CostingProductionPlan::with('details')->findOrFail($id);
            $costingData = $costing->toArray();
            $costingData['details'] = $costing->details->toArray();

            DeleteLog::create([
                'table_name' => 'costing_production_plans',
                'record_id' => $id,
                'deleted_by' => Auth::id(),
                'deleted_at' => Carbon::now(),
                'data' => json_encode($costingData),
            ]);
            Log::info('Membuat log penghapusan', ['record_id' => $id]);

            $costing->details()->delete();
            $costing->delete();
            Log::info('Berhasil menghapus CostingProductionPlan dan detailnya', ['id' => $id]);

            return response()->json(['message' => 'Costing production plan deleted successfully'], 204);
        } catch (\Exception $e) {
            Log::error('Gagal menghapus CostingProductionPlan', [
                'costing_id' => $id,
                'exception' => $e->getMessage(),
                'stack_trace' => $e->getTraceAsString()
            ]);
            return response()->json(['error' => 'Failed to delete costing production plan'], 500);
        }
    }

    public function getMasterData()
    {
        try {
            Log::info('Mengambil master data untuk CostingProductionPlan');
            $company = Company::first();
            $department = Department::first();
            $date = Carbon::now()->format('Y-m-d H:i:s');
            $nobukti = Module::generateDocumentNumber($company->companyCode, $department->department_code, Carbon::now()->month, Carbon::now()->year, "CSTPP", 0);
            Log::info('Menghasilkan nomor dokumen untuk master data', ['nobukti' => $nobukti]);

            $item_details = ItemDetail::with(['item', 'unit'])->orderBy('id')->get();
            $production_plans = ProductionPlan::with(['item', 'unit'])->whereIn('status', ['Pending', 'On Progress', 'Completed'])->orderBy('id')->get();
            $production_plan_details = ProductionPlanDetail::with(['item', 'unit', 'process'])->orderBy('id')->get();
            $processes = Process::all();
            Log::info('Mengambil data item, rencana produksi, dan proses', [
                'item_details_count' => $item_details->count(),
                'production_plans_count' => $production_plans->count(),
                'production_plan_details_count' => $production_plan_details->count(),
                'processes_count' => $processes->count()
            ]);

            $data = [
                'item_details' => $item_details,
                'production_plans' => $production_plans,
                'production_plan_details' => $production_plan_details,
                'processes' => $processes,
                'nobukti' => $nobukti,
            ];

            Log::info('Berhasil mengambil master data');
            return response()->json($data);
        } catch (\Exception $e) {
            Log::error('Gagal mengambil master data untuk CostingProductionPlan', [
                'exception' => $e->getMessage(),
                'stack_trace' => $e->getTraceAsString()
            ]);
            return response()->json(['error' => 'Failed to retrieve master data for costing production plan'], 500);
        }
    }

    public function itemForPlan($planId)
    {
        try {
            if (!is_numeric($planId) || $planId <= 0) {
                Log::info('ID rencana produksi tidak valid', ['plan_id' => $planId]);
                return response()->json(['error' => 'Invalid production plan ID'], 400);
            }

            Log::info('Mengambil data pengeluaran bahan untuk rencana produksi', ['plan_id' => $planId]);
            $pengeluaranBahans = PengeluaranBahan::where('plan_id', $planId)->get();
            if ($pengeluaranBahans->isEmpty()) {
                Log::info('Tidak ada pengeluaran bahan ditemukan', ['plan_id' => $planId]);
                return response()->json(['error' => 'No Pengeluaran Bahan found for this production plan'], 404);
            }

            $items = [];
            foreach ($pengeluaranBahans as $pengeluaranBahan) {
                $details = PengeluaranBahanDetail::where('pengeluaran_bahan_id', $pengeluaranBahan->id)
                    ->with(['item', 'unit'])
                    ->get()
                    ->map(function ($detail) use ($pengeluaranBahan) {
                        $itemDetail = ItemDetail::where('item_id', $detail->item_id)
                            ->where('unit_id', (int)$detail->unit)
                            ->first();
                        return [
                        'pengeluaran_bahan_id' => $pengeluaranBahan->id,
                        'item_id' => $detail->item_id,
                        'qty' => (float)$detail->qty ?? 0,
                        'unit' => (int)$detail->unit ?? 0,
                        'unit_name' => $itemDetail ? $itemDetail->unit->unit_name : 'Unknown Unit',
                        'base_qty' => (float)$detail->base_qty ?? 0,
                            'base_unit' => (int)$detail->unit ?? 0,
                            'base_unit_name' => $itemDetail ? $itemDetail->unit->unit_name : 'Unknown Unit',
                        ];
                    });

                $items = array_merge($items, $details->toArray());
                Log::info('Memproses detail pengeluaran bahan', [
                    'pengeluaran_bahan_id' => $pengeluaranBahan->id,
                    'items_count' => $details->count()
                ]);
            }

            Log::info('Berhasil mengambil item untuk rencana produksi', ['plan_id' => $planId, 'items_count' => count($items)]);
            return response()->json([
                'pengeluaran_bahans' => $pengeluaranBahans->toArray(),
                'items' => $items
            ]);
        } catch (\Exception $e) {
            Log::error('Gagal mengambil item untuk rencana produksi', [
                'plan_id' => $planId,
                'exception' => $e->getMessage(),
                'stack_trace' => $e->getTraceAsString()
            ]);
            return response()->json(['error' => 'Failed to retrieve items for production plan'], 404);
        }
    }

    public function itemForPlanByProcess($planId, $processId)
    {
        try {
            if (!is_numeric($planId) || $planId <= 0) {
                Log::info('ID rencana produksi tidak valid', ['plan_id' => $planId]);
                return response()->json(['error' => 'Invalid production plan ID'], 400);
            }
            if (!is_numeric($processId) || $processId <= 0) {
                Log::info('ID proses tidak valid', ['process_id' => $processId]);
                return response()->json(['error' => 'Invalid process ID'], 400);
            }

            Log::info('Mengambil data pengeluaran bahan berdasarkan rencana produksi dan proses', [
                'plan_id' => $planId,
                'process_id' => $processId
            ]);
            $pengeluaranBahans = PengeluaranBahan::where('plan_id', $planId)
                ->where('process_id', $processId)
                ->get();
            if ($pengeluaranBahans->isEmpty()) {
                Log::info('Tidak ada pengeluaran bahan ditemukan untuk rencana produksi dan proses ini', [
                    'plan_id' => $planId,
                    'process_id' => $processId
                ]);
                return response()->json(['error' => 'No Pengeluaran Bahan found for this production plan and process'], 404);
            }

            $items = [];
            $mergedItems = [];

            foreach ($pengeluaranBahans as $pengeluaranBahan) {
                $details = PengeluaranBahanDetail::where('pengeluaran_bahan_id', $pengeluaranBahan->id)
                    ->with(['item', 'unit'])
                    ->get()
                    ->map(function ($detail) use ($pengeluaranBahan) {
                        $itemDetail = ItemDetail::where('item_id', $detail->item_id)
                            ->where('unit_id', (int)$detail->unit)
                            ->first();
                        return [
                            'item_id' => $detail->item_id,
                        'qty' => (float)$detail->qty ?? 0,
                        'unit' => (int)$detail->unit ?? 0,
                        'unit_name' => $itemDetail ? $itemDetail->unit->unit_name : 'Unknown Unit',
                        'base_qty' => (float)$detail->base_qty ?? 0,
                        'base_unit' => (int)$detail->unit ?? 0,
                        'base_unit_name' => $itemDetail ? $itemDetail->unit->unit_name : 'Unknown Unit',
                        'pengeluaran_bahan_id' => $pengeluaranBahan->id,
                        ];
                    });

                $items = array_merge($items, $details->toArray());
                Log::info('Memproses detail pengeluaran bahan untuk proses', [
                    'pengeluaran_bahan_id' => $pengeluaranBahan->id,
                    'items_count' => $details->count()
                ]);
            }

            foreach ($items as $item) {
                $key = $item['item_id'] . '-' . $item['unit'];
                if (!isset($mergedItems[$key])) {
                    $mergedItems[$key] = [
                        'item_id' => $item['item_id'],
                        'qty' => $item['qty'],
                        'unit' => $item['unit'],
                        'unit_name' => $item['unit_name'],
                        'base_qty' => $item['base_qty'],
                        'base_unit' => $item['unit'],
                        'base_unit_name' => $item['unit_name'],
                    ];
                } else {
                    $mergedItems[$key]['qty'] += $item['qty'];
                }
            }

            Log::info('Berhasil mengambil item untuk rencana produksi berdasarkan proses', [
                'plan_id' => $planId,
                'process_id' => $processId,
                'items_count' => count($mergedItems)
            ]);
            return response()->json([
                'pengeluaran_bahans' => $pengeluaranBahans->toArray(),
                'items' => array_values($mergedItems)
            ]);
        } catch (\Exception $e) {
            Log::error('Gagal mengambil item untuk rencana produksi berdasarkan proses', [
                'plan_id' => $planId,
                'process_id' => $processId,
                'exception' => $e->getMessage(),
                'stack_trace' => $e->getTraceAsString()
            ]);
            return response()->json(['error' => 'Failed to retrieve items for production plan by process'], 404);
        }
    }
}