<?php

namespace App\Http\Controllers;

use DB;
use Carbon\Carbon;
use App\Models\Item;
use App\Models\Company;
use App\Models\Periode;
use App\Models\Process;
use App\Models\Employee;
use App\Models\ItemUnit;
use App\Models\DeleteLog;
use App\Models\Warehouse;
use App\Models\Department;
use App\Models\ItemDetail;
use App\Models\Journal;
use Illuminate\Http\Request;
use App\Models\ProcessingPlan;
use App\Http\Controllers\Module;
use Illuminate\Support\Facades\Log;
use App\Models\ProcessingPlanDetail;
use Illuminate\Support\Facades\Auth;
use Picqer\Barcode\BarcodeGeneratorPNG;
use App\Models\ProcessingPenerimaanBahan;
use Illuminate\Support\Facades\Validator;
use App\Models\ProcessingPenerimaanBahanDetail;

class ProcessingPenerimaanBahanController extends Controller
{
    public function index($dateStart,$dateEnd)
    {
        try {
            $Listdepartment = $this->getDepartment();
            $penerimaanBahans = [];
            if(in_array(4,$Listdepartment)){
                $penerimaanBahans = ProcessingPenerimaanBahan::with(['details', 'plan.item', 'details.item', 'details.unit', 'process', 'warehouse', 'pic'])
                ->whereBetween('document_date',[$dateStart,$dateEnd])->get();
            }else{
                $penerimaanBahans = ProcessingPenerimaanBahan::whereRaw("1 <> 1")->get();
            }
            
            $periods = Periode::all();
            foreach($penerimaanBahans as $pb){
                $pb->closed =  Module::checkPeriodeBack($periods,$pb->document_date);
            }
            return response()->json(["penerimaanBahans" => $penerimaanBahans, "role" => $this->getRole()]);
        } catch (\Exception $e) {
            Log::error('Failed to fetch penerimaan bahan', ['error' => $e->getMessage(), 'user_id' => auth()->id()]);
            return response()->json(['error' => 'Server error'], 500);
        }
    }

    public function show($id)
    {
        try {
            $penerimaanBahan = ProcessingPenerimaanBahan::with(['details.item', 'details.unit', 'plan.item', 'process', 'warehouse', 'pic'])->findOrFail($id);
            return response()->json($penerimaanBahan);
        } catch (\Exception $e) {
            Log::error('Failed to fetch penerimaan bahan', ['id' => $id, 'error' => $e->getMessage(), 'user_id' => auth()->id()]);
            return response()->json(['error' => 'ProcessingPenerimaanBahan not found'], 404);
        }
    }

