<?php

    namespace Modules\Lpj\Http\Controllers;

    use App\Http\Controllers\Controller;
    use Exception;
    use Illuminate\Http\Request;
    use Illuminate\Http\JsonResponse;
    use Illuminate\Support\Collection;
    use Illuminate\Support\Facades\DB;
    use Illuminate\Support\Facades\Storage;
    use Illuminate\Http\UploadedFile;
    use Log;
    use Modules\Location\Models\City;
    use Modules\Location\Models\District;
    use Modules\Location\Models\Province;
    use Modules\Location\Models\Village;
    use Modules\Lpj\Http\Requests\DokumenJaminanRequest;
    use Modules\Lpj\Models\CustomField;
    use Modules\Lpj\Models\Debiture;
    use Modules\Lpj\Models\DetailDokumenJaminan;
    use Modules\Lpj\Models\DokumenJaminan;
    use Modules\Lpj\Models\HubunganPemilikJaminan;
    use Modules\Lpj\Models\JenisJaminan;
    use Modules\Lpj\Models\JenisLegalitasJaminan;
    use Modules\Lpj\Models\PemilikJaminan;
    use Modules\Lpj\Models\Permohonan;
    use ZipArchive;

    class DokumenJaminanController extends Controller
    {
        public $user;


        public function index($id)
        {
            $debitur   = Debiture::find($id);
            $documents = DokumenJaminan::with('pemilik', 'detail')->where('debiture_id', $id)->get();
            if (request()->get('permohonan_id') !== null) {
                $permohonan_id = request()->get('permohonan_id');
                $documents     = DokumenJaminan::with('pemilik', 'detail')
                                               ->where('debiture_id', $id)
                                               ->where('permohonan_id', $permohonan_id)
                                               ->get();
            }

            return view(
                'lpj::debitur.edit',
                compact('debitur', 'documents'),
            );
        }

        public function store(DokumenJaminanRequest $request, $id)
        {
            $debitur = Debiture::find($id);

            $validate = $request->validated();

            if ($validate) {
                try {
                    DB::beginTransaction();
                    $validate['debiture_id'] = $id;

                    if ($validate['pemilik_jaminan_id'] == 0) {
                        $pemilik_jaminan = [
                            'hubungan_pemilik_jaminan_id' => 1,
                            'npwp'                        => $debitur->npwp,
                            'email'                       => $debitur->email,
                            'phone'                       => $debitur->phone,
                            'province_code'               => $debitur->province_code,
                            'city_code'                   => $debitur->city_code,
                            'district_code'               => $debitur->district_code,
                            'village_code'                => $debitur->village_code,
                            'postal_code'                 => $debitur->postal_code,
                            'address'                     => $debitur->address,
                        ];

                        $pemilikJaminan                 = PemilikJaminan::updateOrCreate([
                            'debiture_id' => $id,
                            'name'        => $debitur->name,
                        ], $pemilik_jaminan);
                        $validate['pemilik_jaminan_id'] = $pemilikJaminan->id;
                    }

                    $document = DokumenJaminan::create($validate);

                    if ($request->jenis_legalitas_jaminan_id) {
                        foreach ($request->jenis_legalitas_jaminan_id as $key => $value) {
                            $detailData = [
                                'dokumen_jaminan_id'         => $document->id,
                                'jenis_legalitas_jaminan_id' => $value,
                                'name'                       => $request->name[$key],
                                'keterangan'                 => $request->keterangan[$key],
                                'details'                    => isset($request->custom_field[$key]) ? json_encode($request->custom_field[$key]) : ''
                            ];

                            $dokumenJaminan = [];
                            $dokumenNomor   = [];
                            if (isset($request->dokumen_jaminan[$key]) && is_array($request->dokumen_jaminan[$key])) {
                                foreach ($request->dokumen_jaminan[$key] as $index => $file) {
                                    if ($file) {
                                        $file_name = $file->getClientOriginalName();
                                        $file->storeAs(
                                            'public/jaminan/' . $debitur->id . '/' . $document->id . '/',
                                            $file_name,
                                        );
                                        $dokumenJaminan[] = 'jaminan/' . $debitur->id . '/' . $document->id . '/' . $file_name;
                                        $dokumenNomor[]   = $request->dokumen_nomor[$key][$index] ?? '-';
                                    }
                                }
                            }

                            if (!empty($dokumenJaminan)) {
                                $detailData['dokumen_jaminan'] = json_encode($dokumenJaminan);
                                $detailData['dokumen_nomor']   = json_encode($dokumenNomor);
                            }

                            DetailDokumenJaminan::create($detailData);
                        }
                    }

                    DB::commit();
                    return redirect()->route('debitur.jaminan.index',['id'=>$id,'pemrohonan_id' => $validate['permohonan_id'] ])->with(
                        'success',
                        'Dokumen Jaminan berhasil ditambahkan',
                    );
                } catch (Exception $e) {
                    DB::rollBack();
                    return redirect()->route('debitur.jaminan.create',['id'=>$id,'pemrohonan_id' => $validate['permohonan_id'] ])->with('error', $e->getMessage());
                }
            }
        }

        public function create($id)
        {
            $debitur               = Debiture::find($id);
            $provinces             = Province::all();
            $jenisJaminan          = JenisJaminan::all();
            $jenisLegalitasJaminan = JenisLegalitasJaminan::all();
            $pemilikJaminan        = PemilikJaminan::where('debiture_id', $id)->get();
            $hubunganPemilik       = HubunganPemilikJaminan::all();
            $permohonan = null;
            if(request()->get('permohonan_id')) {
                $permohonan = Permohonan::where('id', request()->get('permohonan_id'))->first();
            }
            return view(
                'lpj::debitur.jaminan',
                compact(
                    'debitur',
                    'provinces',
                    'jenisJaminan',
                    'jenisLegalitasJaminan',
                    'pemilikJaminan',
                    'hubunganPemilik',
                    'permohonan'
                ),
            );
        }

        public function update(DokumenJaminanRequest $request, $id, $jaminan)
        {
            $debitur = Debiture::find($id);

            $validate = $request->validated();
            if ($validate) {
                try {
                    DB::beginTransaction();
                    $validate['debiture_id'] = $id;

                    if ($validate['pemilik_jaminan_id'] == 00) {
                        $pemilik_jaminan = [
                            'hubungan_pemilik_jaminan_id' => request()->get('hubungan_pemilik_jaminan_id'),
                            'province_code'               => $debitur->province_code,
                            'city_code'                   => $debitur->city_code,
                            'district_code'               => $debitur->district_code,
                            'village_code'                => $debitur->village_code,
                            'postal_code'                 => $debitur->postal_code,
                            'address'                     => $debitur->address,
                            'nomor_id'                    => request()->get('nomor_id'),
                            'name'                        => request()->get('pemilik_name'),
                        ];

                        $detailSertifikat = [];
                        $names            = request()->input('detail_sertifikat.name', []);
                        $nomorIds         = request()->input('detail_sertifikat.nomor_id', []);

                        foreach ($names as $index => $name) {
                            if (isset($nomorIds[$index])) {
                                $detailSertifikat[] = [
                                    'name'     => $name,
                                    'nomor_id' => $nomorIds[$index],
                                ];
                            }
                        }

                        $pemilik_jaminan['detail_sertifikat'] = json_encode($detailSertifikat);

                        //dd($pemilik_jaminan);

                        try {
                            $pemilikJaminan = PemilikJaminan::updateOrCreate([
                                'debiture_id' => $id,
                                'name'        => request()->get('pemilik_name'),
                            ], $pemilik_jaminan);
                        } catch (Exception $e) {
                            return redirect()->route('debitur.jaminan.index', $id)->with(
                                'error',
                                'Gagal update pemilik jaminan: ' . $e->getMessage(),
                            );
                        }

                        $validate['pemilik_jaminan_id'] = $pemilikJaminan->id;
                    }


                    if ($validate['pemilik_jaminan_id'] == 0) {
                        $pemilik_jaminan = [
                            'hubungan_pemilik_jaminan_id' => 1,
                            'npwp'                        => $debitur->npwp,
                            'email'                       => $debitur->email,
                            'phone'                       => $debitur->phone,
                            'province_code'               => $debitur->province_code,
                            'city_code'                   => $debitur->city_code,
                            'district_code'               => $debitur->district_code,
                            'village_code'                => $debitur->village_code,
                            'postal_code'                 => $debitur->postal_code,
                            'address'                     => $debitur->address,
                        ];

                        $pemilikJaminan = PemilikJaminan::updateOrCreate([
                            'debiture_id' => $id,
                            'name'        => $debitur->name,
                        ], $pemilik_jaminan);

                        $validate['pemilik_jaminan_id'] = $pemilikJaminan->id;
                    }

                    $document = DokumenJaminan::find($jaminan);
                    $document->update($validate);

                    // Get existing detail documents
                    $existingDetails = DetailDokumenJaminan::where('dokumen_jaminan_id', $document->id)->get()->keyBy(
                        'id',
                    );

                    if ($request->jenis_legalitas_jaminan_id) {
                        foreach ($request->jenis_legalitas_jaminan_id as $key => $value) {
                            $detailData = [
                                'dokumen_jaminan_id'         => $document->id,
                                'jenis_legalitas_jaminan_id' => $value,
                                'name'                       => $request->name[$key],
                                'keterangan'                 => $request->keterangan[$key],
                                'details' => isset($request->custom_field[$key]) ? json_encode(array_values($request->custom_field[$key])) : ''
                            ];

                            $dokumenJaminan = [];
                            $dokumenNomor   = [];

                            if (isset($request->dokumen_jaminan[$key]) && is_array($request->dokumen_jaminan[$key])) {
                                foreach ($request->dokumen_jaminan[$key] as $index => $file) {
                                    if ($file instanceof \Illuminate\Http\UploadedFile) {
                                        // Jika file baru diupload
                                        $file_name = $file->getClientOriginalName();
                                        $file->storeAs(
                                            'public/jaminan/' . $debitur->id . '/' . $document->id . '/',
                                            $file_name,
                                        );
                                        $dokumenJaminan[] = 'jaminan/' . $debitur->id . '/' . $document->id . '/' . $file_name;
                                    }  elseif (is_string($file) && !empty($file)) {
                                        // Jika file tidak diubah, gunakan path yang sudah ada
                                        $dokumenJaminan[] = $file;
                                    } else {
                                        // Jika file kosong atau null, tambahkan placeholder atau skip
                                        $dokumenJaminan[] = null; // atau skip dengan continue;
                                    }

                                    // Selalu update dokumen_nomor, baik file diubah atau tidak
                                    $dokumenNomor[] = $request->dokumen_nomor[$key][$index] ?? '-';
                                }
                            }


                            // Setelah loop, periksa apakah ada dokumen yang dihapus
                            $existingDetail = $existingDetails->get($request->detail_dokumen_jaminan_id[$key] ?? null);

                            if ($existingDetail) {
                                $existingDokumen = json_decode($existingDetail->dokumen_jaminan, true) ?? [];
                                $existingNomor = json_decode($existingDetail->dokumen_nomor, true) ?? [];

                                $newDokumenJaminan = [];
                                $newDokumenNomor = [];

                                $allFilesDeleted = true;

                                foreach ($existingDokumen as $index => $existingFile) {
                                    if (isset($request->dokumen_jaminan[$key][$index])) {
                                        $allFilesDeleted = false;
                                        $file = $request->dokumen_jaminan[$key][$index];
                                        if ($file instanceof \Illuminate\Http\UploadedFile) {
                                            // File baru diupload
                                            $file_name = $file->getClientOriginalName();
                                            $file->storeAs('public/jaminan/' . $debitur->id . '/' . $document->id . '/', $file_name);
                                            $newDokumenJaminan[] = 'jaminan/' . $debitur->id . '/' . $document->id . '/' . $file_name;
                                            $newDokumenNomor[] = $request->dokumen_nomor[$key][$index] ?? '-';
                                        } elseif (is_string($file) && !empty($file)) {
                                            // File tidak diubah
                                            $newDokumenJaminan[] = $existingFile;
                                            $newDokumenNomor[] = $request->dokumen_nomor[$key][$index] ?? $existingNomor[$index];
                                        }
                                    } else {
                                        // File dihapus, hapus dari storage jika ada
                                        if (Storage::exists('public/' . $existingFile)) {
                                            Storage::delete('public/' . $existingFile);
                                        }
                                    }
                                }

                                // Tambahkan file baru yang mungkin ditambahkan
                                foreach ($request->dokumen_jaminan[$key] ?? [] as $index => $file) {
                                    if ($file instanceof UploadedFile) {
                                        $allFilesDeleted = false;
                                        $file_name = $file->getClientOriginalName();
                                        $path = 'jaminan/' . $debitur->id . '/' . $document->id . '/' . $file_name;
                                        if (!in_array($path, $newDokumenJaminan)) {
                                            $file->storeAs('public/' . dirname($path), $file_name);
                                            $newDokumenJaminan[] = $path;
                                            $newDokumenNomor[] = $request->dokumen_nomor[$key][$index] ?? '-';
                                        }
                                    } elseif (is_string($file) && !empty($file) && !in_array($file, $newDokumenJaminan)) {
                                        $allFilesDeleted = false;
                                        $newDokumenJaminan[] = $file;
                                        $newDokumenNomor[] = $request->dokumen_nomor[$key][$index] ?? '-';
                                    }
                                }

                                if ($allFilesDeleted) {
                                    $dokumenJaminan = [];
                                    $dokumenNomor = [];
                                } else {
                                    $dokumenJaminan = $newDokumenJaminan;
                                    $dokumenNomor = $newDokumenNomor;
                                }
                            }



                            if (!empty($dokumenJaminan)) {
                                $detailData['dokumen_jaminan'] = json_encode($dokumenJaminan);
                                $detailData['dokumen_nomor'] = json_encode($dokumenNomor);
                            } else if(empty($dokumenJaminan)){
                                $detailData['dokumen_jaminan'] = null;
                                $detailData['dokumen_nomor'] = null;
                            }

                            if (isset($request->detail_dokumen_jaminan_id[$key])) {
                                $detailId       = $request->detail_dokumen_jaminan_id[$key];
                                $detailDocument = $existingDetails->get($detailId);
                                $detailDocument->update($detailData);

                            } else {
                                DetailDokumenJaminan::create($detailData);
                            }
                        }
                    }

                    DB::commit();
                    return redirect()->route('debitur.jaminan.index', $id)->with(
                        'success',
                        'Dokumen Jaminan berhasil diubah',
                    );
                } catch (Exception $e) {
                    DB::rollBack();
                    return redirect()->route('debitur.jaminan.index', $id)->with('error', $e->getMessage());
                }
            }
        }

        public function edit(
            $id,
            $jaminan,
        )
        {
            $document = DokumenJaminan::find($jaminan);
            $details  = DetailDokumenJaminan::where('dokumen_jaminan_id', $document->id)->get();

            $debitur   = Debiture::find($document->debiture_id);
            $provinces = Province::all();
            $cities    = City::where('province_code', $document->province_code)->get();
            $districts = District::where('city_code', $document->city_code)->get();
            $villages  = Village::where('district_code', $document->district_code)->get();


            $jenisJaminan          = JenisJaminan::all();
            $jenisLegalitasJaminan = JenisLegalitasJaminan::all();

            $_jenisJaminan = JenisJaminan::find($document->jenis_jaminan_id);

            $legalitas     = '';
            if ($_jenisJaminan) {
                $legalitasJaminan = json_decode($_jenisJaminan->jenis_legalitas_jaminan_id, true);

                $currentLegalitasJaminan = JenisLegalitasJaminan::whereIn(
                    'id',
                    $document->detail->pluck('jenis_legalitas_jaminan_id')->toArray(),
                )->get();


                // Remove values from $legalitasJaminan that are in $currentLegalitasJaminan
                $legalitasJaminan = is_array($legalitasJaminan)
                ? array_diff($legalitasJaminan, $currentLegalitasJaminan->pluck('code')->toArray())
                : [];

                $legalitas = JenisLegalitasJaminan::whereIn('code', $legalitasJaminan)->get();
            }

            $pemilikJaminan  = PemilikJaminan::where('debiture_id', $document->debiture_id)->get();
            $hubunganPemilik = HubunganPemilikJaminan::all();

            return view(
                'lpj::debitur.jaminan',
                compact(
                    'debitur',
                    'provinces',
                    'jenisJaminan',
                    'jenisLegalitasJaminan',
                    'document',
                    'details',
                    'cities',
                    'districts',
                    'villages',
                    'pemilikJaminan',
                    'hubunganPemilik',
                    'legalitas',
                ),
            );
        }

        public function destroy(
            $id,
            $jaminan_id,
        )
        {
            try {
                // Periksa apakah pengguna adalah admin
                if (!auth()->user()->hasRole('administrator')) {
                    //return response()->json(['success' => false, 'message' => 'Hanya administrator yang dapat menghapus dokumen jaminan'], 403);
                }

                $jaminan = DokumenJaminan::find($jaminan_id);

                if (!$jaminan) {
                    return response()->json(['success' => false, 'message' => 'Dokumen Jaminan tidak ditemukan'], 404);
                }

                // Periksa apakah dokumen jaminan terkait dengan permohonan aktif
                if ($jaminan->permohonan()->exists() && !in_array($jaminan->permohonan->status,['order','revisi'])) {
                   // return response()->json(['success' => false, 'message' => 'Tidak dapat menghapus dokumen jaminan yang terkait dengan permohonan aktif'], 400);
                }

                DB::beginTransaction();

                $details = DetailDokumenJaminan::where('dokumen_jaminan_id', $jaminan->id)->get();
                foreach ($details as $detail) {
                    Storage::delete('public/' . $detail->dokumen_jaminan);
                    $detail->delete();
                }
                $jaminan->delete();

                DB::commit();

                return response()->json(['success' => true, 'message' => 'Dokumen Jaminan berhasil dihapus']);
            } catch (Exception $e) {
                DB::rollBack();
                return response()->json(['success' => false, 'message' => 'Gagal menghapus Dokumen Jaminan: ' . $e->getMessage()], 500);
            }
        }

        public function bulkDownload()
        {
            $dokumenIds = request()->get('jaminan'); // Expecting an array of dokumen_jaminan_id
            $documents  = DokumenJaminan::where('id', $dokumenIds)->with(['jenisJaminan', 'detail', 'debiture'])->get();

            if ($documents->isEmpty()) {
                return redirect()->back()->with('error', 'No documents found for the provided IDs.');
            }

            $zip         = new ZipArchive;
            $zipFileName = 'documents_jaminan_' . $dokumenIds . '.zip';
            $zipFilePath = storage_path('app/public/' . $zipFileName);

            if ($zip->open($zipFilePath, ZipArchive::CREATE) === true) {
                foreach ($documents as $document) {
                    $jenisJaminan = $document->permohonan->nomor_registrasi ?? 'Uncategorized';
                    $folderName   = $this->sanitizeFolderName($jenisJaminan);

                    foreach ($document->detail as $detail) {
                        if ($detail->dokumen_jaminan) {
                            $folderJaminanName = $this->sanitizeFolderName($detail->jenisLegalitasJaminan->name ?? 'Uncategorized');
                            $files             = is_array(json_decode($detail->dokumen_jaminan))
                                ? json_decode($detail->dokumen_jaminan)
                                : [$detail->dokumen_jaminan];

                            foreach ($files as $file) {
                                $filePath = storage_path('app/public/' . $file);
                                if (file_exists($filePath)) {
                                    $zip->addFile($filePath, $folderName . '/' . $folderJaminanName . '/' . basename($filePath));
                                } else {
                                    // Log or display an error message for missing files
                                    Log::warning('File not found: ' . $filePath);
                                }
                            }
                        }
                    }
                }
                $zip->close();

                if (!file_exists($zipFilePath)) {
                    return redirect()->back()->with('error', 'Failed to create ZIP file.');
                }
            } else {
                return redirect()->back()->with('error', 'Failed to create ZIP file.');
            }

            return response()->download($zipFilePath, $zipFileName, [
                'Content-Type'        => 'application/zip',
                'Content-Disposition' => 'attachment; filename="' . $zipFileName . '"',
                'Content-Length'      => filesize($zipFilePath),
            ])->deleteFileAfterSend(true);
        }

        private function sanitizeFolderName($name)
        {
            // Remove any characters that are not allowed in folder names
            return preg_replace('/[^a-zA-Z0-9_\-]/', '_', $name);
        }


        public function download()
        {
            $dokumen  = request()->get('dokumen');
            $document = DetailDokumenJaminan::find($dokumen);
            $file     = is_array(json_decode($document->dokumen_jaminan)) ? json_decode(
                $document->dokumen_jaminan,
            ) : [$document->dokumen_jaminan];
            return response()->download(storage_path('app/public/' . $file[request()->get('index')]));
        }

        public function legalitasJaminan($id)
        {
            $jenisJaminan     = JenisJaminan::find($id);
            $legalitasJaminan = $jenisJaminan->jenis_legalitas_jaminan_id;

            $legalitas = JenisLegalitasJaminan::whereIn('code', json_decode($legalitasJaminan, true))->get();
            echo json_encode($legalitas);
        }


        public function getLegalitasJaminan($id = 10, $jenisJaminanId = 1)
        : JsonResponse
        {
            $jenisJaminan        = JenisJaminan::findOrFail($jenisJaminanId);
            $legalitasJaminan    = $jenisJaminan->jenis_legalitas_jaminan_id;
            $newLegalitasJaminan = JenisLegalitasJaminan::whereIn('code', json_decode($legalitasJaminan, true))->get();

            $existingLegalitas = [];
            $newLegalitas      = [];

            // Create a set of new jenis_legalitas_jaminan_ids for quick lookup
            $newLegalitasIds = $newLegalitasJaminan->pluck('id')->toArray();

            if ($id > 0) {
                $document = DokumenJaminan::findOrFail($id);
                if ($document && $document->detail) {
                    foreach ($document->detail as $detail) {
                        // Only include existing legalitas if its id is in the new set
                        if (in_array($detail->jenis_legalitas_jaminan_id, $newLegalitasIds)) {
                            $customFields = [];
                            if($detail->jenisLegalitasJaminan->custom_fields) {
                                $customFields = CustomField::whereIn('id', $detail->jenisLegalitasJaminan->custom_fields)
                                                           ->get();
                            }

                            $existingLegalitas[] = [
                                'id'                         => $detail->id,
                                'jenis_legalitas_jaminan_id' => $detail->jenis_legalitas_jaminan_id,
                                'name'                       => $detail->jenisLegalitasJaminan->name,
                                'dokumen_jaminan'            => json_decode(
                                        $detail->dokumen_jaminan,
                                    ) ?? $detail->dokumen_jaminan,
                                'dokumen_nomor'              => json_decode(
                                        $detail->dokumen_nomor,
                                    ) ?? $detail->dokumen_nomor,
                                'custom_field'               => $detail->jenisLegalitasJaminan->custom_field,
                                'custom_fields'               => $customFields,
                                'custom_field_type'          => $detail->jenisLegalitasJaminan->custom_field_type,
                                'details'                    => $detail->details,
                                'keterangan'                 => $detail->keterangan,
                                'is_existing'                => true,
                            ];
                        }
                    }
                }
            }

            foreach ($newLegalitasJaminan as $legalitas) {
                if (!Collection::make($existingLegalitas)->contains('jenis_legalitas_jaminan_id', $legalitas->id)) {
                    $customFields = [];
                    if($legalitas->custom_fields) {
                        $customFields = CustomField::whereIn('id', $legalitas->custom_fields)->get();
                    }

                    $newLegalitas[] = [
                        'id'                         => null,
                        'jenis_legalitas_jaminan_id' => $legalitas->id,
                        'name'                       => $legalitas->name,
                        'dokumen_jaminan'            => null,
                        'dokumen_nomor'              => null,
                        'custom_field'               => $legalitas->custom_field,
                        'custom_field_type'          => $legalitas->custom_field_type,
                        'custom_fields'               => $customFields,
                        'details'                    => null,
                        'keterangan'                 => null,
                        'is_existing'                => false,
                    ];
                }
            }

            $combinedLegalitas = array_merge($existingLegalitas, $newLegalitas);
            return response()->json($combinedLegalitas);
        }

        public function clearDetail(Request $request)
        {
            try {
                DB::beginTransaction();

                $detailId = $request->input('detail_id');
                $detail   = DetailDokumenJaminan::findOrFail($detailId);

                // Delete associated files
                if ($detail->dokumen_jaminan) {
                    $dokumen_jaminan = is_array(json_decode($detail->dokumen_jaminan))
                        ? json_decode($detail->dokumen_jaminan)
                        : [$detail->dokumen_jaminan];

                    foreach ($dokumen_jaminan as $dokumen) {
                        if (Storage::exists($dokumen)) {
                            Storage::delete($dokumen);
                        }
                    }
                }

                // Delete the detail record
                $detail->delete();

                DB::commit();

                return response()->json(['success' => true, 'message' => 'Detail berhasil dihapus']);
            } catch (\Exception $e) {
                DB::rollBack();
                return response()->json([
                    'success' => false,
                    'message' => 'Gagal menghapus detail: ' . $e->getMessage()
                ], 500);
            }
        }
    }