    public function store(Request $request)
    {
        $user = Auth::user();
        $defaultDepartmentId = $user->default_department_id ? json_decode($user->default_department_id) : [];
        $allDept = [];
        foreach($defaultDepartmentId as $d){
            $allDept[] = $d->department_id;
        }

        $validator = Validator::make($request->all(), [
            'document_date' => 'required|date',
            'warehouse_id' => 'required|exists:warehouse,id',
            'plan_id' => 'required|exists:processing_plans,id',
            'process_id' => 'required|exists:process,id',
            'pic' => 'required|exists:employees,id',
            'details' => 'required|array',
            'details.*.item_id' => 'required|exists:items,id',
            'details.*.item_date' => 'nullable|date',
            'details.*.qty' => 'required|numeric|min:0',
            'details.*.unit' => 'required|exists:item_units,id',
        ]);

        if ($validator->fails()) {
            Log::error('Validation failed for penerimaan bahan store', ['errors' => $validator->errors(), 'user_id' => auth()->id()]);
            return response()->json(['errors' => $validator->errors()], 422);
        }

        DB::beginTransaction();
        try {
            $company = Company::first();
            $department = Department::where('department_code','PRO001')->first();
            $date = Carbon::parse($request->document_date);
            $nobukti = Module::generateDocumentNumber($company->companyCode, $department->department_code, $date->month, $date->year, "PMM", 1);

            $penerimaanBahan = ProcessingPenerimaanBahan::create([
                'penerimaan_bahan_id' => $nobukti,
                'document_date' => $request->document_date,
                'warehouse_id' => $request->warehouse_id,
                'plan_id' => $request->plan_id,
                'process_id' => $request->process_id,
                'pic' => $request->pic,
                'created_by' => auth()->id(),
                'updated_by' => auth()->id(),
            ]);

            $existingReceipt = ProcessingPenerimaanBahan::where('plan_id', $request->plan_id)
                ->where('process_id', $request->process_id)
                ->where('id', '!=', $penerimaanBahan->id)
                ->exists();

            if (!$existingReceipt) {
                ProcessingPlan::where('id', $request->plan_id)
                    ->update(['status' => 'On Progress']);
                ProcessingPlanDetail::where('plan_id', $request->plan_id)
                    ->where('process_id', $request->process_id)
                    ->where('status', 'Pending')
                    ->update(['status' => 'On Progress']);
            }

            foreach ($request->details as $detail) {
                $itemDetail = ItemDetail::where("item_id", $detail['item_id'])->where("unit_id", $detail['unit'])->first();
                if (!$itemDetail) {
                    DB::rollback();
                    Log::error('ItemDetail not found', ['item_id' => $detail['item_id'], 'unit_id' => $detail['unit'], 'user_id' => auth()->id()]);
                    return response()->json(['error' => 'ItemDetail not found for item_id: ' . $detail['item_id'] . ', unit_id: ' . $detail['unit']], 422);
                }
                ProcessingPenerimaanBahanDetail::create([
                    'penerimaan_bahan_id' => $penerimaanBahan->id,
                    'warehouse_id' => $request->warehouse_id,
                    'item_id' => $detail['item_id'],
                    'item_date' => $detail['item_date']??$penerimaanBahan->document_date,
                    'qty' => $detail['qty'],
                    'unit' => $detail['unit'],
                    'base_qty' => $itemDetail->conversion,
                    'created_by' => auth()->id(),
                    'updated_by' => auth()->id(),
                ]);

                $cogs = Module::getCogs($penerimaanBahan->document_date,$detail['item_id'],$company->companyCode,$department->id,$penerimaanBahan->warehouse_id);
                DB::table('inventory_details')->insert([
                    'document_number' => $penerimaanBahan->penerimaan_bahan_id,
                    'document_date' => $penerimaanBahan->document_date,
                    'purchase_date' => $penerimaanBahan->document_date,
                    'transaction_type' => 'Processsing Pengambilan Bahan',
                    'warehouse_id' => $penerimaanBahan->warehouse_id,
                    'item_id' => $detail['item_id'],
                    'quantity' => $detail['qty'],
                    'unit' => $detail['unit'],
                    'base_quantity' => $itemDetail->conversion,
                    'unit_base' => $itemDetail->item->base_unit_id,
                    'department_id' => $department->id,
                    'company_code' => $company->companyCode,
                    'total' => $cogs * $detail['qty'] * $itemDetail->conversion,
                    'cogs' => $cogs * $detail['qty'] * $itemDetail->conversion,
                    'qty_actual' => $detail['qty'],
                    'created_by' => Auth::user()->id,
                    'updated_by' => Auth::user()->id,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);

                $it = Item::find($detail['item_id']);
                if($it){
                    $accWip = $it->categoryItem->acc_number_wip;
                    Journal::create([
                        'document_number' => $penerimaanBahan->penerimaan_bahan_id,
                        'document_date' => $penerimaanBahan->document_date,
                        'account_number' => $accWip,
                        'notes' => 'Persediaan dalam WIP: ' . $it->item_name,
                        'debet_nominal' => 0,
                        'credit_nominal' => $cogs * $detail['qty'] * $itemDetail->conversion,
                        'debet_nominal_base' => 0,
                        'credit_nominal_base' => $cogs * $detail['qty'] * $itemDetail->conversion,
                        'company_code' => $company->companyCode,
                        'department_id' => $department->id,
                        'created_by' => Auth::user()->id,
                        'updated_by' => Auth::user()->id,
                    ]);
                    
                    Journal::create([
                        'document_number' => $penerimaanBahan->penerimaan_bahan_id,
                        'document_date' => $penerimaanBahan->document_date,
                        'account_number' => $it->categoryItem->account_inventory,
                        'notes' => 'Persediaan: ' . $it->item_name,
                        'debet_nominal' => $cogs * $detail['qty'] * $itemDetail->conversion,
                        'credit_nominal' => 0,
                        'debet_nominal_base' => $cogs * $detail['qty'] * $itemDetail->conversion,
                        'credit_nominal_base' => 0,
                        'company_code' => $company->companyCode,
                        'department_id' => $department->id,
                        'created_by' => Auth::user()->id,
                        'updated_by' => Auth::user()->id,
                    ]);
                }
            }

            DB::commit();
            return response()->json(null);
        } catch (\Exception $e) {
            DB::rollback();
            Log::error('Failed to store penerimaan bahan', ['error' => $e->getMessage(), 'request' => $request->all(), 'user_id' => auth()->id()]);
            return response()->json(['error' => 'Server error'], 500);
        }
    }

    public function update(Request $request, $id)
    {
        $user = Auth::user();
        $defaultDepartmentId = $user->default_department_id ? json_decode($user->default_department_id) : [];
        $allDept = [];
        foreach($defaultDepartmentId as $d){
            $allDept[] = $d->department_id;
        }

        try {
            $penerimaanBahan = ProcessingPenerimaanBahan::findOrFail($id);

            $validator = Validator::make($request->all(), [
                'document_date' => 'required|date',
                'warehouse_id' => 'required|exists:warehouse,id',
                'plan_id' => 'required|exists:processing_plans,id',
                'process_id' => 'required|exists:process,id',
                'pic' => 'required|exists:employees,id',
                'details' => 'required|array',
                'details.*.item_id' => 'required|exists:items,id',
                'details.*.item_date' => 'nullable|date',
                'details.*.qty' => 'required|numeric|min:0',
                'details.*.unit' => 'required|exists:item_units,id',
            ]);

            if ($validator->fails()) {
                Log::error('Validation failed for penerimaan bahan update', ['id' => $id, 'errors' => $validator->errors(), 'user_id' => auth()->id()]);
                return response()->json(['errors' => $validator->errors()], 422);
            }

            DB::beginTransaction();

            $penerimaanBahan->update([
                'warehouse_id' => $request->warehouse_id,
                'plan_id' => $request->plan_id,
                'process_id' => $request->process_id,
                'pic' => $request->pic,
                'updated_by' => auth()->id(),
            ]);

            $existingReceipt = ProcessingPenerimaanBahan::where('plan_id', $request->plan_id)
                ->where('process_id', $request->process_id)
                ->where('id', '!=', $penerimaanBahan->id)
                ->exists();

            if (!$existingReceipt) {
                ProcessingPlan::where('id', $request->plan_id)
                    ->update(['status' => 'On Progress']);
                ProcessingPlanDetail::where('plan_id', $request->plan_id)
                    ->where('process_id', $request->process_id)
                    ->where('status', 'Pending')
                    ->update(['status' => 'On Progress']);
            }

            $penerimaanBahan->details()->delete();
            DB::table('inventory_details')->where("document_number",$penerimaanBahan->penerimaan_bahan_id)->delete();
            Journal::where("document_number",$penerimaanBahan->penerimaan_bahan_id)->delete();

            $company = Company::first();
            $department = Department::where('department_code','PRO001')->first();

            foreach ($request->details as $detail) {
                $itemDetail = ItemDetail::where("item_id", $detail['item_id'])->where("unit_id", $detail['unit'])->first();
                if (!$itemDetail) {
                    DB::rollback();
                    Log::error('ItemDetail not found for update', ['id' => $id, 'item_id' => $detail['item_id'], 'unit_id' => $detail['unit'], 'user_id' => auth()->id()]);
                    return response()->json(['error' => 'ItemDetail not found for item_id: ' . $detail['item_id'] . ', unit_id: ' . $detail['unit']], 422);
                }
                ProcessingPenerimaanBahanDetail::create([
                    'penerimaan_bahan_id' => $penerimaanBahan->id,
                    'warehouse_id' => $request->warehouse_id,
                    'item_id' => $detail['item_id'],
                    'item_date' => $detail['item_date']??$penerimaanBahan->document_date,
                    'qty' => $detail['qty'],
                    'unit' => $detail['unit'],
                    'base_qty' => $itemDetail->conversion,
                    'created_by' => $penerimaanBahan->created_by,
                    'updated_by' => auth()->id(),
                ]);

                $cogs = Module::getCogs($penerimaanBahan->document_date,$detail['item_id'],$company->companyCode,$department->id,$penerimaanBahan->warehouse_id);
                DB::table('inventory_details')->insert([
                    'document_number' => $penerimaanBahan->penerimaan_bahan_id,
                    'document_date' => $penerimaanBahan->document_date,
                    'purchase_date' => $penerimaanBahan->document_date,
                    'transaction_type' => 'Processsing Pengambilan Bahan',
                    'warehouse_id' => $penerimaanBahan->warehouse_id,
                    'item_id' => $detail['item_id'],
                    'quantity' => $detail['qty'],
                    'unit' => $detail['unit'],
                    'base_quantity' => $itemDetail->conversion,
                    'unit_base' => $itemDetail->item->base_unit_id,
                    'department_id' => $department->id,
                    'company_code' => $company->companyCode,
                    'total' => $cogs * $detail['qty'] * $itemDetail->conversion,
                    'cogs' => $cogs * $detail['qty'] * $itemDetail->conversion,
                    'qty_actual' => $detail['qty'],
                    'created_by' => Auth::user()->id,
                    'updated_by' => Auth::user()->id,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);

                $it = Item::find($detail['item_id']);
                if($it){
                    $accWip = $it->categoryItem->acc_number_wip;
                    Journal::create([
                        'document_number' => $penerimaanBahan->penerimaan_bahan_id,
                        'document_date' => $penerimaanBahan->document_date,
                        'account_number' => $accWip,
                        'notes' => 'Persediaan dalam WIP: ' . $it->item_name,
                        'debet_nominal' => 0,
                        'credit_nominal' => $cogs * $detail['qty'] * $itemDetail->conversion,
                        'debet_nominal_base' => 0,
                        'credit_nominal_base' => $cogs * $detail['qty'] * $itemDetail->conversion,
                        'company_code' => $company->companyCode,
                        'department_id' => $department->id,
                        'created_by' => Auth::user()->id,
                        'updated_by' => Auth::user()->id,
                    ]);
                    
                    Journal::create([
                        'document_number' => $penerimaanBahan->penerimaan_bahan_id,
                        'document_date' => $penerimaanBahan->document_date,
                        'account_number' => $it->categoryItem->account_inventory,
                        'notes' => 'Persediaan: ' . $it->item_name,
                        'debet_nominal' => $cogs * $detail['qty'] * $itemDetail->conversion,
                        'credit_nominal' => 0,
                        'debet_nominal_base' => $cogs * $detail['qty'] * $itemDetail->conversion,
                        'credit_nominal_base' => 0,
                        'company_code' => $company->companyCode,
                        'department_id' => $department->id,
                        'created_by' => Auth::user()->id,
                        'updated_by' => Auth::user()->id,
                    ]);
                }
            }

            DB::commit();
            return response()->json($penerimaanBahan->load('details'));
        } catch (\Exception $e) {
            DB::rollback();
            Log::error('Failed to update penerimaan bahan', ['id' => $id, 'error' => $e->getMessage(), 'request' => $request->all(), 'user_id' => auth()->id()]);
            return response()->json(['error' => 'Server error'], 500);
        }
    }

    public function destroy($id)
    {
        try {
            $penerimaanBahan = ProcessingPenerimaanBahan::findOrFail($id);
            DB::beginTransaction();

            $penerimaanBahan->details()->delete();
            DB::table('inventory_details')->where("document_number",$penerimaanBahan->penerimaan_bahan_id)->delete();
            Journal::where('document_number', $penerimaanBahan->penerimaan_bahan_id)->delete();

            DeleteLog::create([
                'document_number' => $penerimaanBahan->penerimaan_bahan_id,
                'document_date' => $penerimaanBahan->document_date,
                'delete_notes' => request()->delete_notes ?? 'No notes provided',
                'company_code' => null,
                'department_code' => null,
                'deleted_by' => Auth::check() ? Auth::user()->name : 'system',
                'type' => 'ProcessingPenerimaanBahan',
            ]);

            $penerimaanBahan->delete();

            DB::commit();
            return response()->json(null, 204);
        } catch (\Exception $e) {
            DB::rollback();
            Log::error('Failed to delete penerimaan bahan', ['id' => $id, 'error' => $e->getMessage(), 'user_id' => auth()->id()]);
            return response()->json(['error' => 'Server error'], 500);
        }
    }

    public function getMasterData()
    {
        try {
            $user = Auth::user();
            
            $processingPlans = ProcessingPlan::with(['details.process','item'])->whereIn('status', ['Pending', 'On Progress'])->get();
            $processingPlans->each(function ($plan) {
                $tgl = Carbon::parse($plan->production_start_date);
                $plan->production_start_date = $tgl->format("d-m-Y");
                
                $plan->details->each(function ($detail) {
                    $process = $detail->process;

                    if ($process) {
                        $data = json_decode($process->output_item_id, true);
                        $ids = is_array($data) ? array_column($data, 'id') : [];

                        if(count($ids) == 1){
                            if(!is_null($ids[0])){
                                // Get item names based on IDs
                                $items = Item::whereIn('id', $ids)->pluck('item_name', 'id');

                                // Attach to process
                                $process->output_item_ids = $ids;
                                $process->output_item_names = $ids ? array_values($items->only($ids)->toArray()) : null;
                            }
                        }
                    }
                });
            });

            // 4 = department Processing
            $gudangUser = DB::table("user_warehouse")->where("user_id",Auth::user()->id)->select("warehouse_id")->get()->pluck("warehouse_id")->toArray();
            $warehouses = Warehouse::whereIn("id",$gudangUser)->get();
            $itemDetails = ItemDetail::with('item', 'unit')->get();
            $employees = Employee::all();

            $company = Company::first();
            $department = Department::where('department_code','PRO001')->first();
            $date = Carbon::now();
            $nobukti = Module::generateDocumentNumber($company->companyCode, $department->department_code, $date->month, $date->year, "PMM", 0);

            return response()->json([
                'processing_plans' => $processingPlans,
                'warehouses' => $warehouses,
                'item_details' => $itemDetails,
                'employees' => $employees,
                'nobukti' => $nobukti,
                'role' => $this->getRole(),
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to fetch master data', ['error' => $e->getMessage(), 'user_id' => auth()->id()]);
            return response()->json(['error' => 'Server error'], 500);
        }
    }

    public function getItemsForProcess($processId)
    {
        try {
            if (!is_numeric($processId) || $processId <= 0) {
                Log::error('Invalid process ID', ['process_id' => $processId, 'user_id' => auth()->id()]);
                return response()->json(['error' => 'Invalid process ID'], 400);
            }

            $process = Process::findOrFail($processId);
            $itemIds = [];

            if (!empty($process->output_item_id)) {
                $inputData = is_string($process->output_item_id) ? json_decode($process->output_item_id, true) : $process->output_item_id;
                if (json_last_error() === JSON_ERROR_NONE && is_array($inputData)) {
                    foreach ($inputData as $item) {
                        if (isset($item['id']) && !empty($item['id'])) {
                            $itemIds[] = (int) $item['id'];
                        }
                    }
                }
            }

            if (!empty($process->output_item_id)) {
                $outputData = is_string($process->output_item_id) ? json_decode($process->output_item_id, true) : $process->output_item_id;
                if (json_last_error() === JSON_ERROR_NONE && is_array($outputData)) {
                    foreach ($outputData as $item) {
                        if (isset($item['id']) && !empty($item['id'])) {
                            $itemIds[] = (int) $item['id'];
                        }
                    }
                }
            }

            $itemIds = array_unique($itemIds);

            if (empty($itemIds)) {
                Log::info('No items found for process', ['process_id' => $processId, 'user_id' => auth()->id()]);
                return response()->json([]);
            }

            $itemDetails = ItemDetail::whereExists(function ($query) use($itemIds) {
                    $query->fromSub(function ($query2) use($itemIds) {
                        $query2->from('item_details')->select('item_id',DB::raw('min(conversion) as conversion'))->whereIn('item_id',$itemIds)->groupBy('item_id');
                    }, 'b')->whereColumn('b.item_id', 'item_details.item_id')->whereColumn('b.conversion', 'item_details.conversion');
                })
                ->with('item', 'unit')
                ->get();

            return response()->json($itemDetails);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            Log::error('Process not found', ['process_id' => $processId, 'error' => $e->getMessage(), 'user_id' => auth()->id()]);
            return response()->json(['error' => 'Process not found'], 404);
        } catch (\Exception $e) {
            Log::error('Failed to fetch items for process', ['process_id' => $processId, 'error' => $e->getMessage(), 'user_id' => auth()->id()]);
            return response()->json(['error' => 'Failed to load items for process'], 500);
        }
    }

    public function print($id)
    {
        try {
            $penerimaanBahan = ProcessingPenerimaanBahan::with(['details.item', 'pic' => function ($query) {
                $query->select('id', 'employee_name');
            }])->where("id", $id)->firstOrFail();
            $iu = ItemUnit::get();
            $imagePath = storage_path('app/images/logo-only.png');
            $imageData = file_get_contents($imagePath);

            foreach ($penerimaanBahan->details as $detail) {
                $detail->unit = $iu->where("id", $detail->unit)->first()->unit_name;
            }
            $username = Auth::user()->name;
            $pdf = \PDF::loadView('print.processing_material_receipt_pdf', compact('penerimaanBahan', 'imageData','username'))->setPaper('A5', 'landscape');
            return ["data" => "data:application/pdf;base64,".base64_encode($pdf->stream()),"role" => $this->getRole()];
        } catch (\Exception $e) {
            Log::error('Failed to generate PDF for penerimaan bahan', ['id' => $id, 'error' => $e->getMessage(), 'user_id' => auth()->id()]);
            return response()->json(['error' => 'Failed to generate PDF'], 500);
        }
    }

    public function increasePrintNumber($id){
        $do = ProcessingPenerimaanBahan::find($id);
        $do->print_number = ($do->print_number ?? 0) + 1;
        $do->save();
        return response()->json(null);
    }

    public function printDetail($penerimaanBahanId, $itemId)
    {
        try {
            $penerimaanBahan = ProcessingPenerimaanBahan::with([
                'details' => function ($query) use ($itemId) {
                    $query->where('item_id', $itemId)->with('item', 'units');
                },
                'plan',
                'plan.item',
                'process',
                'pic' => function ($query) {
                    $query->select('id', 'employee_name');
                }
            ])->where('id', $penerimaanBahanId)->firstOrFail();

            if ($penerimaanBahan->details->isEmpty()) {
                return response()->json(['error' => 'No details found for item'], 404);
            }

            $detail = $penerimaanBahan->details->first();
            $generator = new BarcodeGeneratorPNG();
            $barcodez = $itemId . '/' . $detail->unit. '/' . floor($detail->qty) . '/' . date('Y-m-d', strtotime($penerimaanBahan->document_date));
            $imageData = $generator->getBarcode($barcodez, $generator::TYPE_CODE_93);

            $pdf = \PDF::loadView('print.processing_material_receipt_detail_pdf', compact('penerimaanBahan', 'detail', 'imageData'))
                ->setPaper('A5', 'portrait');
            return response()->json([
                'data' => "data:application/pdf;base64," . base64_encode($pdf->stream()),
                'role' => $this->getRole()
            ]);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            Log::error('Penerimaan bahan not found', ['penerimaan_bahan_id' => $penerimaanBahanId, 'item_id' => $itemId, 'error' => $e->getMessage(), 'user_id' => auth()->id()]);
            return response()->json(['error' => 'Penerimaan bahan not found'], 404);
        } catch (\Exception $e) {
            Log::error('Failed to generate PDF for penerimaan bahan detail', ['penerimaan_bahan_id' => $penerimaanBahanId, 'item_id' => $itemId, 'error' => $e->getMessage(), 'user_id' => auth()->id()]);
            return response()->json(['error' => 'Failed to generate PDF'], 500);
        }
    }

    public function summary($dateStart, $dateEnd)
    {
        try {
            $penerimaanBahans = DB::table("processing_penerimaan_bahan_details as x")
            ->join("processing_penerimaan_bahan as y","x.penerimaan_bahan_id","=","y.id")
            ->join("processing_plans as pp","pp.id", "=", "y.plan_id")
            ->join("process as pr","pr.id", "=", "y.process_id")
            ->join("items as i","i.id", "=", "x.item_id")
            ->join("item_units as iu","iu.id", "=", DB::raw("cast(x.unit as bigint)"))
            ->whereBetween("y.document_date",[$dateStart, $dateEnd])
            ->select("i.item_name",DB::raw("sum(x.qty) qty"),"iu.unit_name",
            "pp.plan_id","pr.process_name","pp.production_start_date","pp.production_end_date")
            ->groupBy("i.item_name","iu.unit_name",
            "pp.plan_id","pr.process_name","pp.production_start_date","pp.production_end_date")
            ->get();
            return response()->json(["penerimaanBahans" => $penerimaanBahans, "role" => $this->getRole()], 200);
        } catch (\Exception $e) {
            dd($e->getMessage());
            \Log::error('Summary Error', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'user_id' => Auth::id()
            ]);
            return response()->json(['error' => 'Failed to fetch material receipts summary'], 500);
        }
    }

    public function summaryDetail($dateStart, $dateEnd)
    {
        try {
            $penerimaanBahanDetails = DB::table("processing_penerimaan_bahan_details as x")
            ->join("processing_penerimaan_bahan as y","x.penerimaan_bahan_id","=","y.id")
            ->join("processing_plans as pp","pp.id", "=", "y.plan_id")
            ->leftjoin("process as pr","pr.id", "=", "y.process_id")
            ->leftjoin("items as i","i.id", "=", "x.item_id")
            ->leftjoin("item_units as iu","iu.id", "=", DB::raw("cast(x.unit as bigint)"))
            ->leftjoin("warehouse as wh","wh.id", "=", "y.warehouse_id")
            ->whereBetween("y.document_date",[$dateStart, $dateEnd])
            ->select("y.penerimaan_bahan_id as document_number","y.document_date","i.item_name","x.item_date","x.qty","iu.unit_name",
            "pp.plan_id","pr.process_name","wh.warehouse_name")
            ->get();

            return response()->json(["penerimaanBahanDetails" => $penerimaanBahanDetails, "role" => $this->getRole()], 200);
        } catch (\Exception $e) {
            \Log::error('Summary Detail Error', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'user_id' => Auth::id()
            ]);
            return response()->json(['error' => 'Failed to fetch material receipts detail summary'], 500);
        }
    }

    public function reCalc(){
        $data = DB::table("processing_penerimaan_bahan")->get();
        DB::beginTransaction();
        try {
            $company = Company::first();
            $department = Department::where('department_code','PRO001')->first();
            foreach($data as $dat){
                $penerimaanBahan = ProcessingPenerimaanBahan::find($dat->id);

                $det = DB::table("processing_penerimaan_bahan_details")->where("penerimaan_bahan_id",$penerimaanBahan->id)->get();
                Journal::where("document_number",$penerimaanBahan->penerimaan_bahan_id)->delete();

                foreach ($det as $detail) {
                    $itemDetail = ItemDetail::where("item_id", $detail->item_id)->where("unit_id", $detail->unit)->first();

                    //$cogs = Module::getCogs($penerimaanBahan->document_date,$detail->item_id,$company->companyCode,$department->id,$penerimaanBahan->warehouse_id);
                    // DB::table('inventory_details')->insert([
                    //     'document_number' => $kasirPengeluaranBahan->kasir_pengeluaran_bahan_number,
                    //     'document_date' => $kasirPengeluaranBahan->document_date,
                    //     'transaction_type' => 'Kasir Production Penggunaan Bahan',
                    //     'warehouse_id' => $kasirPengeluaranBahan->warehouse_id,
                    //     'item_id' => $detail->item_id,
                    //     'quantity' => $detail->qty,
                    //     'unit' => $detail->unit,
                    //     'base_quantity' => $itemDetail->conversion,
                    //     'unit_base' => $itemDetail->item->base_unit_id,
                    //     'department_id' => $department->id,
                    //     'company_code' => $company->companyCode,
                    //     'total' => $cogs * $detail->qty * $itemDetail->conversion,
                    //     'cogs' => $cogs * $detail->qty * $itemDetail->conversion,
                    //     'qty_actual' => $detail->qty,
                    //     'created_by' => Auth::user()->id,
                    //     'updated_by' => Auth::user()->id,
                    //     'created_at' => now(),
                    //     'updated_at' => now(),
                    // ]);

                    $ambilCogs = DB::table("inventory_details")->where("document_number",$penerimaanBahan->penerimaan_bahan_id)
                    ->where("item_id",$detail->item_id)->where("unit",$detail->unit)
                    ->where("base_quantity",$itemDetail->conversion)->first();

                    $it = Item::find($detail->item_id);
                    if($it){
                        $accWip = $it->categoryItem->acc_number_wip;
                        Journal::create([
                            'document_number' => $penerimaanBahan->penerimaan_bahan_id,
                            'document_date' => $penerimaanBahan->document_date,
                            'account_number' => $accWip,
                            'notes' => 'Persediaan dalam WIP: ' . $it->item_name,
                            'debet_nominal' => $ambilCogs->cogs,
                            'credit_nominal' => 0,
                            'debet_nominal_base' => $ambilCogs->cogs,
                            'credit_nominal_base' => 0,
                            'company_code' => $company->companyCode,
                            'department_id' => $department->id,
                            'created_by' => Auth::user()->id,
                            'updated_by' => Auth::user()->id,
                        ]);
                        
                        Journal::create([
                            'document_number' => $penerimaanBahan->penerimaan_bahan_id,
                            'document_date' => $penerimaanBahan->document_date,
                            'account_number' => $it->categoryItem->account_inventory,
                            'notes' => 'Persediaan: ' . $it->item_name,
                            'debet_nominal' => 0,
                            'credit_nominal' => $ambilCogs->cogs,
                            'debet_nominal_base' => 0,
                            'credit_nominal_base' => $ambilCogs->cogs,
                            'company_code' => $company->companyCode,
                            'department_id' => $department->id,
                            'created_by' => Auth::user()->id,
                            'updated_by' => Auth::user()->id,
                        ]);
                    }
                }
            }
            DB::commit();
            return response()->json(null);
        } catch (\Exception $e) {
            DB::rollback();
            return response()->json(['error' => 'Server error'], 500);
        }
    }
}
