From ec247a70ab112d6e0a201e1b775d023d8f065ca5 Mon Sep 17 00:00:00 2001 From: Daeng Deni Mardaeni Date: Wed, 1 Jan 2025 22:00:51 +0700 Subject: [PATCH] Refactor Surveyor module and update form handling - Ubah ID elemen HTML di halaman Surveyor - Perbarui textarea dan validasi terkait dengan "alasan" - Refaktor dan optimalkan code untuk SurveyorController - Tambahkan konstanta, properti, dan metode baru untuk mengatur inspeksi, denah, serta data permohonan - Perbaiki struktur data dengan menambah model dan atribut terkait --- app/Http/Controllers/SurveyorController.php | 5470 ++++++++++--------- resources/views/surveyor/index.blade.php | 12 +- 2 files changed, 2762 insertions(+), 2720 deletions(-) diff --git a/app/Http/Controllers/SurveyorController.php b/app/Http/Controllers/SurveyorController.php index 16f0e2e..994c3e8 100644 --- a/app/Http/Controllers/SurveyorController.php +++ b/app/Http/Controllers/SurveyorController.php @@ -1,1697 +1,152 @@ findOrFail($id); - - $surveyor = $id; - $branches = Branch::all(); - $provinces = Province::all(); - $bentukTanah = BentukTanah::all(); - - // Get all inspeksi data for this permohonan - $inspeksiData = Inspeksi::where('permohonan_id', $id) - ->get() - ->keyBy('dokument_id') - ->map(function ($item) { - return [ - 'data_form' => json_decode($item->data_form, true), - 'foto_form' => json_decode($item->foto_form, true), - 'denah_form' => json_decode($item->denah_form, true), - 'data_pembanding' => json_decode($item->data_pembanding, true), - ]; - }); - - - return view('lpj::surveyor.detail', compact( - 'permohonan', - 'surveyor', - 'branches', - 'provinces', - 'bentukTanah', - 'inspeksiData' - )); - } - - /** - * Store form inspeksi. - */ - public function store(FormSurveyorRequest $request) - { - try { - // Validate request data - $validatedData = $request->validated(); - - // Get action specific rules and process data - $processedData = $this->getActionSpecificRules( - $validatedData, - $request->input('type'), - $request - ); - - // Find or create inspeksi record - $inspeksi = Inspeksi::updateOrCreate( - [ - 'permohonan_id' => $request->input('permohonan_id'), - 'dokument_id' => $request->input('dokument_id') - ], - [ - 'data_form' => json_encode($processedData), - 'name' => $request->input('type') - ] - ); - - return response()->json([ - 'success' => true, - 'message' => 'Data berhasil disimpan', - 'data' => $processedData - ], 200); - - } catch (\Exception $e) { - return response()->json([ - 'success' => false, - 'message' => 'Gagal menyimpan data', - 'error' => $e->getMessage() - ], 500); - } - } - - private function getActionSpecificRules($data, $action, $request): array - { - $allowedActions = [ - 'apartemen-kantor' => 'getUnitData', - 'tanah' => 'getTanahData', - 'bangunan' => 'getBangunanData', - 'kapal' => 'getKapalData', - 'kendaraan' => 'getKendaraanData', - 'mesin' => 'getMesinData', - 'pesawat' => 'getPesawatData', - 'alat-berat' => 'getAlatBeratData', - 'lingkungan' => 'getLingkunganData', - 'fakta' => 'getFactData' + private const HEADERS = [ + 'bentuk-tanah' => ['Bentuk Tanah', 'bentuk-tanah'], + 'kontur-tanah' => ['Kontur Tanah', 'kontur-tanah'], + 'posisi-kavling' => ['Posisi Kavling', 'posisi-kavling'], + 'ketinggian-tanah' => ['Ketinggian Tanah', 'ketinggian-tanah'], + 'kondisi-fisik-tanah' => ['Kondisi Fisik Tanah', 'kondisi-fisik-tanah'], + 'jenis-bangunan' => ['Jenis Bangunan', 'jenis-bangunan'], + 'kondisi-bangunan' => ['Kondisi Bangunan', 'kondisi-bangunan'], + 'sifat-bangunan' => ['Sifat Bangunan', 'sifat-bangunan'], + 'sarana-pelengkap' => ['Sarana Pelengkap', 'sarana-pelengkap'], + 'lalu-lintas-lokasi' => ['Lalu Lintas Depan Lokasi', 'lalu-lintas-lokasi'], + 'tingkat-keramaian' => ['Tingkat Keramaian', 'tingkat-keramaian'], + 'gol-mas-sekitar' => ['Golongan Masyarakat Sekitar', 'gol-mas-sekitar'], + 'spek-kategori-bangunan' => ['Spek Kategori Bangunan', 'spek-kategori-bangunan'], + 'spek-bangunan' => ['Spek Bangunan', 'spek-bangunan'], + 'lantai-unit' => ['Lantai Unit', 'lantai-unit'], + 'view-unit' => ['View Unit', 'view-unit'], + 'perkerasan-jalan' => ['Perkerasan jalan', 'perkerasan-jalan'], + 'jenis-pesawat' => ['Jenis pesawat', 'jenis-pesawat'], + 'model-alat-berat' => ['Model alat berat', 'model-alat-berat'], + 'jenis-kapal' => ['Jenis kapal', 'jenis-kapal'], + 'jenis-kendaraan' => ['Jenis kendaraan', 'jenis-kendaraan'], + 'jenis-unit' => ['Jenis unit', 'jenis-unit'], + 'terletak-area' => ['Terletak di Area', 'terletak-area'], + 'merupakan-daerah' => ['Merupakan Daerah', 'merupakan-daerah'], + 'posisi-unit' => ['Posisi unit', 'posisi-unit'], + 'bentuk-unit' => ['Bentuk unit', 'bentuk-unit'], + 'fasilitas-objek' => ['Fasilitas Umum Dekat Objek', 'fasilitas-objek'], + 'foto-objek-jaminan' => ['Foto Objek Jaminan', 'foto-objek-jaminan'], + ]; + public $user; + private $modelClasses = [ + 'bentuk-tanah' => BentukTanah::class, + 'kontur-tanah' => KonturTanah::class, + 'posisi-kavling' => PosisiKavling::class, + 'ketinggian-tanah' => KetinggianTanah::class, + 'kondisi-fisik-tanah' => KondisiFisikTanah::class, + 'jenis-bangunan' => JenisBangunan::class, + 'kondisi-bangunan' => KondisiBangunan::class, + 'sifat-bangunan' => SifatBangunan::class, + 'sarana-pelengkap' => SaranaPelengkap::class, + 'lalu-lintas-lokasi' => LaluLintasLokasi::class, + 'tingkat-keramaian' => TingkatKeramaian::class, + 'gol-mas-sekitar' => GolonganMasySekitar::class, + 'spek-kategori-bangunan' => SpekKategoritBangunan::class, + 'spek-bangunan' => SpekBangunan::class, + 'lantai-unit' => Lantai::class, + 'view-unit' => ViewUnit::class, + 'jenis-pesawat' => JenisPesawat::class, + 'model-alat-berat' => ModelAlatBerat::class, + 'jenis-kapal' => JenisKapal::class, + 'jenis-kendaraan' => JenisKendaraan::class, + 'terletak-area' => TerletakArea::class, + 'posisi-unit' => PosisiUnit::class, + 'bentuk-unit' => BentukUnit::class, + 'fasilitas-objek' => FasilitasObjek::class, + 'merupakan-daerah' => MerupakanDaerah::class, + 'jenis-unit' => JenisUnit::class, + 'perkerasan-jalan' => PerkerasanJalan::class, + 'foto-objek-jaminan' => FotoObjekJaminan::class ]; - $rules = []; - $hasAssetDescriptionRules = false; - - $pisah = array_filter( - explode(',', $action), - function ($act) use ($allowedActions) { - return isset($allowedActions[trim($act)]); - } - ); - - foreach ($pisah as $act) { - $act = trim($act); - $method = $allowedActions[$act]; - - $actionRules = $this->$method($data, $request); - $rules = array_merge($rules, $actionRules); - - if (in_array($act, ['apartemen-kantor', 'tanah', 'bangunan'])) { - $hasAssetDescriptionRules = true; - } + /** + * Display a listing of the resource. + */ + public function index() + { + return view('lpj::surveyor.index'); } - if ($hasAssetDescriptionRules) { - $rules = array_merge($rules, $this->getAssetData($data)); - } - - return $rules; - } - - - public function storeDenah(Request $request) - { - $validator = $request->validate([ - 'foto_denah.*' => 'nullable|file|mimes:jpg,jpeg,png,bmp,gif,webp,pdf', - 'nama_denah.*' => 'nullable|string|max:255', - 'luas_denah.*' => 'nullable|numeric', - 'permohonan_id' => 'required|exists:permohonan,id', - 'dokument_id' => 'required' - ]); - if ($validator) { - try { - - $denahs = []; - - $inspeksi = Inspeksi::where('permohonan_id', $request->permohonan_id) - ->where('dokument_id', $request->dokument_id) - ->first(); - - $existingDenah = $inspeksi ? json_decode($inspeksi->denah_form ?? '[]', true) : []; - $existingDenahs = $existingDenah['denahs'] ?? []; - - if ($request->has('nama_denah')) { - foreach ($request->nama_denah as $index => $namaDenah) { - $denahItem = [ - 'nama_denah' => $namaDenah, - 'luas_denah' => $request->luas_denah[$index] ?? null - ]; - - if ($request->hasFile('foto_denah') && isset($request->file('foto_denah')[$index])) { - $file = $request->file('foto_denah')[$index]; - $denahItem['foto_denah'] = $this->uploadFile($file, 'foto_denah'); - } elseif (isset($existingDenahs[$index]['foto_denah'])) { - $denahItem['foto_denah'] = $existingDenahs[$index]['foto_denah']; - } - - $denahs[] = $denahItem; - } - } - - if (empty($denahs) && !empty($existingDenahs)) { - $denahs = $existingDenahs; - } - - $inspeksi = Inspeksi::firstOrNew([ - 'permohonan_id' => $request->permohonan_id, - 'dokument_id' => $request->dokument_id - ]); - - // Update denah_form - $updatedDenah = ['denahs' => $denahs]; - $inspeksi->denah_form = json_encode($updatedDenah); - $inspeksi->save(); - - return response()->json([ - 'success' => true, - 'message' => 'Data berhasil disimpan', - 'data' => $updatedDenah - ], 200); - - } catch (\Exception $e) { - \Log::error('Denah Store Error: ' . $e->getMessage()); - return response()->json([ - 'success' => false, - 'message' => 'Gagal menyimpan data: ' . $e->getMessage() - ], 500); - } - } - } - - public function storeFoto(Request $request) - { - $validatedData = $this->validateFotoRequest($request); - try { - $log = []; - $photoCategories = [ - 'rute_menuju_lokasi', - 'foto_lingkungan', - ]; - - $lainnya = [ - 'foto_rute_lainnya' => ['foto_rute_lainnya', 'name_rute_lainnya'], - 'foto_lantai_lainnya' => ['foto_lantai_lainnya', 'name_lantai_lainnya'] - ]; - - - $inspeksi = Inspeksi::firstOrNew([ - 'permohonan_id' => $request->input('permohonan_id'), - 'dokument_id' => $request->input('dokument_id') - ]); - // Get existing foto_form data if it exists - $existingData = $inspeksi->exists && $inspeksi->foto_form - ? json_decode($inspeksi->foto_form, true) - : []; - - $formatFotojson = $existingData; - - // Upload berbagai jenis foto - $this->handleFileUpload($request, 'rute_menuju_lokasi', $formatFotojson); - $this->handleFileUpload($request, 'foto_lingkungan', $formatFotojson); - - $this->processFotoLantaiUnit($request, $formatFotojson); - - if ($request->hasFile('foto_objek')) { - $existingObjekJaminan = $formatFotojson['object_jaminan'] ?? []; - $formatFotojson['object_jaminan'] = $this->processObjekJaminanPhotos( - $request, - $existingObjekJaminan - ); - } - - foreach ($lainnya as $category => $fields) { - $photoField = $fields[0]; - $nameField = $fields[1]; - $descriptionField = $fields[2] ?? null; - - if ($request->hasFile($photoField)) { - $newPhotos = $this->processPhotoLainnya( - $request, - $fields, - $existingData[$category] ?? [] - ); - - $formatFotojson[$category] = $newPhotos; - } - } - // // Process single files - $singleFiles = ['foto_basement', 'foto_gerbang', 'pendamping']; - foreach ($singleFiles as $file) { - if ($request->hasFile($file)) { - // Hapus file lama jika ada - if (isset($formatFotojson[$file])) { - $this->deleteOfFile($formatFotojson[$file]); - } - - // Upload dan simpan file baru - $formatFotojson[$file] = $this->uploadFile($request->file($file), $file); - - } - } - - // Update record - if (!empty($formatFotojson)) { - $inspeksi->foto_form = json_encode($formatFotojson); - $inspeksi->save(); - - return response()->json([ - 'success' => true, - 'message' => 'Data berhasil disimpan', - 'data' => $formatFotojson, - 'log' => $log - ], 200); - } - - return response()->json([ - 'success' => false, - 'message' => 'Tidak ada data untuk disimpan' - ], 400); - } catch (Exception $e) { - return response()->json(['success' => false, 'message' => 'Failed to upload: ' . $e->getMessage()], 500); - } - } - - /** - * Process a photo - */ - protected function processFotoLantaiUnit(Request $request, &$formatFotojson) - { - // Pastikan foto_lantai_unit sudah ada di formatFotojson - if (!isset($formatFotojson['foto_lantai_unit'])) { - $formatFotojson['foto_lantai_unit'] = []; - } - - // Ambil nama-nama lantai dari request - $lantaiNama = $request->input('lantai_nama', []); - - // Tambahan: gunakan lantai_index jika tersedia - $lantaiIndex = $request->input('lantai_index', null); - - // Cek apakah ada file foto lantai yang diunggah - $lantaiFiles = $request->file('foto_lantai_unit', []); - - // Proses setiap file foto lantai - foreach ($lantaiFiles as $index => $files) { - // Pastikan $files adalah array - if (!is_array($files)) { - $files = [$files]; - } - - // Gunakan lantai_index jika tersedia, jika tidak gunakan cara sebelumnya - $lantaiNomor = $lantaiIndex ?? ($index + 1); - - // Inisialisasi array untuk lantai ini jika belum ada - if (!isset($formatFotojson['foto_lantai_unit'][$lantaiNomor])) { - $formatFotojson['foto_lantai_unit'][$lantaiNomor] = []; - } - - foreach ($files as $fileIndex => $file) { - // Validasi file - if (!$file->isValid()) { - continue; // Lewati file yang tidak valid - } - - // Generate nama file unik - $uniqueFileName = 'lantai_unit_' . $lantaiNomor . '_' . $fileIndex . '_' . Str::random(10) . '.' . $file->getClientOriginalExtension(); - - // Simpan file dengan nama asli - $path = $file->storeAs( - 'surveyor/lantai_unit', - $uniqueFileName . '/' . time() . '_' . $file->getClientOriginalName(), - 'public' - ); - - // Buat nama foto - $fotoName = "Foto Lantai {$lantaiNomor} - " . ($fileIndex + 1); - - // Tambahkan detail foto ke array - $fotoDetail = [ - 'path' => $path, - 'name' => $fotoName - ]; - - // Tambahkan ke array foto lantai unit sesuai struktur - $formatFotojson['foto_lantai_unit'][$lantaiNomor][] = $fotoDetail; - } - } - - return $formatFotojson; - } - - - - private function handleFileUpload(Request $request, $paramName, &$formatFotojson) - { - if ($request->hasFile($paramName)) { - $files = $request->file($paramName); - - // Pastikan $files adalah array - if (!is_array($files)) { - $files = [$files]; - } - - $formatFotoData = []; - - foreach ($files as $index => $file) { - $timestamp = time(); - $originalName = $file->getClientOriginalName(); - $uniqueFileName = "{$timestamp}_{$originalName}"; - - // Simpan file - $path = $file->storeAs("surveyor/{$paramName}", $uniqueFileName, 'public'); - - $fotoData = [ - 'path' => $path, - 'name' => ucwords(str_replace('_', ' ', $paramName)) . ' - ' . ($index + 1) - ]; - - $formatFotoData[] = $fotoData; - } - - // Struktur JSON yang konsisten - if (!isset($formatFotojson[$paramName][$paramName][0])) { - $formatFotojson[$paramName] = [ - $paramName => [ - $formatFotoData - ] - ]; - } else { - $formatFotojson[$paramName][$paramName][0] = array_merge( - $formatFotojson[$paramName][$paramName][0] ?? [], - $formatFotoData - ); - } - - return $formatFotoData; - } - - return []; - } - - public function hapusFoto(Request $request) - { - try { - $permohonanId = $request->permohonan_id; - $dokumentId = $request->dokument_id; - $paramName = $request->param_name; - - $cleanRequestPath = str_replace('/storage/', '', $request->path); - - $inspeksi = Inspeksi::firstOrNew( - ['permohonan_id' => $permohonanId, 'dokument_id' => $dokumentId] - ); - $fotoForm = json_decode($inspeksi->foto_form, true); - - if (isset($fotoForm[$paramName][$paramName][0])) { - // Filter foto yang akan dihapus - - $tes = null; - $fotoForm[$paramName][$paramName][0] = array_values( - array_filter( - $fotoForm[$paramName][$paramName][0], - function ($foto) use ($cleanRequestPath) { - if ($foto['path'] === $cleanRequestPath) { - // Hapus file dari storage - \Storage::disk('public')->delete($cleanRequestPath); - return false; // Hapus elemen ini dari array - } - $tes = $foto['path']; - return true; - } - ) - ); - - - // Reset array index - $fotoForm[$paramName][$paramName][0] = array_values($fotoForm[$paramName][$paramName][0]); - - $inspeksi->foto_form = $fotoForm; - $inspeksi->save(); - - return response()->json([ - 'success' => true, - 'message' => 'Foto berhasil dihapus', - ], 200); - } - - return response()->json(['success' => false], 400); - } catch (\Exception $e) { - return response()->json([ - 'success' => false, - 'message' => $e->getMessage() - ], 500); - } - } - - // Metode untuk mendapatkan foto yang sudah diupload - public function getFoto(Request $request) - { - $permohonanId = $request->permohonan_id; - $dokumentId = $request->dokument_id; - $paramName = $request->param_name; - - $inspeksi = Inspeksi::firstOrNew( - ['permohonan_id' => $permohonanId, 'dokument_id' => $dokumentId] - ); - - // Decode foto_form - $fotoForm = json_decode($inspeksi->foto_form, true) ?? []; - - // Cari foto berdasarkan param name - $fotos = $this->findFotoByParamName($fotoForm, $paramName); - - - $param = $paramName == 'rute_menuju_lokasi' ? $fotos['rute_menuju_lokasi'][0] : $fotos['foto_lingkungan'][0]; - $data = array_map(function ($foto) { - return [ - 'name' => $foto['name'] ?? 'Foto', - 'path' => \Storage::url($foto['path']), - ]; - }, $param); - - return response()->json([ - 'fotos' => $data, - 'success' => !empty($data) - ]); - } - - private function findFotoByParamName($fotoForm, $paramName) - { - // Mapping parameter name ke struktur JSON - $paramMapping = [ - 'rute_menuju_lokasi' => ['rute_menuju_lokasi'], - 'foto_lingkungan' => ['foto_lingkungan'], - ]; - - // // Traverse array menggunakan mapping - $fotos = $fotoForm; - if (isset($paramMapping[$paramName])) { - foreach ($paramMapping[$paramName] as $key) { - $fotos = $fotos[$key] ?? []; - } - } - - return is_array($fotos) ? $fotos : []; - } - - - private function processObjekJaminanPhotos(Request $request, array $existingPhotos = []) - { - $photoField = 'foto_objek'; - $nameField = 'name_objek'; - $descriptionField = 'deskripsi_objek'; - - // Mulai dengan data lama - $result = $existingPhotos; - - if ($request->hasFile($photoField)) { - $newFiles = $request->file($photoField, []); - $newNames = $request->input($nameField, []); - $newDescriptions = $request->input($descriptionField, []); - - foreach ($newFiles as $key => $file) { - // Cari atau buat entri berdasarkan nama objek - $existingIndex = $this->findObjekJaminanIndexByName($result, $newNames[$key]); - - // Buat entri baru untuk file yang diunggah - $newPhotoEntry = [ - $nameField => $newNames[$key], - $photoField => $this->uploadFile($file, $photoField . '.' . $key), - $descriptionField => $newDescriptions[$key] ?? '', - ]; - - // Jika sudah ada, update; jika belum, tambahkan - if ($existingIndex !== false) { - // Hapus file lama jika ada - if (isset($result[$existingIndex][$photoField])) { - $this->deleteOfFile($result[$existingIndex][$photoField]); - } - $result[$existingIndex] = $newPhotoEntry; - } else { - $result[] = $newPhotoEntry; - } - } - } - - // Pastikan array tetap terurut dengan benar - return array_values($result); - } - - /** - * Cari index objek jaminan berdasarkan nama objek - */ - private function findObjekJaminanIndexByName(array $existingPhotos, string $name) - { - foreach ($existingPhotos as $index => $photo) { - if (isset($photo['name_objek']) && $photo['name_objek'] === $name) { - return $index; - } - } - return false; - } - - public function hapusLantai(Request $request) - { - $permohonanId = $request->permohonan_id; - $dokumentId = $request->dokument_id; - - // Normalisasi path foto - $cleanRequestPath = str_replace(['storage/', 'surveyor/'], '', $request->foto_path); - - $inspeksi = Inspeksi::firstOrNew( - ['permohonan_id' => $permohonanId, 'dokument_id' => $dokumentId] - ); - $fotoLantaiUnit = json_decode($inspeksi->foto_form, true); - - // Konversi lantai ke string untuk konsistensi - $lantai = (string)$request->lantai; - - // Cek apakah lantai ada di array - $pat = null; - if (isset($fotoLantaiUnit['foto_lantai_unit'][$lantai])) { - // Filter foto, hapus foto yang sesuai - $fotoLantaiUnit['foto_lantai_unit'][$lantai] = array_filter( - $fotoLantaiUnit['foto_lantai_unit'][$lantai], - function ($foto) use ($cleanRequestPath) { - // Normalisasi path foto yang tersimpan - $storedPath = str_replace(['storage/', 'surveyor/'], '', $foto['path']); - - // Jika path cocok, hapus file dari storage - if ($storedPath === $cleanRequestPath) { - // Hapus file dari storage dengan berbagai kemungkinan path - $possiblePaths = [ - 'storage/surveyor/lantai_unit/' . $cleanRequestPath, - 'storage/surveyor/' . $cleanRequestPath, - 'storage/' . $cleanRequestPath, - $cleanRequestPath - ]; - - foreach ($possiblePaths as $path) { - if (Storage::disk('public')->exists($path)) { - Storage::disk('public')->delete($path); - break; - } - } - - return false; // Hapus dari array - } - return true; - } - ); - - // Reset index array - $fotoLantaiUnit['foto_lantai_unit'][$lantai] = array_values($fotoLantaiUnit['foto_lantai_unit'][$lantai]); - - // Hapus lantai jika tidak ada foto - if (empty($fotoLantaiUnit['foto_lantai_unit'][$lantai])) { - unset($fotoLantaiUnit['foto_lantai_unit'][$lantai]); - } - - // Update inspeksi - $inspeksi->foto_form = json_encode($fotoLantaiUnit); - $inspeksi->save(); - - return response()->json([ - 'success' => true, - 'foto_lantai_unit' => $pat - ]); - } - - return response()->json([ - 'success' => false, - 'message' => 'gagal menghapus' - ], 404); - } - - private function processPhotoLainnya(Request $request, array $fields, array $existingPhotos = []) - { - $result = $existingPhotos; // Start with existing photos - $photoField = $fields[0]; - $nameField = $fields[1]; - $descriptionField = $fields[2] ?? null; - - if ($request->hasFile($photoField)) { - $newFiles = $request->file($photoField, []); - $newNames = $request->input($nameField, []); - $newDescriptions = $descriptionField ? $request->input($descriptionField, []) : []; - - // Process each new file - foreach ($newFiles as $key => $file) { - // Create new photo entry - $newPhotoEntry = [ - $nameField => $newNames[$key] ?? '', // Use new name if provided - $photoField => $this->uploadFile($file, $photoField . '.' . $key) - ]; - - // Add description if field exists - if ($descriptionField) { - $newPhotoEntry[$descriptionField] = $newDescriptions[$key] ?? ''; - } - - // Add to result - $result[] = $newPhotoEntry; - } - } - - return $result; - } - - private function generateUniqueFileName($file, $prefix = '') - { - $extension = $file->getClientOriginalExtension(); - return $prefix . '_' . uniqid() . '.' . $extension; - } - - private function deleteOfFile($filePath) - { - if ($filePath && Storage::exists($filePath)) { - Storage::delete($filePath); - } - } - - /** - * Custom validation request for foto - */ - public function validateFotoRequest(Request $request) - { - $maxSize = getMaxFileSize('Foto'); - return $request->validate([ - 'permohonan_id' => 'required', - 'dokument_id' => 'required', - 'pendamping' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp,bmp,tiff,heic,heif|max:'. $maxSize, - 'foto_objek.*' => 'required|image|mimes:jpeg,png,jpg,gif,svg,webp,bmp,tiff,heic,heif|max:'. $maxSize, - 'name_objek.*' => 'required|string|max:255', - - 'name_lingkungan.*' => 'required|string|max:255', - 'foto_rute.*' => 'required|image|mimes:jpeg,png,jpg,gif,svg,webp,bmp,tiff,heic,heif|max:'. $maxSize, - 'name_rute.*' => 'required|string|max:255', - 'lantai.*' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp,bmp,tiff,heic,heif|max:'. $maxSize, - - 'name_rute_lainnya.*' => 'nullable|string', - 'foto_rute_lainnya.*' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp,bmp,tiff,heic,heif|max:'. $maxSize, - 'foto_lantai_lainnya.*' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp,bmp,tiff,heic,heif|max:'. $maxSize, - 'name_lantai_lainnya.*' => 'nullable|string|max:255', - 'foto_basement.*' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp,bmp,tiff,heic,heif|max:'. $maxSize, - 'name_basement.*' => 'nullable|string|max:255', - 'foto_gerbang' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp,bmp,tiff,heic,heif|max:'. $maxSize, - 'name_gerbang' => 'nullable|string|max:255', - - - 'name_lantai_unit' => 'array', - - ]); - } - - public function submitSurveyor($id) - { - try { - // Get button status check result - $buttonStatusCheck = $this->checkButtonStatus($id); - $buttonStatus = json_decode($buttonStatusCheck->getContent(), true); - - // Check if button should be disabled - if ($buttonStatus['buttonDisable']) { - return response()->json([ - 'success' => false, - 'message' => 'Form belum lengkap. Pastikan semua data telah diisi dengan benar.', - ], 422); - } - - // If validation passes, update permohonan status - $permohonan = Permohonan::findOrFail($id); - $permohonan->update([ - 'status' => 'done', - 'submitted_at' => now() - ]); - - return response()->json([ - 'success' => true, - 'message' => 'Form surveyor berhasil disubmit' - ], 200); - - } catch (\Exception $e) { - return response()->json([ - 'success' => false, - 'message' => 'Terjadi kesalahan', - 'error' => $e->getMessage() - ], 500); - } - } - - - - - public function checkButtonStatus($id) - { - try { - // Get all inspeksi records for this permohonan - $inspeksiRecords = Inspeksi::with(['dokument.jenisJaminan']) - ->where('permohonan_id', $id) - ->get(); - - if ($inspeksiRecords->isEmpty()) { - return response()->json(['buttonDisable' => true]); - } - - foreach ($inspeksiRecords as $inspeksi) { - $dataForm = json_decode($inspeksi->data_form, true); - $fotoForm = json_decode($inspeksi->foto_form, true); - $denahForm = json_decode($inspeksi->denah_form, true); - $dataPembanding = json_decode($inspeksi->data_pembanding, true); - - $jenisJaminan = $inspeksi->dokument->jenisJaminan->name ?? ''; - - $isTanahBangunan = !in_array( - strtoupper($jenisJaminan->name ?? ''), - ['KAPAL', 'PESAWAT', 'KENDARAAN', 'ALAT BERAT'] - ); - - $isInvalid = - empty($dataForm) || - empty($fotoForm) || - (($isTanahBangunan && empty($denahForm)) || - empty($dataPembanding)); - - if ($isInvalid) { - return response()->json(['buttonDisable' => true]); - } - } - - // If we get here, all checks passed - return response()->json(['buttonDisable' => false]); - - } catch (\Exception $e) { - return response()->json([ - 'error' => 'Something went wrong', - 'message' => $e->getMessage(), - 'buttonDisable' => true - ], 500); - } - } - - - public function storeJadwal(Request $request) - { - try { - $validate = $request->validate([ - 'id' => 'required', - 'waktu_penilaian' => 'required', - 'deskripsi_penilaian' => 'required' - ]); - - // $user = ['user' => 'rustammajid76@gmail.com']; - - // $emailData = [ - // 'email' => 'rustammajid76@gmail.com', - // 'subject' => 'Test', - // 'emailData' => '

Hello, World!

This is the email content. Waktu Penilaian:

' - // ]; - - // $this->sendMessage($emailData, $user); - - $id = $request->input('id'); - $penilaian = Penilaian::findOrFail($id); - - $penilaian->update([ - 'waktu_penilaian' => $validate['waktu_penilaian'], - 'deskripsi_penilaian' => $validate['deskripsi_penilaian'], - ]); - - return redirect() - ->route('surveyor.index') - ->with('success', 'Jadwal berhasil dibuat.'); - } catch (\Exception $e) { - return response()->json(['buttonDisable' => $e->getMessage()]); - } - } - - - - public function storeAproved(Request $request, $id): JsonResponse - { - $data = []; - if (request()->ajax()) { - try { - $penilaian = Penilaian::findOrFail($id); - $penilaian->update([ - 'authorized_status' => 1, - ]); - - $data['status'] = 'success'; - $data['message'] = 'Jadwal '.$request->noReg.' berhasil di aprove'; - } catch (\Exception $e) { - $data['status'] = 'error'; - $data['message'] = 'Gagal membuat jadwal: ' . $e->getMessage(); - } - - } else { - $data['status'] = 'error'; - $data['message'] = "no ajax request"; - } - - return response()->json($data); - } - - - public function storeFreeze() - { - - } - - - private function formatDataPembanding($request) - { - $dataPembanding = []; - $pembandingCount = count($request->input('address_pembanding', [])); - $fotoPembanding = $request->file('foto_objek_pembanding') ?? []; - - $existingData = null; - if ($request->has('permohonan_id') && $request->has('dokument_id')) { - $inspeksi = Inspeksi::where('permohonan_id', $request->input('permohonan_id')) - ->where('dokument_id', $request->input('dokument_id')) - ->first(); - - if ($inspeksi) { - $existingData = json_decode($inspeksi->data_pembanding, true) ?? []; - } - } - - for ($i = 0; $i < $pembandingCount; $i++) { - $pembanding = $this->formatSinglePembanding($request, $i); - - - $existingFoto = null; - if ($existingData && isset($existingData['data_pembanding'][$i]['foto_objek'])) { - $existingFoto = $existingData['data_pembanding'][$i]['foto_objek']; - } - - // Penanganan foto pembanding - if (isset($fotoPembanding[$i]) && $fotoPembanding[$i]->isValid()) { - $pembanding['foto_objek'] = $this->handleupdateOrDeleteFile( - $fotoPembanding[$i], - 'pembanding', - "pembanding_{$i}" - ); - } else { - $pembanding['foto_objek'] = $existingFoto; - } - - $dataPembanding[] = $pembanding; - } - - return $dataPembanding; - } - - - private function formatSinglePembanding($request, $index) - { - $fields = [ - 'address', 'village_code', 'district_code', 'city_code', 'province_code', - 'tahun', 'luas_tanah', 'luas_bangunan', 'tahun_bangunan', - 'status_nara_sumber', 'harga', 'harga_diskon', 'diskon', 'total', 'nama_nara_sumber', - 'peruntukan', 'penawaran', 'telepon','hak_properti', - 'kordinat_lat', 'kordinat_lng', 'jenis_aset','foto_objek' - ]; - - $pembanding = []; - foreach ($fields as $field) { - $inputName = "{$field}_pembanding"; - $inputValue = $request->input($inputName); - - // Pastikan input adalah array dan index valid - if (is_array($inputValue) && isset($inputValue[$index])) { - $pembanding[$field] = $inputValue[$index]; - } else { - $pembanding[$field] = null; - } - } - - - return $pembanding; - } - - - - private function handleupdateOrDeleteFile($file, $type, $prefix) - { - try { - if ($file) { - // Generate nama file unik - $fileName = $prefix . '_' . uniqid() . '_' . time() . '.' . $file->getClientOriginalExtension(); - $path = "{$type}/" . date('Y/m'); - Storage::makeDirectory("public/{$path}"); - $filePath = $file->storeAs("public/{$path}", $fileName); - return str_replace('public/', '', $filePath); - } - - return null; - - } catch (\Exception $e) { - \Log::error('File upload error: ' . $e->getMessage()); - throw new \Exception("Gagal mengupload file: " . $e->getMessage()); - } - } - - - private function formatObjekPenilaian($request) - { - $fields = [ - 'address', 'village_code', 'district_code', 'city_code', 'province_code', - 'luas_tanah', 'luas_tanah_bagunan', 'total', 'diskon', 'harga_diskon', - 'status_nara_sumber', 'harga', 'nama_nara_sumber','hak_properti','telepon', - 'kordinat_lat', 'kordinat_lng', 'jenis_aset','penawaran', - ]; - - $inspeksi = Inspeksi::where('permohonan_id', $request->input('permohonan_id')) - ->where('dokument_id', $request->input('dokument_id')) - ->first(); - - if ($inspeksi) { - $needsSave = false; - - // Handle foto_form - $fotoForm = json_decode($inspeksi->foto_form, true) ?: []; - if (!isset($fotoForm['object_jaminan'])) { - $fotoForm['object_jaminan'] = [['foto_objek' => null]]; - $needsSave = true; - } - - // Handle data_form - $dataForm = json_decode($inspeksi->data_form, true) ?: []; - - // Inisialisasi struktur data jika belum ada - if (!isset($dataForm['bangunan'])) { - $dataForm['bangunan'] = []; - $needsSave = true; - } - - if (!isset($dataForm['tanah'])) { - $dataForm['tanah'] = []; - $needsSave = true; - } - - if (!isset($dataForm['asset'])) { - $dataForm['asset'] = []; - $needsSave = true; - } - - // Update data dengan mempertahankan struktur sesuai/tidak sesuai - foreach ($fields as $field) { - if ($request->filled($field)) { - $newValue = $request->input($field); - - // Fields untuk tanah - if (in_array($field, ['luas_tanah'])) { - // Pastikan struktur array ada sebelum diakses - if (!isset($dataForm['tanah']['luas_tanah'])) { - $dataForm['tanah']['luas_tanah'] = []; - } - - $cekLuas = isset($dataForm['tanah']['luas_tanah']['sesuai']) && $dataForm['tanah']['luas_tanah']['sesuai'] === 'sesuai' - ? 'sesuai' - : 'tidak sesuai'; - - $dataForm['tanah']['luas_tanah'][$cekLuas] = $newValue; - $needsSave = true; - } - - // Fields untuk bangunan - elseif (in_array($field, ['luas_tanah_bagunan'])) { - if (!isset($dataForm['bangunan']['luas_tanah_bagunan'])) { - $dataForm['bangunan']['luas_tanah_bagunan'] = []; - } - - $cekBanguan = isset($dataForm['bangunan']['luas_tanah_bagunan']['sesuai']) && $dataForm['bangunan']['luas_tanah_bagunan']['sesuai'] === 'sesuai' - ? 'sesuai' - : 'tidak sesuai'; - - $dataForm['bangunan']['luas_tanah_bagunan'][$cekBanguan] = $newValue; - $needsSave = true; - } - - // Fields untuk alamat dalam asset - elseif (in_array($field, ['address', 'village_code', 'district_code', 'city_code', 'province_code'])) { - - if (!isset($dataForm['asset']['alamat'])) { - $dataForm['asset']['alamat'] = []; - } - - $alamatStatus = $dataForm['asset']['alamat'] == 'sesuai' ? 'sesuai' : 'tidak sesuai'; - if (!isset($dataForm['asset']['alamat'][$alamatStatus])) { - $dataForm['asset']['alamat'][$alamatStatus] = []; - } - - $dataForm['asset']['alamat'][$alamatStatus][$field] = $newValue; - } - // Jenis asset dalam asset - elseif ($field === 'jenis_asset') { - $assetStatus = $request->input('asset_status', 'sesuai'); - $dataForm['asset']['jenis_asset'] = [ - $assetStatus => $newValue - ]; - } - // Fields lainnya dalam asset - else { - if (!isset($dataForm['asset'][$field])) { - $dataForm['asset'][$field] = []; - } - $dataForm['asset'][$field] = $newValue; - } - - - $needsSave = true; - } - } - - if ($needsSave) { - $inspeksi->foto_form = json_encode($fotoForm); - $inspeksi->data_form = json_encode($dataForm); - $inspeksi->save(); - } - - $existingFoto = $fotoForm['object_jaminan'][0]['foto_objek'] ?? null; - - // Gabungkan data dari tanah, bangunan, dan asset - $objekPenilaian = array_merge( - ['foto_objek' => $existingFoto], - $dataForm['tanah'] ?? [], - $dataForm['bangunan'] ?? [], - array_reduce($fields, function ($carry, $field) use ($request, $dataForm) { - if (isset($dataForm['asset'][$field])) { - if (is_array($dataForm['asset'][$field])) { - if (isset($dataForm['asset'][$field]['sesuai'])) { - $carry[$field] = $dataForm['asset'][$field]['sesuai']; - } elseif (isset($dataForm['asset'][$field]['tidak sesuai'])) { - $carry[$field] = $dataForm['asset'][$field]['tidak sesuai']; - } - } else { - $carry[$field] = $dataForm['asset'][$field]; - } - } else { - $carry[$field] = $request->input($field); - } - return $carry; - }, []) - ); - - } else { - // Inisialisasi data baru - $objekPenilaian = array_reduce($fields, function ($carry, $field) use ($request) { - $carry[$field] = $request->input($field); - return $carry; - }, ['foto_objek' => null]); - } - - return $objekPenilaian; - } - - - - private function saveInspeksi($formattedData) - { - $inspeksi = Inspeksi::updateOrCreate( - [ - 'permohonan_id' => $formattedData['permohonan_id'], - 'dokument_id' => $formattedData['dokument_id'] - ], - [ - 'data_pembanding' => json_encode($formattedData), - 'name' => $formattedData['type'] - ] - ); - - return $inspeksi; - } - public function storeDataPembanding(Request $request) - { - try { - DB::beginTransaction(); - - $maxSize = getMaxFileSize('Foto'); - $validator = $request->validate([ - 'permohonan_id' => 'required|exists:permohonan,id', - 'type' => 'required|string', - 'dokument_id' => 'required', - 'foto_objek' => 'nullable|image|max:'.$maxSize, - 'foto_objek_pembanding.*' => 'nullable|image|max:'.$maxSize, - ]); - - $objekPenilaian = $this->formatObjekPenilaian($request); - if ($request->hasFile('foto_objek')) { - $newFoto = $this->handleupdateOrDeleteFile( - $request->file('foto_objek'), - $request['type'] = 'pembanding', - 'objek_penilaian' - ); - - // Update foto_form - $inspeksi = Inspeksi::where('permohonan_id', $request->input('permohonan_id')) - ->where('dokument_id', $request->input('dokument_id')) - ->first(); - - if ($inspeksi) { - $fotoForm = json_decode($inspeksi->foto_form, true) ?: []; - if (!isset($fotoForm['object_jaminan'])) { - $fotoForm['object_jaminan'] = []; - } - if (empty($fotoForm['object_jaminan'])) { - $fotoForm['object_jaminan'][] = ['foto_objek' => $newFoto]; - } else { - $fotoForm['object_jaminan'][0]['foto_objek'] = $newFoto; - } - - $inspeksi->foto_form = json_encode($fotoForm); - $inspeksi->save(); - } - - $objekPenilaian['foto_objek'] = $newFoto; - } - - - $formattedData = [ - 'permohonan_id' => $request->input('permohonan_id'), - 'type' => $request->input('type'), - 'dokument_id' => $request->input('dokument_id'), - 'objek_penilaian' => $objekPenilaian, - 'data_pembanding' => $this->formatDataPembanding($request) - ]; - - - $inspeksi = $this->saveInspeksi($formattedData); - - DB::commit(); - - return response()->json([ - 'success' => true, - 'message' => 'Data berhasil disimpan', - 'data' => $formattedData - ], 200); - - } catch (\Exception $e) { - DB::rollBack(); - return response()->json([ - 'success' => false, - 'message' => 'Gagal menyimpan data: ' . $e->getMessage() - ], 500); - } - } - - - - /** - * Form inspeksi. - */ - - public function formInspeksi(Request $request, $id) - { - - $validated = $request->validate([ - 'form' => 'required|in:create-inspeksi', - 'inspeksi' => 'required|exists:permohonan,id', - 'dokument' => 'required', - 'jenisjaminan' => 'required' - ]); - - $dokumentId = $validated['dokument']; - $jaminanId = $validated['jenisjaminan']; - - $permohonan = $this->getPermohonanJaminanId($id, $dokumentId, $jaminanId); - - $link_url_region = Teams::with('regions', 'teamsUsers') - ->whereHas('teamsUsers', function ($query) { - $query->where('user_id', Auth::user()->id); - })->first(); - - $branches = Branch::all(); - $provinces = Province::all(); - - - - $surveyor = $id; - $basicData = $this->getCommonData(); - - $inpeksi = Inspeksi::where('permohonan_id', $id)->where('dokument_id', $dokumentId)->first(); - $forminspeksi = null; - if ($inpeksi) { - $forminspeksi = json_decode($inpeksi->data_form, true); - } - - // Default: gunakan data dari debitur - $debitur = Debiture::find($permohonan->debiture_id); - - $provinceCode = $debitur->province_code; - $cityCode = $debitur->city_code; - $districtCode = $debitur->district_code; - - // Jika alamat tidak sesuai, override dengan kode dari alamat - - $cekAlamat = $forminspeksi['asset']['alamat']['tidak sesuai'] ?? null; - - if ($cekAlamat) { - $provinceCode = $cekAlamat['province_code'] ?? $provinceCode; - $cityCode = $cekAlamat['city_code'] ?? $cityCode; - $districtCode = $cekAlamat['district_code'] ?? $districtCode; - } - - // Ambil data menggunakan kode yang telah ditentukan - $cities = City::where('province_code', $provinceCode)->get(); - $districts = District::where('city_code', $cityCode)->get(); - $villages = Village::where('district_code', $districtCode)->get(); - return view('lpj::surveyor.components.inspeksi', compact( - 'permohonan', - 'surveyor', - 'branches', - 'provinces', - 'debitur', - 'cities', - 'districts', - 'villages', - 'link_url_region', - 'forminspeksi', - 'basicData', - 'cekAlamat' - )); - } - - /** - * Denah. - */ - - public function denah(Request $request, $id) - { - $validated = $request->validate([ - 'form' => 'required|in:create-denah', - 'denah' => 'required|exists:permohonan,id', - 'dokument' => 'required', - 'jenisjaminan' => 'required' - ]); - - $dokumentId = $validated['dokument']; - $jaminanId = $validated['jenisjaminan']; - - $permohonan = $this->getPermohonanJaminanId($id, $dokumentId, $jaminanId); - - $denah = null; - - $inpeksi = Inspeksi::where('permohonan_id', $id)->where('dokument_id', $dokumentId)->first(); - $formDenah = null; - if ($inpeksi) { - $formDenah = json_decode($inpeksi->denah_form, true); - } - - // return response()->json($formDenah); - return view('lpj::surveyor.components.denah', compact('permohonan', 'denah', 'formDenah')); - } - - /** - * Foto. - */ - - public function foto(Request $request, $id) - { - $validated = $request->validate([ - 'form' => 'required|in:create-foto', - 'foto' => 'required|exists:permohonan,id', - 'dokument' => 'required', - 'jenisjaminan' => 'required' - ]); - - $dokumentId = $validated['dokument']; - $jaminanId = $validated['jenisjaminan']; - $fotoObjekJaminan = FotoObjekJaminan::all(); - - $permohonan = $this->getPermohonanJaminanId($id, $dokumentId, $jaminanId); - - $surveyor = $id; - $branches = Branch::all(); - $provinces = Province::all(); - - $inpeksi = Inspeksi::where('permohonan_id', $id)->where('dokument_id', $dokumentId)->first(); - - $formFoto = null; - if ($inpeksi) { - $formFoto = json_decode($inpeksi->foto_form, true); - } - $fotoJaminan = null; - return view('lpj::surveyor.components.foto', compact('permohonan', 'surveyor', 'branches', 'provinces', 'fotoJaminan', 'formFoto', 'fotoObjekJaminan')); - } - - /** - * Data pembanding. - */ - - public function dataPembanding(Request $request, $id) - { - try { - // Ambil data permohonan dengan eager loading - - $validated = $request->validate([ - 'form' => 'required|in:data-pembanding', - 'pembanding' => 'required|exists:permohonan,id', - 'dokument' => 'required', - 'jenisjaminan' => 'required' - ]); - - $dokumentId = $validated['dokument']; - $jaminanId = $validated['jenisjaminan']; - - $permohonan = $this->getPermohonanJaminanId($id, $dokumentId, $jaminanId); - - - // Ambil data inspeksi - $inspeksi = Inspeksi::where([ - 'permohonan_id' => $id, - 'dokument_id' => $dokumentId - ])->first(); - - // Inisialisasi variabel - $inspectionData = null; - $comparisons = null; - $fotoForm = null; - - - if ($inspeksi) { - - $inspectionData = json_decode($inspeksi->data_form, true); - if (json_last_error() !== JSON_ERROR_NONE) { - throw new \Exception('Harap mengisi form inspeksi terlebih dahulu.'); - } - - if ($inspeksi->data_pembanding) { - $comparisons = json_decode($inspeksi->data_pembanding, true); - if (json_last_error() !== JSON_ERROR_NONE) { - throw new \Exception('Error decoding comparison data: ' . json_last_error_msg()); - } - } - $fotoForm = json_decode($inspeksi->foto_form, true); - - } - - // Ambil data pendukung - $data = $this->getCommonData(); - $provinces = Province::all(); - - $cities = City::where('province_code', $this->getCodeAlamat('province_code', $inspectionData))->get(); - $districts = District::where('city_code', $this->getCodeAlamat('city_code', $inspectionData))->get(); - $villages = Village::where('district_code', $this->getCodeAlamat('district_code', $inspectionData))->get(); - - return view('lpj::surveyor.components.data-pembanding', compact( - 'permohonan', - 'id', - 'inspectionData', - 'comparisons', - 'data', - 'jaminanId', - 'fotoForm', - 'cities', - 'districts', - 'villages', - 'provinces', - 'inspeksi' - )); - - } catch (\Exception $e) { - return redirect() - ->back() - ->with('error', 'Terjadi kesalahan saat memuat data: ' . $e->getMessage()); - } - } - - - public function getCodeAlamat($code, $inspectionData) - { - $cekAlamat = isset( - $inspectionData['asset']['alamat']['sesuai'], - ) - ? 'sesuai' - : 'tidak sesuai'; - $selectedProvince = - $inspectionData['asset']['alamat'][$cekAlamat][ - $code - ] ?? null; - return $selectedProvince; - } - - - private function getHeader(string $type): array - { - return self::HEADERS[$type] ?? []; - } - - public function data(Request $request) - { - - $type = $request->route('type'); - $header = $this->getHeader($request->route('type')); - return view('lpj::surveyor.data.index', compact('header')); - } - - - public function createData($type) - { - $spekKategoriBagunan = SpekKategoritBangunan::all(); - $header = $this->getHeader($type); - return view('lpj::surveyor.data.form', compact('header', 'spekKategoriBagunan')); - } - - - public function storeData(SurveyorRequest $request, $type) - { - $validate = $request->validated(); - if ($validate) { - - try { - $type = $request->route('type'); - - $modelClass = $this->getModelClass($type); - - if (!$modelClass) { - return redirect() - ->route('basicdata.' . $type . '.index') - ->with('error', 'Invalid type specified.'); - } - - if ($type == 'spek-bangunan') { - $validate['spek_kategori_bagunan_id'] = $request->spek_kategori_bagunan_id; - } - - - $data = array_merge($validate, ['status' => true]); - $modelClass::create($data); - - return redirect() - ->route('basicdata.' . $type . '.index') - ->with('success', 'created successfully'); - } catch (Exeception $e) { - return redirect() - ->route('basicdata.' . $type . '.index') - ->with('error', $th->getMessage()); - } - } - } - - - public function editData($type, $id) - { - $dataMap = [ - 'bentuk-tanah' => ['Bentuk Tanah', 'bentuk-tanah', BentukTanah::class], - 'kontur-tanah' => ['Kontur Tanah', 'kontur-tanah', KonturTanah::class], - 'posisi-kavling' => ['Posisi Kavling', 'posisi-kavling', PosisiKavling::class], - 'ketinggian-tanah' => ['Ketinggian Tanah', 'ketinggian-tanah', KetinggianTanah::class], - 'kondisi-fisik-tanah' => ['Kondisi Fisik Tanah', 'kondisi-fisik-tanah', KondisiFisikTanah::class], - 'jenis-bangunan' => ['Jenis Bangunan', 'jenis-bangunan', JenisBangunan::class], - 'kondisi-bangunan' => ['Kondisi Bangunan', 'kondisi-bangunan', KondisiBangunan::class], - 'sifat-bangunan' => ['Sifat Bangunan', 'sifat-bangunan', SifatBangunan::class], - 'spek-bangunan' => ['Spek Bangunan', 'spek-bangunan', SpekBangunan::class], - 'spek-kategori-bangunan' => ['Spek Kategori Bangunan', 'spek-kategori-bangunan', SpekKategoritBangunan::class], - 'sarana-pelengkap' => ['Sarana Pelengkap', 'sarana-pelengkap', SaranaPelengkap::class], - 'lantai-unit' => ['Lantai Unit', 'lantai-unit', Lantai::class], - 'view-unit' => ['View Unit', 'view-unit', ViewUnit::class], - 'gol-mas-sekitar' => ['Golongan Masyarakat Sekitar', 'gol-mas-sekitar', GolonganMasySekitar::class], - 'jenis-pesawat' => ['Jenis Pasawat', 'jenis-pesawat', JenisPesawat::class], - 'model-alat-berat' => ['Model Alat Berat', 'model-alat-berat', ModelAlatBerat::class], - 'jenis-kapal' => ['Jenis Kapal', 'jenis-kapal', JenisKapal::class], - 'jenis-kendaraan' => ['Jenis Kendaraan', 'jenis-kendaraan', JenisKendaraan::class], - 'jenis-unit' => ['Jenis unit', 'jenis-unit', JenisUnit::class], - 'terletak-area' => ['Terletak di Area', 'terletak-area', TerletakArea::class], - 'merupakan-daerah' => ['Merupakan Daerah', 'merupakan-daerah', MerupakanDaerah::class], - 'posisi-unit' => ['Posisi unit', 'posisi-unit', PosisiUnit::class], - 'bentuk-unit' => ['Bentuk unit', 'bentuk-unit', BentukUnit::class], - 'fasilitas-objek' => ['Fasilitas Umum Dekat Objek', 'fasilitas-objek', FasilitasObjek::class], - 'foto-objek-jaminan' => ['Foto Objek Jaminan', 'foto-objek-jaminan', FotoObjekJaminan::class], - ]; - - - if (!array_key_exists($type, $dataMap)) { - return redirect()->back()->with('error', 'Invalid type specified.'); - } - - [$headers, $routeName, $modelClass] = $dataMap[$type]; - - $header = $dataMap[$type] ?? ''; - $model = $modelClass::findOrFail($id); - - $spekKategoriBagunan = null; - if ($type == 'spek-bangunan') { - $spekKategoriBagunan = SpekKategoritBangunan::all(); - } - - - return view('lpj::surveyor.data.form', compact('header', 'model', 'spekKategoriBagunan')); - } - - - public function updateData(SurveyorRequest $request, $type, $id) - { - $validate = $request->validated(); - if ($validate) { - $modelClass = $this->getModelClass($type); - - if ($type == 'spek-bangunan') { - $validate['spek_kategori_bagunan_id'] = $request->spek_kategori_bagunan_id; - } - - if ($type == 'foto-objek-jaminan') { - $validate['kategori'] = $request->kategori; - } - - // Check if the provided type exists in the modelClasses - if (!$modelClass) { - return redirect() - ->route('basicdata.' . $type . '.index') - ->with('error', 'Invalid type specified.'); - } - - $model = $modelClass::findOrFail($id); - $model->update($validate); - - // Redirect back with a success message - return redirect() - ->route('basicdata.' . $type . '.index') - ->with('success', 'Updated successfully'); - } - } - - - public function update_analisa($id, Request $request) - { - try { + /** + * Show the specified resource. + */ + public function show($id) + { $permohonan = Permohonan::with([ 'user', 'debiture.province', @@ -1701,1137 +156,2724 @@ class SurveyorController extends Controller 'branch', 'tujuanPenilaian', 'penilaian', + 'documents.jenisJaminan', 'documents', ])->findOrFail($id); - $jenisAssetUpdated = false; - if ($request->input('types') == 'jenis_asset') { - $this->updateJenisAsset($permohonan, $request); - $jenisAssetUpdated = true; - } + $surveyor = $id; + $branches = Branch::all(); + $provinces = Province::all(); + $bentukTanah = BentukTanah::all(); - if (in_array($request->input('types'), ['analisa_tanah', 'analisa_bangunan', 'analisa_unit'])) { - $key = match ($request->input('types')) { - 'analisa_tanah' => 'luas_tanah', - 'analisa_bangunan' => 'luas_bangunan', - 'analisa_unit' => 'luas_unit', - }; + // Get all inspeksi data for this permohonan + $inspeksiData = Inspeksi::where('permohonan_id', $id) + ->get() + ->keyBy('dokument_id') + ->map(function ($item) { + return [ + 'data_form' => json_decode($item->data_form, true), + 'foto_form' => json_decode($item->foto_form, true), + 'denah_form' => json_decode($item->denah_form, true), + 'data_pembanding' => json_decode($item->data_pembanding, true), + ]; + }); - $this->updateDetails($permohonan, $key, $request->input($key)); - } - return response()->json([ - 'success' => true, - 'message' => 'Data berhasil disimpan', - 'jenis_asset' => $jenisAssetUpdated, - ], 200); - } catch (\Exception $e) { - return response()->json(['error' => 'Something went wrong', 'message' => $e->getMessage()], 500); + return view('lpj::surveyor.detail', compact( + 'permohonan', + 'surveyor', + 'branches', + 'provinces', + 'bentukTanah', + 'inspeksiData' + )); } - } + /** + * Store form inspeksi. + */ + public function store(FormSurveyorRequest $request) + { + try { + // Validate request data + $validatedData = $request->validated(); - private function updateJenisAsset($permohonan, $request) - { - $jenis_jaminan_id = $permohonan->debiture->documents->first()->jenis_jaminan_id; - DokumenJaminan::where('permohonan_id', $permohonan->id) - ->where('jenis_jaminan_id', $jenis_jaminan_id) - ->update([ - 'jenis_jaminan_id' => $request->input('jenis_asset'), + // Get action specific rules and process data + $processedData = $this->getActionSpecificRules( + $validatedData, + $request->input('type'), + $request + ); + + // Find or create inspeksi record + $inspeksi = Inspeksi::updateOrCreate( + [ + 'permohonan_id' => $request->input('permohonan_id'), + 'dokument_id' => $request->input('dokument_id') + ], + [ + 'data_form' => json_encode($processedData), + 'name' => $request->input('type') + ] + ); + + return response()->json([ + 'success' => true, + 'message' => 'Data berhasil disimpan', + 'data' => $processedData + ], 200); + + } catch (Exception $e) { + return response()->json([ + 'success' => false, + 'message' => 'Gagal menyimpan data', + 'error' => $e->getMessage() + ], 500); + } + } + + private function getActionSpecificRules($data, $action, $request) + : array + { + $allowedActions = [ + 'apartemen-kantor' => 'getUnitData', + 'tanah' => 'getTanahData', + 'bangunan' => 'getBangunanData', + 'kapal' => 'getKapalData', + 'kendaraan' => 'getKendaraanData', + 'mesin' => 'getMesinData', + 'pesawat' => 'getPesawatData', + 'alat-berat' => 'getAlatBeratData', + 'lingkungan' => 'getLingkunganData', + 'fakta' => 'getFactData' + ]; + + $rules = []; + $hasAssetDescriptionRules = false; + + $pisah = array_filter( + explode(',', $action), + function ($act) use ($allowedActions) { + return isset($allowedActions[trim($act)]); + } + ); + + foreach ($pisah as $act) { + $act = trim($act); + $method = $allowedActions[$act]; + + $actionRules = $this->$method($data, $request); + $rules = array_merge($rules, $actionRules); + + if (in_array($act, ['apartemen-kantor', 'tanah', 'bangunan'])) { + $hasAssetDescriptionRules = true; + } + } + + if ($hasAssetDescriptionRules) { + $rules = array_merge($rules, $this->getAssetData($data)); + } + + return $rules; + } + + private function getAssetData(array $data) + : array + { + $alamatData = [ + 'address' => $data['address'] ?? null, + 'village_code' => $data['village_code'] ?? null, + 'district_code' => $data['district_code'] ?? null, + 'city_code' => $data['city_code'] ?? null, + 'province_code' => $data['province_code'] ?? null, + ]; + + return [ + 'asset' => [ + 'debitur_perwakilan' => $data['debitur_perwakilan'] ?? [], + 'jenis_asset' => [ + $data['jenis_asset'] => ($data['jenis_asset'] === 'sesuai') + ? $data['jenis_asset_name'] + : ($data['jenis_asset_tidak_sesuai'] ?? null) + ], + 'alamat' => [ + $data['alamat_sesuai'] => $alamatData + ], + 'hub_cadeb' => [ + $data['hub_cadeb'] => ($data['hub_cadeb'] == 'sesuai') ? $data['hub_cadeb_sesuai'] : $data['hub_cadeb_tidak_sesuai'] + ], + 'hub_cadeb_penghuni' => [ + $data['hub_cadeb_penghuni'] => ($data['hub_cadeb_penghuni'] == 'sesuai') ? $data['hub_cadeb_penghuni_sesuai'] : $data['hub_penghuni_tidak_sesuai'] + ], + 'pihak_bank' => $data['pihak_bank'] ?? null, + 'kordinat_lng' => $data['kordinat_lng'] ?? null, + 'kordinat_lat' => $data['kordinat_lat'] ?? null, + ] + ]; + } + + public function storeDenah(Request $request) + { + $validator = $request->validate([ + 'foto_denah.*' => 'nullable|file|mimes:jpg,jpeg,png,bmp,gif,webp,pdf', + 'nama_denah.*' => 'nullable|string|max:255', + 'luas_denah.*' => 'nullable|numeric', + 'permohonan_id' => 'required|exists:permohonan,id', + 'dokument_id' => 'required' ]); - } + if ($validator) { + try { - private function updateDetails($permohonan, $key, $newValue) - { - $document = $permohonan->debiture->documents->first(); + $denahs = []; - if (!$document) { - throw new \Exception("Document not found"); - } + $inspeksi = Inspeksi::where('permohonan_id', $request->permohonan_id) + ->where('dokument_id', $request->dokument_id) + ->first(); - $detailsUpdate = DetailDokumenJaminan::where('dokumen_jaminan_id', $document->id)->first(); + $existingDenah = $inspeksi ? json_decode($inspeksi->denah_form ?? '[]', true) : []; + $existingDenahs = $existingDenah['denahs'] ?? []; - if (!$detailsUpdate) { - throw new \Exception("DetailDokumenJaminan not found"); - } + if ($request->has('nama_denah')) { + foreach ($request->nama_denah as $index => $namaDenah) { + $denahItem = [ + 'nama_denah' => $namaDenah, + 'luas_denah' => $request->luas_denah[$index] ?? null + ]; - $datas = json_decode($detailsUpdate->details, true) ?? []; + if ($request->hasFile('foto_denah') && isset($request->file('foto_denah')[$index])) { + $file = $request->file('foto_denah')[$index]; + $denahItem['foto_denah'] = $this->uploadFile($file, 'foto_denah'); + } else if (isset($existingDenahs[$index]['foto_denah'])) { + $denahItem['foto_denah'] = $existingDenahs[$index]['foto_denah']; + } - if (is_numeric($newValue)) { - $newValue = [$key => $newValue]; - } + $denahs[] = $denahItem; + } + } - if (!is_array($newValue)) { - throw new \InvalidArgumentException("'{$key}' must be an array or valid JSON string"); - } + if (empty($denahs) && !empty($existingDenahs)) { + $denahs = $existingDenahs; + } - foreach ($newValue as $subKey => $value) { - $datas[$subKey] = $value; // Update atau tambahkan key baru - } + $inspeksi = Inspeksi::firstOrNew([ + 'permohonan_id' => $request->permohonan_id, + 'dokument_id' => $request->dokument_id + ]); - $detailsUpdate->update([ - 'details' => json_encode($datas), - ]); - } + // Update denah_form + $updatedDenah = ['denahs' => $denahs]; + $inspeksi->denah_form = json_encode($updatedDenah); + $inspeksi->save(); + return response()->json([ + 'success' => true, + 'message' => 'Data berhasil disimpan', + 'data' => $updatedDenah + ], 200); - public function dataForDatatables(Request $request) - { - if (is_null($this->user) || !$this->user->can('debitur.view')) { - // abort(403, 'Sorry! You are not allowed to view users.'); - } - - $query = Permohonan::query(); - - if ($request->has('search') && !empty($request->get('search'))) { - $search = $request->get('search'); - $query->where(function ($q) use ($search) { - $q->where('nomor_registrasi', 'LIKE', '%' . $search . '%'); - $q->orWhere('tanggal_permohonan', 'LIKE', '%' . $search . '%'); - $q->orWhereRelation('user', 'name', 'LIKE', '%' . $search . '%'); - $q->orWhereRelation('debiture', 'name', 'LIKE', '%' . $search . '%'); - $q->orWhereRelation('tujuanPenilaian', 'name', 'LIKE', '%' . $search . '%'); - $q->orWhereRelation('branch', 'name', 'LIKE', '%' . $search . '%'); - $q->orWhere('status', 'LIKE', '%' . $search . '%'); - }); - } - - $query->whereRaw('LOWER(status) = ?', ['assign']); - - if (!Auth::user()->hasRole('administrator')) { - $query->whereHas('penilaian.userPenilai', function ($q) { - $q->where('user_id', Auth::user()->id); - $q->where('role', 'surveyor'); - }); - } - - - if ($request->has('sortOrder') && !empty($request->get('sortOrder'))) { - $order = $request->get('sortOrder'); - $column = $request->get('sortField'); - $query->orderBy($column, $order); - } - - $totalRecords = $query->count(); - - $size = $request->get('size', 10); - if ($size == 0) { - $size = 10; - } - - if ($request->has('page') && $request->has('size')) { - $page = $request->get('page', 1); - $offset = ($page - 1) * $size; - - $query->skip($offset)->take($size); - } - - $filteredRecords = $query->count(); - $data = $query->with(['user', 'debiture', 'branch', 'tujuanPenilaian', 'jenisFasilitasKredit', 'penilaian'])->get(); - - $pageCount = ceil($totalRecords / $size); - - $currentPage = max(1, $request->get('page', 1)); - return response()->json([ - 'draw' => $request->get('draw'), - 'recordsTotal' => $totalRecords, - 'recordsFiltered' => $filteredRecords, - 'pageCount' => $pageCount, - 'page' => $currentPage, - 'totalCount' => $totalRecords, - 'data' => $data, - ]); - } - - - - public function dataForDatatablesData(Request $request, $type) - { - if (is_null($this->user) || !$this->user->can('jenis_aset.view')) { - //abort(403, 'Sorry! You are not allowed to view users.'); - } - - $models = [ - 'Bentuk Tanah' => BentukTanah::class, - 'Kontur Tanah' => KonturTanah::class, - 'Posisi Kavling' => PosisiKavling::class, - 'Ketinggian Tanah' => KetinggianTanah::class, - 'Kondisi Fisik Tanah' => KondisiFisikTanah::class, - 'Jenis Bangunan' => JenisBangunan::class, - 'Kondisi Bangunan' => KondisiBangunan::class, - 'Sifat Bangunan' => SifatBangunan::class, - 'Spek Kategori Bangunan' => SpekKategoritBangunan::class, - 'Spek Bangunan' => SpekBangunan::class, - 'Sarana Pelengkap' => SaranaPelengkap::class, - 'Lalu Lintas Depan Lokasi' => LaluLintasLokasi::class, - 'Tingkat Keramaian' => TingkatKeramaian::class, - 'Golongan Masyarakat Sekitar' => GolonganMasySekitar::class, - 'Lantai Unit' => Lantai::class, - 'View Unit' => ViewUnit::class, - 'Perkerasan jalan' => PerkerasanJalan::class, - 'Jenis pesawat' => JenisPesawat::class, - 'Model alat berat' => ModelAlatBerat::class, - 'Jenis kapal' => JenisKapal::class, - 'Jenis kendaraan' => JenisKendaraan::class, - 'Terletak di Area' => TerletakArea::class, - 'Posisi unit' => PosisiUnit::class, - 'Bentuk unit' => BentukUnit::class, - 'Fasilitas Umum Dekat Objek' => FasilitasObjek::class, - 'Merupakan Daerah' => MerupakanDaerah::class, - 'Jenis unit' => JenisUnit::class, - 'Foto Objek Jaminan' => FotoObjekJaminan::class, - ]; - - - if (array_key_exists($type, $models)) { - $query = $models[$type]::query(); - } else { - throw new InvalidArgumentException("Invalid type: $type"); - } - - if ($request->has('search') && !empty($request->get('search'))) { - $search = $request->get('search'); - $query->where(function ($q) use ($search) { - $q->where('code', 'LIKE', "%$search%"); - $q->orWhere('name', 'LIKE', "%$search%"); - }); - } - - // Apply sorting if provided - if ($request->has('sortOrder') && !empty($request->get('sortOrder'))) { - $order = $request->get('sortOrder'); - $column = $request->get('sortField'); - $query->orderBy($column, $order); - } - - // Get the total count of records - $totalRecords = $query->count(); - - // Apply pagination if provided - if ($request->has('page') && $request->has('size')) { - $page = $request->get('page'); - $size = $request->get('size'); - $offset = ($page - 1) * $size; // Calculate the offset - - $query->skip($offset)->take($size); - } - - // Get the filtered count of records - $filteredRecords = $query->count(); - - // Get the data for the current page - - if ($type == 'Spek Bangunan') { - $data = $query->with(['bangunanKategori'])->get(); - } else { - $data = $query->get(); - } - - - // Calculate the page count - $pageCount = ceil($totalRecords / $request->get('size')); - - // Calculate the current page number - $currentPage = 0 + 1; - - - // Return the response data as a JSON object - return response()->json([ - 'draw' => $request->get('draw'), - 'recordsTotal' => $totalRecords, - 'recordsFiltered' => $filteredRecords, - 'pageCount' => $pageCount, - 'page' => $currentPage, - 'totalCount' => $totalRecords, - 'data' => $data, - ]); - } - - public function destroy($id, $type) - { - try { - - $modelClass = $this->getModelClass($type); - - if (!$modelClass) { - return response()->json(['success' => false, 'message' => 'Invalid type specified.'], 400); + } catch (Exception $e) { + Log::error('Denah Store Error: ' . $e->getMessage()); + return response()->json([ + 'success' => false, + 'message' => 'Gagal menyimpan data: ' . $e->getMessage() + ], 500); + } } - $model = $modelClass::findOrFail($id); - $model->delete(); - return response()->json(['success' => true, 'message' => 'deleted successfully']); - } catch (ModelNotFoundException $e) { - return response()->json(['success' => false, 'message' => 'not found.'], 404); - } catch (Exception $e) { - return response()->json(['success' => false, 'message' => 'Failed to delete.'], 500); } - } + + /** + * Helper untuk upload file + * + * @param $file + * @param $type + * + * @return path name + */ - public function getPermohonanJaminanId($id, $dokumentId, $jaminanId) - { - return Permohonan::with([ - 'user', - 'debiture.province', - 'debiture.city', - 'debiture.district', - 'debiture.village', - 'branch', - 'tujuanPenilaian', - 'penilaian', - 'debiture.documents' => function ($query) use ($dokumentId, $jaminanId) { - $query->where('id', $dokumentId) - ->where('jenis_jaminan_id', $jaminanId); + public function uploadFile($file, $type) + { + if (!$file->isValid()) { + throw new Exception("Invalid file upload for {$type}"); } - ])->findOrFail($id); - } + + $fileName = time() . '_' . $file->getClientOriginalName(); + $path = $file->storeAs("public/surveyor/{$type}", $fileName); + + if ($path === false) { + throw new Exception("Failed to store file for {$type}"); + } + + return str_replace('public/', '', $path); + } + + // Metode untuk mendapatkan foto yang sudah diupload + + public function storeFoto(Request $request) + { + $validatedData = $this->validateFotoRequest($request); + try { + $log = []; + $photoCategories = [ + 'rute_menuju_lokasi', + 'foto_lingkungan', + ]; + + $lainnya = [ + 'foto_rute_lainnya' => ['foto_rute_lainnya', 'name_rute_lainnya'], + 'foto_lantai_lainnya' => ['foto_lantai_lainnya', 'name_lantai_lainnya'] + ]; + $inspeksi = Inspeksi::firstOrNew([ + 'permohonan_id' => $request->input('permohonan_id'), + 'dokument_id' => $request->input('dokument_id') + ]); + // Get existing foto_form data if it exists + $existingData = $inspeksi->exists && $inspeksi->foto_form + ? json_decode($inspeksi->foto_form, true) + : []; + + $formatFotojson = $existingData; + + // Upload berbagai jenis foto + $this->handleFileUpload($request, 'rute_menuju_lokasi', $formatFotojson); + $this->handleFileUpload($request, 'foto_lingkungan', $formatFotojson); + + $this->processFotoLantaiUnit($request, $formatFotojson); + + if ($request->hasFile('foto_objek')) { + $existingObjekJaminan = $formatFotojson['object_jaminan'] ?? []; + $formatFotojson['object_jaminan'] = $this->processObjekJaminanPhotos( + $request, + $existingObjekJaminan + ); + } + + foreach ($lainnya as $category => $fields) { + $photoField = $fields[0]; + $nameField = $fields[1]; + $descriptionField = $fields[2] ?? null; + + if ($request->hasFile($photoField)) { + $newPhotos = $this->processPhotoLainnya( + $request, + $fields, + $existingData[$category] ?? [] + ); + + $formatFotojson[$category] = $newPhotos; + } + } + // // Process single files + $singleFiles = ['foto_basement', 'foto_gerbang', 'pendamping']; + foreach ($singleFiles as $file) { + if ($request->hasFile($file)) { + // Hapus file lama jika ada + if (isset($formatFotojson[$file])) { + $this->deleteOfFile($formatFotojson[$file]); + } + + // Upload dan simpan file baru + $formatFotojson[$file] = $this->uploadFile($request->file($file), $file); + + } + } + + // Update record + if (!empty($formatFotojson)) { + $inspeksi->foto_form = json_encode($formatFotojson); + $inspeksi->save(); + + return response()->json([ + 'success' => true, + 'message' => 'Data berhasil disimpan', + 'data' => $formatFotojson, + 'log' => $log + ], 200); + } + + return response()->json([ + 'success' => false, + 'message' => 'Tidak ada data untuk disimpan' + ], 400); + } catch (Exception $e) { + return response()->json([ + 'success' => false, + 'message' => 'Failed to upload: ' . $e->getMessage() + ], 500); + } + } + + /** + * Custom validation request for foto + */ + public function validateFotoRequest(Request $request) + { + $maxSize = getMaxFileSize('Foto'); + return $request->validate([ + 'permohonan_id' => 'required', + 'dokument_id' => 'required', + 'pendamping' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp,bmp,tiff,heic,heif|max:' . $maxSize, + 'foto_objek.*' => 'required|image|mimes:jpeg,png,jpg,gif,svg,webp,bmp,tiff,heic,heif|max:' . $maxSize, + 'name_objek.*' => 'required|string|max:255', + + 'name_lingkungan.*' => 'required|string|max:255', + 'foto_rute.*' => 'required|image|mimes:jpeg,png,jpg,gif,svg,webp,bmp,tiff,heic,heif|max:' . $maxSize, + 'name_rute.*' => 'required|string|max:255', + 'lantai.*' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp,bmp,tiff,heic,heif|max:' . $maxSize, + + 'name_rute_lainnya.*' => 'nullable|string', + 'foto_rute_lainnya.*' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp,bmp,tiff,heic,heif|max:' . $maxSize, + 'foto_lantai_lainnya.*' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp,bmp,tiff,heic,heif|max:' . $maxSize, + 'name_lantai_lainnya.*' => 'nullable|string|max:255', + 'foto_basement.*' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp,bmp,tiff,heic,heif|max:' . $maxSize, + 'name_basement.*' => 'nullable|string|max:255', + 'foto_gerbang' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp,bmp,tiff,heic,heif|max:' . $maxSize, + 'name_gerbang' => 'nullable|string|max:255', - private function getModelClass(string $type): ?string - { - return $this->modelClasses[$type] ?? null; - } + 'name_lantai_unit' => 'array', + ]); + } + private function handleFileUpload(Request $request, $paramName, &$formatFotojson) + { + if ($request->hasFile($paramName)) { + $files = $request->file($paramName); - private $modelClasses = [ - 'bentuk-tanah' => BentukTanah::class, - 'kontur-tanah' => KonturTanah::class, - 'posisi-kavling' => PosisiKavling::class, - 'ketinggian-tanah' => KetinggianTanah::class, - 'kondisi-fisik-tanah' => KondisiFisikTanah::class, - 'jenis-bangunan' => JenisBangunan::class, - 'kondisi-bangunan' => KondisiBangunan::class, - 'sifat-bangunan' => SifatBangunan::class, - 'sarana-pelengkap' => SaranaPelengkap::class, - 'lalu-lintas-lokasi' => LaluLintasLokasi::class, - 'tingkat-keramaian' => TingkatKeramaian::class, - 'gol-mas-sekitar' => GolonganMasySekitar::class, - 'spek-kategori-bangunan' => SpekKategoritBangunan::class, - 'spek-bangunan' => SpekBangunan::class, - 'lantai-unit' => Lantai::class, - 'view-unit' => ViewUnit::class, - 'jenis-pesawat' => JenisPesawat::class, - 'model-alat-berat' => ModelAlatBerat::class, - 'jenis-kapal' => JenisKapal::class, - 'jenis-kendaraan' => JenisKendaraan::class, - 'terletak-area' => TerletakArea::class, - 'posisi-unit' => PosisiUnit::class, - 'bentuk-unit' => BentukUnit::class, - 'fasilitas-objek' => FasilitasObjek::class, - 'merupakan-daerah' => MerupakanDaerah::class, - 'jenis-unit' => JenisUnit::class, - 'perkerasan-jalan' => PerkerasanJalan::class, - 'foto-objek-jaminan' => FotoObjekJaminan::class - ]; + // Pastikan $files adalah array + if (!is_array($files)) { + $files = [$files]; + } + $formatFotoData = []; + foreach ($files as $index => $file) { + $timestamp = time(); + $originalName = $file->getClientOriginalName(); + $uniqueFileName = "{$timestamp}_{$originalName}"; + // Simpan file + $path = $file->storeAs("surveyor/{$paramName}", $uniqueFileName, 'public'); - public function getCommonData() - { - return [ - 'branches' => Branch::all(), - 'bentukTanah' => BentukTanah::all(), - 'konturTanah' => KonturTanah::all(), - 'posisiKavling' => PosisiKavling::all(), - 'ketinggianTanah' => KetinggianTanah::all(), - 'kondisiFisikTanah' => KondisiFisikTanah::all(), - 'jenisBangunan' => JenisBangunan::all(), - 'kondisiBangunan' => KondisiBangunan::all(), - 'sifatBangunan' => SifatBangunan::all(), - 'spekKategoriBangunan' => SpekKategoritBangunan::all(), - 'spekBangunan' => SpekBangunan::all(), - 'saranaPelengkap' => SaranaPelengkap::all(), - 'arahMataAngin' => ArahMataAngin::all(), - 'lantai' => Lantai::all(), - 'viewUnit' => ViewUnit::all(), - 'golMasySekitar' => GolonganMasySekitar::all(), - 'tingkatKeramaian' => TingkatKeramaian::all(), - 'laluLintasLokasi' => LaluLintasLokasi::all(), - 'jenisPesawat' => JenisPesawat::all(), - 'modelAlatBerat' => ModelAlatBerat::all(), - 'jenisKapal' => JenisKapal::all(), - 'jenisKendaraan' => JenisKendaraan::all(), - 'terletakArea' => TerletakArea::all(), - 'posisiUnit' => PosisiUnit::all(), - 'bentukUnit' => BentukUnit::all(), - 'fasilitasObjek' => FasilitasObjek::all(), - 'merupakanDaerah' => MerupakanDaerah::all(), - 'jenisUnit' => JenisUnit::all(), - 'jenisJaminan' => JenisJaminan::all(), - 'hubCadeb' => HubunganPemilikJaminan::all(), - 'hubPenghuni' => HubunganPenghuniJaminan::all(), - 'perkerasanJalan' => PerkerasanJalan::all(), - 'terletakDiArea' => TerletakArea::all(), - 'tujuanPenilaian' => TujuanPenilaian::all() - ]; - } + $fotoData = [ + 'path' => $path, + 'name' => ucwords(str_replace('_', ' ', $paramName)) . ' - ' . ($index + 1) + ]; + $formatFotoData[] = $fotoData; + } + // Struktur JSON yang konsisten + if (!isset($formatFotojson[$paramName][$paramName][0])) { + $formatFotojson[$paramName] = [ + $paramName => [ + $formatFotoData + ] + ]; + } else { + $formatFotojson[$paramName][$paramName][0] = array_merge( + $formatFotojson[$paramName][$paramName][0] ?? [], + $formatFotoData + ); + } - private const HEADERS = [ - 'bentuk-tanah' => ['Bentuk Tanah', 'bentuk-tanah'], - 'kontur-tanah' => ['Kontur Tanah', 'kontur-tanah'], - 'posisi-kavling' => ['Posisi Kavling', 'posisi-kavling'], - 'ketinggian-tanah' => ['Ketinggian Tanah', 'ketinggian-tanah'], - 'kondisi-fisik-tanah' => ['Kondisi Fisik Tanah', 'kondisi-fisik-tanah'], - 'jenis-bangunan' => ['Jenis Bangunan', 'jenis-bangunan'], - 'kondisi-bangunan' => ['Kondisi Bangunan', 'kondisi-bangunan'], - 'sifat-bangunan' => ['Sifat Bangunan', 'sifat-bangunan'], - 'sarana-pelengkap' => ['Sarana Pelengkap', 'sarana-pelengkap'], - 'lalu-lintas-lokasi' => ['Lalu Lintas Depan Lokasi', 'lalu-lintas-lokasi'], - 'tingkat-keramaian' => ['Tingkat Keramaian', 'tingkat-keramaian'], - 'gol-mas-sekitar' => ['Golongan Masyarakat Sekitar', 'gol-mas-sekitar'], - 'spek-kategori-bangunan' => ['Spek Kategori Bangunan', 'spek-kategori-bangunan'], - 'spek-bangunan' => ['Spek Bangunan', 'spek-bangunan'], - 'lantai-unit' => ['Lantai Unit', 'lantai-unit'], - 'view-unit' => ['View Unit', 'view-unit'], - 'perkerasan-jalan' => ['Perkerasan jalan', 'perkerasan-jalan'], - 'jenis-pesawat' => ['Jenis pesawat', 'jenis-pesawat'], - 'model-alat-berat' => ['Model alat berat', 'model-alat-berat'], - 'jenis-kapal' => ['Jenis kapal', 'jenis-kapal'], - 'jenis-kendaraan' => ['Jenis kendaraan', 'jenis-kendaraan'], - 'jenis-unit' => ['Jenis unit', 'jenis-unit'], - 'terletak-area' => ['Terletak di Area', 'terletak-area'], - 'merupakan-daerah' => ['Merupakan Daerah', 'merupakan-daerah'], - 'posisi-unit' => ['Posisi unit', 'posisi-unit'], - 'bentuk-unit' => ['Bentuk unit', 'bentuk-unit'], - 'fasilitas-objek' => ['Fasilitas Umum Dekat Objek', 'fasilitas-objek'], - 'foto-objek-jaminan' => ['Foto Objek Jaminan', 'foto-objek-jaminan'], - ]; + return $formatFotoData; + } - private function getAssetData(array $data): array - { - $alamatData = [ - 'address' => $data['address'] ?? null, - 'village_code' => $data['village_code'] ?? null, - 'district_code' => $data['district_code'] ?? null, - 'city_code' => $data['city_code'] ?? null, - 'province_code' => $data['province_code'] ?? null, - ]; + return []; + } - return [ - 'asset' => [ - 'debitur_perwakilan' => $data['debitur_perwakilan'] ?? [], - 'jenis_asset' => [ - $data['jenis_asset'] => ($data['jenis_asset'] === 'sesuai') - ? $data['jenis_asset_name'] - : ($data['jenis_asset_tidak_sesuai'] ?? null) - ], - 'alamat' => [ - $data['alamat_sesuai'] => $alamatData - ], - 'hub_cadeb' => [ - $data['hub_cadeb'] => ($data['hub_cadeb'] == 'sesuai') ? $data['hub_cadeb_sesuai'] : $data['hub_cadeb_tidak_sesuai'] - ], - 'hub_cadeb_penghuni' => [ - $data['hub_cadeb_penghuni'] => ($data['hub_cadeb_penghuni'] == 'sesuai') ? $data['hub_cadeb_penghuni_sesuai'] : $data['hub_penghuni_tidak_sesuai'] - ], - 'pihak_bank' => $data['pihak_bank'] ?? null, - 'kordinat_lng' => $data['kordinat_lng'] ?? null, - 'kordinat_lat' => $data['kordinat_lat'] ?? null, - ] - ]; - } + /** + * Process a photo + */ + protected function processFotoLantaiUnit(Request $request, &$formatFotojson) + { + // Pastikan foto_lantai_unit sudah ada di formatFotojson + if (!isset($formatFotojson['foto_lantai_unit'])) { + $formatFotojson['foto_lantai_unit'] = []; + } + // Ambil nama-nama lantai dari request + $lantaiNama = $request->input('lantai_nama', []); - private function getTanahData(array $data): array - { - return [ - 'tanah' => [ - 'luas_tanah' => $this->getFieldData( - $data, - 'luas_tanah', - true - ), - 'hadap_mata_angin' => [ - $data['hadap_mata_angin'] => $data['hadap_mata_angin'] == 'sesuai' ? $data['hadap_mata_angin_sesuai'] : $data['hadap_mata_angin_tidak_sesuai'] ?? null - ], - 'bentuk_tanah' => $this->getFieldData( - $data, - 'bentuk_tanah', - false, - 'lainnya' - ), - 'kontur_tanah' => $data['kontur_tanah'] ?? [], - 'ketinggian_tanah' => [ - 'ketinggian' => $data['ketinggian_jalan'] ?? null, - 'lebih_tinggi' => $data['ketinggian_lebih_tinggi'] ?? null, - 'lebih_rendah' => $data['ketinggian_lebih_rendah'] ?? null - ], - 'kontur_jalan' => $data['kontur_jalan'] ?? null, - 'ketinggian_jalan' => $data['ketinggian_jalan'] ?? [], - 'posisi_kavling' => $this->getFieldData( - $data, - 'posisi_kavling', - false, - 'lainnya' - ), + // Tambahan: gunakan lantai_index jika tersedia + $lantaiIndex = $request->input('lantai_index', null); - 'tusuk_sate' => $data['tusuk_sate'] ?? null, - 'lockland' => $data['lockland'] ?? null, - 'kondisi_fisik_tanah' => $this->getFieldData( - $data, - 'kondisi_fisik_tanah', - false, - 'lainnya' - ) - ] - ]; - } + // Cek apakah ada file foto lantai yang diunggah + $lantaiFiles = $request->file('foto_lantai_unit', []); + // Proses setiap file foto lantai + foreach ($lantaiFiles as $index => $files) { + // Pastikan $files adalah array + if (!is_array($files)) { + $files = [$files]; + } - private function getBangunanData($data, $request): array - { - $data = $request->all(); - $result = []; + // Gunakan lantai_index jika tersedia, jika tidak gunakan cara sebelumnya + $lantaiNomor = $lantaiIndex ?? ($index + 1); + // Inisialisasi array untuk lantai ini jika belum ada + if (!isset($formatFotojson['foto_lantai_unit'][$lantaiNomor])) { + $formatFotojson['foto_lantai_unit'][$lantaiNomor] = []; + } - foreach ($request->input('nama_bangunan') as $index => $buildingName) { - if (empty($buildingName)) { - continue; - } // Skip if building name is empty + foreach ($files as $fileIndex => $file) { + // Validasi file + if (!$file->isValid()) { + continue; // Lewati file yang tidak valid + } - $buildingData = []; - $buildingData['bagunan'] = $buildingName; + // Generate nama file unik + $uniqueFileName = 'lantai_unit_' . $lantaiNomor . '_' . $fileIndex . '_' . Str::random(10) . '.' . $file->getClientOriginalExtension(); - $specCategories = $request->input('spek_kategori_bangunan'); - $buildingData['spek_kategori_bangunan'] = []; + // Simpan file dengan nama asli + $path = $file->storeAs( + 'surveyor/lantai_unit', + $uniqueFileName . '/' . time() . '_' . $file->getClientOriginalName(), + 'public' + ); - if (!empty($specCategories)) { - foreach ($specCategories as $category) { - if (empty($category)) { - continue; - } // Skip empty categories + // Buat nama foto + $fotoName = "Foto Lantai {$lantaiNomor} - " . ($fileIndex + 1); - $specs = $request->input("spek_bangunan.{$index}.{$category}", []); + // Tambahkan detail foto ke array + $fotoDetail = [ + 'path' => $path, + 'name' => $fotoName + ]; - // Only add category if it has specifications - if (!empty($specs)) { - $buildingData['spek_kategori_bangunan'][$category] = $specs; + // Tambahkan ke array foto lantai unit sesuai struktur + $formatFotojson['foto_lantai_unit'][$lantaiNomor][] = $fotoDetail; + } + } + + return $formatFotojson; + } + + private function processObjekJaminanPhotos(Request $request, array $existingPhotos = []) + { + $photoField = 'foto_objek'; + $nameField = 'name_objek'; + $descriptionField = 'deskripsi_objek'; + + // Mulai dengan data lama + $result = $existingPhotos; + + if ($request->hasFile($photoField)) { + $newFiles = $request->file($photoField, []); + $newNames = $request->input($nameField, []); + $newDescriptions = $request->input($descriptionField, []); + + foreach ($newFiles as $key => $file) { + // Cari atau buat entri berdasarkan nama objek + $existingIndex = $this->findObjekJaminanIndexByName($result, $newNames[$key]); + + // Buat entri baru untuk file yang diunggah + $newPhotoEntry = [ + $nameField => $newNames[$key], + $photoField => $this->uploadFile($file, $photoField . '.' . $key), + $descriptionField => $newDescriptions[$key] ?? '', + ]; + + // Jika sudah ada, update; jika belum, tambahkan + if ($existingIndex !== false) { + // Hapus file lama jika ada + if (isset($result[$existingIndex][$photoField])) { + $this->deleteOfFile($result[$existingIndex][$photoField]); + } + $result[$existingIndex] = $newPhotoEntry; + } else { + $result[] = $newPhotoEntry; } } } - // Only add building data if it has specifications - if (!empty($buildingData['spek_kategori_bangunan'])) { - $result[] = $buildingData; + // Pastikan array tetap terurut dengan benar + return array_values($result); + } + + /** + * Cari index objek jaminan berdasarkan nama objek + */ + private function findObjekJaminanIndexByName(array $existingPhotos, string $name) + { + foreach ($existingPhotos as $index => $photo) { + if (isset($photo['name_objek']) && $photo['name_objek'] === $name) { + return $index; + } + } + return false; + } + + private function deleteOfFile($filePath) + { + if ($filePath && Storage::exists($filePath)) { + Storage::delete($filePath); } } + private function processPhotoLainnya(Request $request, array $fields, array $existingPhotos = []) + { + $result = $existingPhotos; // Start with existing photos + $photoField = $fields[0]; + $nameField = $fields[1]; + $descriptionField = $fields[2] ?? null; - return [ - 'bangunan' => [ - 'luas_tanah_bagunan' => $this->getFieldData( - $data, - 'luas_tanah_bagunan', - true - ), - 'jenis_bangunan' => $data['jenis_bangunan'] ?? null, - 'kondisi_bangunan' => $data['kondisi_bangunan'] ?? null, - 'sifat_bangunan' => $data['sifat_bangunan'] ?? null, - 'sifat_bangunan_input' => $data['sifat_bangunan_input'] ?? null, - 'spesifikasi_bangunan' => $result ?? null, - 'sarana_pelengkap' => $data['sarana_pelengkap'] ?? null, - 'sarana_pelengkap_input' => $data['sarana_pelengkap_input'] ?? null, - ], - ]; - } + if ($request->hasFile($photoField)) { + $newFiles = $request->file($photoField, []); + $newNames = $request->input($nameField, []); + $newDescriptions = $descriptionField ? $request->input($descriptionField, []) : []; - private function getLingkunganData($data, $request): array - { - return [ - 'lingkungan' => [ - 'jarak_jalan_utama' => $data['jarak_jalan_utama'] ?? null, - 'jalan_linkungan' => $data['jalan_linkungan'] ?? null, - 'jarak_cbd_point' => $data['jarak_cbd_point'] ?? null, - 'nama_cbd_point' => $data['nama_cbd_point'] ?? null, - 'lebar_perkerasan_jalan' => $data['lebar_perkerasan_jalan'] ?? null, - 'perkerasan_jalan' => $this->getFieldData( - $data, - 'perkerasan_jalan', - false, - 'lainnya' - ), - 'lalu_lintas' => $data['lalu_lintas'] ?? null, - 'gol_mas_sekitar' => $data['gol_mas_sekitar'] ?? null, - 'tingkat_keramaian' => $data['tingkat_keramaian'] ?? null, - 'terletak_diarea' => $this->getFieldData( - $data, - 'terletak_diarea', - false, - 'lainnya' - ), - 'disekitar_lokasi' => $data['disekitar_lokasi'] === 'yes' ? [ - 'kondisi' => $data['kondisi_bagunan_disekitar_lokasi'] ?? null, - 'sifat' => $data['sifat_bagunan_disekitar_lokasi'] ?? null, - ] : $data['disekitar_lokasi'], - 'kondisi_bagunan_disekitar_lokasi' => $data['kondisi_bagunan_disekitar_lokasi'] ?? null, - 'sifat_bagunan_disekitar_lokasi' => $data['sifat_bagunan_disekitar_lokasi'] ?? null, - 'dekat_makam' => $data['dekat_makam'] ?? null, - 'jarak_makam' => $data['jarak_makam'] ?? null, - 'nama_makam' => $data['nama_makam'] ?? null, - 'dekat_tps' => $data['dekat_tps'] ?? null, - 'jarak_tps' => $data['jarak_tps'] ?? null, - 'nama_tps' => $data['nama_tps'] ?? null, - 'dekat_lainnya' => $data['dekat_lainnya'] ?? null, - 'merupakan_daerah' => $data['merupakan_daerah'] ?? null, - 'fasilitas_dekat_object' => $data['fasilitas_dekat_object'] ?? null, - 'fasilitas_dekat_object_input' => $data['fasilitas_dekat_object_input'] ?? null, - ] - ]; - } + // Process each new file + foreach ($newFiles as $key => $file) { + // Create new photo entry + $newPhotoEntry = [ + $nameField => $newNames[$key] ?? '', // Use new name if provided + $photoField => $this->uploadFile($file, $photoField . '.' . $key) + ]; - private function getFactData($data, $request): array - { - $factData = [ - 'fakta' => [ - 'fakta_positif' => $data['fakta_positif'] ?? null, - 'fakta_negatif' => $data['fakta_negatif'] ?? null, - 'rute_menuju' => $data['rute_menuju'] ?? null, - 'batas_batas' => $data['batas_batas'] ?? null, - 'batas_batas_input' => $data['batas_batas_input'] ?? null, - 'kondisi_lingkungan' => $data['kondisi_lingkungan'] ?? null, - 'kondisi_lain_bangunan' => $data['kondisi_lain_bangunan'] ?? null, - 'informasi_dokument' => $data['informasi_dokument'] ?? null, - 'peruntukan' => $data['peruntukan'] ?? null, - 'kdb' => $data['kdb'] ?? null, - 'kdh' => $data['kdh'] ?? null, - 'gsb' => $data['gsb'] ?? null, - 'max_lantai' => $data['max_lantai'] ?? null, - 'klb' => $data['klb'] ?? null, - 'gss' => $data['gss'] ?? null, - 'pelebaran_jalan' => $data['pelebaran_jalan'] ?? null, - 'nama_petugas' => $data['nama_petugas'] ?? null, - 'keterangan' => $data['keterangan'] ?? null, - ] - ]; + // Add description if field exists + if ($descriptionField) { + $newPhotoEntry[$descriptionField] = $newDescriptions[$key] ?? ''; + } - - $inspeksi = Inspeksi::where('permohonan_id', $request->input('permohonan_id'))->where('dokument_id', $request->input('dokument_id'))->first(); - - - $fotoTypes = [ - 'foto_gistaru', - 'foto_bhumi', - 'foto_argis_region', - 'foto_tempat' - ]; - - if ($inspeksi) { - $dataForm = json_decode($inspeksi->data_form, true); - foreach ($fotoTypes as $fotoType) { - // Jika ada file baru diupload - if ($request->hasFile($fotoType)) { - $factData[$fotoType] = $this->updateOrDeleteFile($dataForm, $request, $fotoType); - } else { - $factData[$fotoType] = $dataForm[$fotoType] ?? null; + // Add to result + $result[] = $newPhotoEntry; } } - } else { - foreach ($fotoTypes as $fotoType) { - $factData[$fotoType] = $this->updateOrDeleteFile($data, $request, $fotoType); + + return $result; + } + + public function hapusFoto(Request $request) + { + try { + $permohonanId = $request->permohonan_id; + $dokumentId = $request->dokument_id; + $paramName = $request->param_name; + + $cleanRequestPath = str_replace('/storage/', '', $request->path); + + $inspeksi = Inspeksi::firstOrNew( + ['permohonan_id' => $permohonanId, 'dokument_id' => $dokumentId] + ); + $fotoForm = json_decode($inspeksi->foto_form, true); + + if (isset($fotoForm[$paramName][$paramName][0])) { + // Filter foto yang akan dihapus + + $tes = null; + $fotoForm[$paramName][$paramName][0] = array_values( + array_filter( + $fotoForm[$paramName][$paramName][0], + function ($foto) use ($cleanRequestPath) { + if ($foto['path'] === $cleanRequestPath) { + // Hapus file dari storage + \Storage::disk('public')->delete($cleanRequestPath); + return false; // Hapus elemen ini dari array + } + $tes = $foto['path']; + return true; + } + ) + ); + + + // Reset array index + $fotoForm[$paramName][$paramName][0] = array_values($fotoForm[$paramName][$paramName][0]); + + $inspeksi->foto_form = $fotoForm; + $inspeksi->save(); + + return response()->json([ + 'success' => true, + 'message' => 'Foto berhasil dihapus', + ], 200); + } + + return response()->json(['success' => false], 400); + } catch (Exception $e) { + return response()->json([ + 'success' => false, + 'message' => $e->getMessage() + ], 500); } } - return $factData; - } - private function updateOrDeleteFile($data, $request, $fileKey) - { - if ($request->hasFile($fileKey)) { - $file = $request->file($fileKey); - if ($file->isValid()) { - $fileName = time() . '_' . $file->getClientOriginalName(); - $path = $file->storeAs("public/surveyor/{$request->type}", $fileName); + public function getFoto(Request $request) + { + $permohonanId = $request->permohonan_id; + $dokumentId = $request->dokument_id; + $paramName = $request->param_name; - if ($path === false) { - throw new Exception("Failed to store file for {$fileKey}"); + $inspeksi = Inspeksi::firstOrNew( + ['permohonan_id' => $permohonanId, 'dokument_id' => $dokumentId] + ); + + // Decode foto_form + $fotoForm = json_decode($inspeksi->foto_form, true) ?? []; + + // Cari foto berdasarkan param name + $fotos = $this->findFotoByParamName($fotoForm, $paramName); + + + $param = $paramName == 'rute_menuju_lokasi' ? $fotos['rute_menuju_lokasi'][0] : $fotos['foto_lingkungan'][0]; + $data = array_map(function ($foto) { + return [ + 'name' => $foto['name'] ?? 'Foto', + 'path' => \Storage::url($foto['path']), + ]; + }, $param); + + return response()->json([ + 'fotos' => $data, + 'success' => !empty($data) + ]); + } + + private function findFotoByParamName($fotoForm, $paramName) + { + // Mapping parameter name ke struktur JSON + $paramMapping = [ + 'rute_menuju_lokasi' => ['rute_menuju_lokasi'], + 'foto_lingkungan' => ['foto_lingkungan'], + ]; + + // // Traverse array menggunakan mapping + $fotos = $fotoForm; + if (isset($paramMapping[$paramName])) { + foreach ($paramMapping[$paramName] as $key) { + $fotos = $fotos[$key] ?? []; } - if (isset($data[$fileKey]) && $data[$fileKey]) { - $this->deleteFile($data[$fileKey]); + } + + return is_array($fotos) ? $fotos : []; + } + + public function hapusLantai(Request $request) + { + $permohonanId = $request->permohonan_id; + $dokumentId = $request->dokument_id; + + // Normalisasi path foto + $cleanRequestPath = str_replace(['storage/', 'surveyor/'], '', $request->foto_path); + + $inspeksi = Inspeksi::firstOrNew( + ['permohonan_id' => $permohonanId, 'dokument_id' => $dokumentId] + ); + $fotoLantaiUnit = json_decode($inspeksi->foto_form, true); + + // Konversi lantai ke string untuk konsistensi + $lantai = (string) $request->lantai; + + // Cek apakah lantai ada di array + $pat = null; + if (isset($fotoLantaiUnit['foto_lantai_unit'][$lantai])) { + // Filter foto, hapus foto yang sesuai + $fotoLantaiUnit['foto_lantai_unit'][$lantai] = array_filter( + $fotoLantaiUnit['foto_lantai_unit'][$lantai], + function ($foto) use ($cleanRequestPath) { + // Normalisasi path foto yang tersimpan + $storedPath = str_replace(['storage/', 'surveyor/'], '', $foto['path']); + + // Jika path cocok, hapus file dari storage + if ($storedPath === $cleanRequestPath) { + // Hapus file dari storage dengan berbagai kemungkinan path + $possiblePaths = [ + 'storage/surveyor/lantai_unit/' . $cleanRequestPath, + 'storage/surveyor/' . $cleanRequestPath, + 'storage/' . $cleanRequestPath, + $cleanRequestPath + ]; + + foreach ($possiblePaths as $path) { + if (Storage::disk('public')->exists($path)) { + Storage::disk('public')->delete($path); + break; + } + } + + return false; // Hapus dari array + } + return true; + } + ); + + // Reset index array + $fotoLantaiUnit['foto_lantai_unit'][$lantai] = array_values($fotoLantaiUnit['foto_lantai_unit'][$lantai]); + + // Hapus lantai jika tidak ada foto + if (empty($fotoLantaiUnit['foto_lantai_unit'][$lantai])) { + unset($fotoLantaiUnit['foto_lantai_unit'][$lantai]); } - return str_replace('public/', '', $path); + + // Update inspeksi + $inspeksi->foto_form = json_encode($fotoLantaiUnit); + $inspeksi->save(); + + return response()->json([ + 'success' => true, + 'foto_lantai_unit' => $pat + ]); + } + + return response()->json([ + 'success' => false, + 'message' => 'gagal menghapus' + ], 404); + } + + public function submitSurveyor($id) + { + try { + // Get button status check result + $buttonStatusCheck = $this->checkButtonStatus($id); + $buttonStatus = json_decode($buttonStatusCheck->getContent(), true); + + // Check if button should be disabled + if ($buttonStatus['buttonDisable']) { + return response()->json([ + 'success' => false, + 'message' => 'Form belum lengkap. Pastikan semua data telah diisi dengan benar.', + ], 422); + } + + // If validation passes, update permohonan status + $permohonan = Permohonan::findOrFail($id); + $permohonan->update([ + 'status' => 'done', + 'submitted_at' => now() + ]); + + return response()->json([ + 'success' => true, + 'message' => 'Form surveyor berhasil disubmit' + ], 200); + + } catch (Exception $e) { + return response()->json([ + 'success' => false, + 'message' => 'Terjadi kesalahan', + 'error' => $e->getMessage() + ], 500); + } + } + + public function checkButtonStatus($id) + { + try { + // Get all inspeksi records for this permohonan + $inspeksiRecords = Inspeksi::with(['dokument.jenisJaminan']) + ->where('permohonan_id', $id) + ->get(); + + if ($inspeksiRecords->isEmpty()) { + return response()->json(['buttonDisable' => true]); + } + + foreach ($inspeksiRecords as $inspeksi) { + $dataForm = json_decode($inspeksi->data_form, true); + $fotoForm = json_decode($inspeksi->foto_form, true); + $denahForm = json_decode($inspeksi->denah_form, true); + $dataPembanding = json_decode($inspeksi->data_pembanding, true); + + $jenisJaminan = $inspeksi->dokument->jenisJaminan->name ?? ''; + + $isTanahBangunan = !in_array( + strtoupper($jenisJaminan->name ?? ''), + ['KAPAL', 'PESAWAT', 'KENDARAAN', 'ALAT BERAT'] + ); + + $isInvalid = + empty($dataForm) || + empty($fotoForm) || + (($isTanahBangunan && empty($denahForm)) || + empty($dataPembanding)); + + if ($isInvalid) { + return response()->json(['buttonDisable' => true]); + } + } + + // If we get here, all checks passed + return response()->json(['buttonDisable' => false]); + + } catch (Exception $e) { + return response()->json([ + 'error' => 'Something went wrong', + 'message' => $e->getMessage(), + 'buttonDisable' => true + ], 500); + } + } + + public function storeJadwal(Request $request) + { + try { + $validate = $request->validate([ + 'id' => 'required', + 'waktu_penilaian' => 'required', + 'deskripsi_penilaian' => 'required' + ]); + + // $user = ['user' => 'rustammajid76@gmail.com']; + + // $emailData = [ + // 'email' => 'rustammajid76@gmail.com', + // 'subject' => 'Test', + // 'emailData' => '

Hello, World!

This is the email content. Waktu Penilaian:

' + // ]; + + // $this->sendMessage($emailData, $user); + + $id = $request->input('id'); + $penilaian = Penilaian::findOrFail($id); + + $penilaian->update([ + 'waktu_penilaian' => $validate['waktu_penilaian'], + 'deskripsi_penilaian' => $validate['deskripsi_penilaian'], + ]); + + return redirect() + ->route('surveyor.index') + ->with('success', 'Jadwal berhasil dibuat.'); + } catch (Exception $e) { + return response()->json(['buttonDisable' => $e->getMessage()]); + } + } + + public function storeAproved(Request $request, $id) + : JsonResponse + { + $data = []; + if (request()->ajax()) { + try { + $penilaian = Penilaian::findOrFail($id); + $penilaian->update([ + 'authorized_status' => 1, + ]); + + $data['status'] = 'success'; + $data['message'] = 'Jadwal ' . $request->noReg . ' berhasil di aprove'; + } catch (Exception $e) { + $data['status'] = 'error'; + $data['message'] = 'Gagal membuat jadwal: ' . $e->getMessage(); + } + } else { - throw new Exception("Invalid file upload for {$fileKey}"); + $data['status'] = 'error'; + $data['message'] = "no ajax request"; } - } elseif (isset($data[$fileKey]) && $data[$fileKey]) { - return $data[$fileKey]; - } else { - return null; - } - } - private function deleteFile($filePath) - { - $fullPath = storage_path('app/public/' . $filePath); - if (file_exists($fullPath)) { - unlink($fullPath); - } - } - - - private function getKapalData($data, $request): array - { - return [ - - 'action' => $data['action'] ?? null, - 'nama_wakil_debitur' => $data['nama_wakil_debitur'] ?? null, - 'hub_calon_debitur' => $data['hub_calon_debitur'] ?? null, - 'dermaga' => $data['dermaga'] ?? null, - 'desa_kelurahan' => $data['desa_kelurahan'] ?? null, - 'kecamatan' => $data['kecamatan'] ?? null, - 'kota_madya' => $data['kota_madya'] ?? null, - 'provinsi' => $data['provinsi'] ?? null, - 'jenis' => $data['jenis'] ?? null, - 'size' => $data['size'] ?? null, - 'kondisi' => $data['kondisi'] ?? null, - 'klasifikasi' => $data['klasifikasi'] ?? null, - - 'nama_kapal' => $data['nama_kapal'] ?? null, - 'pemilik_kapal' => $data['pemilik_kapal'] ?? null, - 'bendera' => $data['bendera'] ?? null, - 'nomor_selar' => $data['nomor_selar'] ?? null, - 'kapal' => $data['kapal'] ?? null, - 'galangan_kapal' => $data['galangan_kapal'] ?? null, - 'kapal_shipyard' => $data['kapal_shipyard'] ?? null, - 'tahun_pembuatan' => $data['tahun_pembuatan'] ?? null, - 'tahun_launcing' => $data['tahun_launcing'] ?? null, - 'dwt' => $data['dwt'] ?? null, - 'lwt' => $data['lwt'] ?? null, - 'gross_tonnage' => $data['gross_tonnage'] ?? null, - 'net_tonnage' => $data['net_tonnage'] ?? null, - 'tenaga_mesin' => $data['tenaga_mesin'] ?? null, - 'loa' => $data['loa'] ?? null, - 'lbp' => $data['lbp'] ?? null, - 'beam' => $data['beam'] ?? null, - 'depth' => $data['depth'] ?? null, - 'draft' => $data['draft'] ?? null, - - - 'lambung_kapal' => $data['lambung_kapal'] ?? null, - 'dek' => $data['dek'] ?? null, - 'struktur_rangka' => $data['struktur_rangka'] ?? null, - 'palka' => $data['palka'] ?? null, - 'pondasi_mesin' => $data['pondasi_mesin'] ?? null, - 'area_mesin' => $data['area_mesin'] ?? null, - 'cat_dan_korosi' => $data['cat_dan_korosi'] ?? null, - 'sistem_pengelasan' => $data['sistem_pengelasan'] ?? null, - 'deskripsi_struktur' => $data['deskripsi_struktur'] ?? null, - - 'sekoci' => $data['sekoci'] ?? null, - 'jaket_pelampung' => $data['jaket_pelampung'] ?? null, - 'alat_pemadaman' => $data['alat_pemadaman'] ?? null, - 'rambu_darurat' => $data['rambu_darurat'] ?? null, - 'sistem_alarm' => $data['sistem_alarm'] ?? null, - 'sistem_pencegah' => $data['sistem_pencegah'] ?? null, - 'kebakaran' => $data['kebakaran'] ?? null, - 'lampu_darurat' => $data['lampu_darurat'] ?? null, - 'deskripsi_peralatan' => $data['deskripsi_peralatan'] ?? null, - - 'gps' => $data['gps'] ?? null, - 'radar' => $data['radar'] ?? null, - 'radio_komunikasi' => $data['radio_komunikasi'] ?? null, - 'lampu_navigasi' => $data['lampu_navigasi'] ?? null, - 'sistem_kendali_otomatis' => $data['sistem_kendali_otomatis'] ?? null, - 'kompas' => $data['kompas'] ?? null, - 'deskripsi_navigasi' => $data['deskripsi_navigasi'] ?? null, - - 'mesin_utama' => $data['mesin_utama'] ?? null, - 'mesin_bantu' => $data['mesin_bantu'] ?? null, - 'pompa_pendingin' => $data['pompa_pendingin'] ?? null, - 'sistem_pelumasan' => $data['sistem_pelumasan'] ?? null, - 'propeller' => $data['propeller'] ?? null, - 'sistem_kelistrikan' => $data['sistem_kelistrikan'] ?? null, - 'deskripsi_mesin_penggerak' => $data['deskripsi_mesin_penggerak'] ?? null, - - 'lampu_navigasi' => $data['lampu_navigasi'] ?? null, - 'sistem_penerangan' => $data['sistem_penerangan'] ?? null, - 'sistem_panel_distribusi' => $data['sistem_panel_distribusi'] ?? null, - 'kabel_perangkat' => $data['kabel_perangkat'] ?? null, - 'deskripsi_kelistrikan' => $data['deskripsi_kelistrikan'] ?? null, - - 'kebersihan_dek_luar' => $data['kebersihan_dek_luar'] ?? null, - 'tangki_limbah' => $data['tangki_limbah'] ?? null, - 'sistem_pengelolaan_limbah' => $data['sistem_pengelolaan_limbah'] ?? null, - 'pengelolaan_air_ballast' => $data['pengelolaan_air_ballast'] ?? null, - 'deskripsi_kebersihan' => $data['deskripsi_kebersihan'] ?? null, - - 'fakta_positif' => $data['fakta_positif'] ?? null, - 'fakta_negatif' => $data['fakta_negatif'] ?? null, - 'analisa_makro' => $data['analisa_makro'] ?? null, - 'kesimpulan' => $data['kesimpulan'] ?? null, - 'catatan' => $data['catatan'] ?? null, - - ]; - } - public function getKendaraanData($data, $request): array - { - return [ - 'action' => $data['action'] ?? null, - 'tanggal_survey' => $data['tanggal_survey'] ?? null, - 'nama_wakil' => $data['nama_wakil'] ?? null, - 'hub_calon_debitur' => $data['hub_calon_debitur'] ?? null, - 'nama_jalan' => $data['nama_jalan'] ?? null, - 'perumahan_gang' => $data['perumahan_gang'] ?? null, - 'blok_nomor' => $data['blok_nomor'] ?? null, - 'desa_kelurahan' => $data['desa_kelurahan'] ?? null, - 'kecamatan' => $data['kecamatan'] ?? null, - 'kota_madya' => $data['kota_madya'] ?? null, - 'provinsi' => $data['provinsi'] ?? null, - 'kondisi' => $data['kondisi'] ?? null, - 'nomor_polisi' => $data['nomor_polisi'] ?? null, - 'nomor_polis_tidak_sesuai' => $data['nomor_polis_tidak_sesuai'] ?? null, - 'merek' => $data['merek'] ?? null, - 'merek_tidak_sesuai' => $data['merek_tidak_sesuai'] ?? null, - 'warna' => $data['warna'] ?? null, - 'warna_tidak_sesuai' => $data['warna_tidak_sesuai'] ?? null, - 'nomor_rangka' => $data['nomor_rangka'] ?? null, - 'nomor_rangka_tidak_sesuai' => $data['nomor_rangka_tidak_sesuai'] ?? null, - 'nomor_mesin' => $data['nomor_mesin'] ?? null, - 'nomor_mesin_tidak_sesuai' => $data['nomor_mesin_tidak_sesuai'] ?? null, - 'posisi_kilometer' => $data['posisi_kilometer'] ?? null, - 'transmisi' => $data['transmisi'] ?? null, - - - 'mesin_panel_instrument' => $data['mesin_panel_instrument'] ?? null, - 'fungsi_mesin_panel_instrument' => $data['fungsi_mesin_panel_instrument'] ?? null, - 'interior' => $data['interior'] ?? null, - 'interior' => $data['interior'] ?? null, - - 'jumlah_pintu' => $data['jumlah_pintu'] ?? null, - 'rangka_karoseri' => $data['rangka_karoseri'] ?? null, - 'ban' => $data['ban'] ?? null, - 'velg' => $data['velg'] ?? null, - 'bamper_depan' => $data['bamper_depan'] ?? null, - 'bamper_belakang' => $data['bamper_belakang'] ?? null, - 'lampu_depan' => $data['lampu_depan'] ?? null, - 'lampu_belakang' => $data['lampu_belakang'] ?? null, - 'kaca_kendaraan' => $data['kaca_kendaraan'] ?? null, - 'air_conditioner' => $data['air_conditioner'] ?? null, - 'tape_radio_cd' => $data['tape_radio_cd'] ?? null, - 'sensor_parkir' => $data['sensor_parkir'] ?? null, - 'sensor_camera_recorder' => $data['sensor_camera_recorder'] ?? null, - 'lcd' => $data['lcd'] ?? null, - 'sabuk_keselamatan' => $data['sabuk_keselamatan'] ?? null, - 'airbag' => $data['airbag'] ?? null, - 'asuransi' => $data['asuransi'] ?? null, - 'perusahaan_asuransi' => $data['perusahaan_asuransi'] ?? null, - 'tahun_berakhir' => $data['tahun_berakhir'] ?? null, - - - 'fakta_positif' => $data['fakta_positif'] ?? null, - 'fakta_negatif' => $data['fakta_negatif'] ?? null, - 'analisa_makro' => $data['analisa_makro'] ?? null, - 'kesimpulan' => $data['kesimpulan'] ?? null, - 'catatan' => $data['catatan'] ?? null, - ]; - } - - public function getMesinData($data, $request): array - { - return [ - 'action' => $data['action'] ?? null, - 'nama_wakil' => $data['nama_wakil'] ?? null, - 'nama_jalan' => $data['nama_jalan'] ?? null, - 'perumahan_gang' => $data['perumahan_gang'] ?? null, - 'blok' => $data['blok'] ?? null, - 'desa_kelurahan' => $data['desa_kelurahan'] ?? null, - 'kecamatan' => $data['kecamatan'] ?? null, - 'kota_madya' => $data['kota_madya'] ?? null, - 'provinsi' => $data['provinsi'] ?? null, - 'hub_calon_debitur' => $data['hub_calon_debitur'] ?? null, - 'tipe_model' => $data['tipe_model'] ?? null, - 'merek' => $data['merek'] ?? null, - 'tahun_pembuatan' => $data['tahun_pembuatan'] ?? null, - 'negara_pembuat' => $data['negara_pembuat'] ?? null, - 'kondisi_mesin' => $data['kondisi_mesin'] ?? null, - 'faktor_positif' => $data['faktor_positif'] ?? null, - 'faktor_negatif' => $data['faktor_negatif'] ?? null, - 'kesimpulan' => $data['kesimpulan'] ?? null, - 'catatan' => $data['catatan'] ?? null, - ]; - } - - public function getAlatBeratData($data, $request): array - { - return [ - 'action' => $data['action'] ?? null, - 'tanggal_survey' => $data['tanggal_survey'] ?? null, - 'nama_wakil' => $data['nama_wakil'] ?? null, - 'hub_calon_debitur' => $data['hub_calon_debitur'] ?? null, - 'dengan_wadeb' => $data['dengan_wadeb'] ?? null, - 'nama_jalan' => $data['nama_jalan'] ?? null, - 'perumahan_gang' => $data['perumahan_gang'] ?? null, - 'blok' => $data['blok'] ?? null, - 'desa_kelurahan' => $data['desa_kelurahan'] ?? null, - 'kecamatan' => $data['kecamatan'] ?? null, - 'kota_madya' => $data['kota_madya'] ?? null, - 'provinsi' => $data['provinsi'] ?? null, - 'jenis_model' => $data['jenis_model'] ?? null, - 'nomor_lambung' => $data['nomor_lambung'] ?? null, - 'model_unit' => $data['model_unit'] ?? null, - 'tahun_pembuatan' => $data['tahun_pembuatan'] ?? null, - 'merk' => $data['merk'] ?? null, - 'negara_pembuat' => $data['negara_pembuat'] ?? null, - 'tahun_pembelian' => $data['tahun_pembelian'] ?? null, - 'nomor_faktur' => $data['nomor_faktur'] ?? null, - 'nomor_kontrak' => $data['nomor_kontrak'] ?? null, - 'nama_pemilik' => $data['nama_pemilik'] ?? null, - 'alamat_pemilik' => $data['alamat_pemilik'] ?? null, - 'nomor_asuransi' => $data['nomor_asuransi'] ?? null, - 'nomor_rangka' => $data['nomor_rangka'] ?? null, - 'nomor_mesin' => $data['nomor_mesin'] ?? null, - 'hour_mesters' => $data['hour_mesters'] ?? null, - 'overhaul_mesin' => $data['overhaul_mesin'] ?? null, - - 'mesin_panel' => $data['mesin_panel'] ?? null, - 'fungsi_panel' => $data['fungsi_panel'] ?? null, - 'interior' => $data['interior'] ?? null, - 'rangka_Karoseri' => $data['rangka_Karoseri'] ?? null, - 'ban' => $data['ban'] ?? null, - 'velg' => $data['velg'] ?? null, - 'air_conditioner' => $data['air_conditioner'] ?? null, - 'aksesoris' => $data['aksesoris'] ?? null, - 'lcd' => $data['lcd'] ?? null, - 'perlengkapan' => $data['perlengkapan'] ?? null, - 'asuransi' => $data['asuransi'] ?? null, - 'perusahaan_asuransi' => $data['perusahaan_asuransi'] ?? null, - 'tahun_berakhir' => $data['tahun_berakhir'] ?? null, - 'sensor_kamera' => $data['sensor_kamera'] ?? null, - 'sabuk_keselamatan' => $data['sabuk_keselamatan'] ?? null, - 'air_bag' => $data['air_bag'] ?? null, - - 'faktor_positif' => $data['faktor_positif'] ?? null, - 'faktor_negatif' => $data['faktor_negatif'] ?? null, - 'kesimpulan' => $data['kesimpulan'] ?? null, - 'catatan' => $data['catatan'] ?? null, - ]; - } - - private function getPesawatData($data, $request): array - { - return [ - 'action' => $data['action'] ?? null, - 'tanggal_survey' => $data['tanggal_survey'] ?? null, - 'nama_wakil' => $data['nama_wakil'] ?? null, - 'hub_calon_debitur' => $data['hub_calon_debitur'] ?? null, - 'bandara' => $data['bandara'] ?? null, - 'desa_kelurahan' => $data['desa_kelurahan'] ?? null, - 'kecamatan' => $data['kecamatan'] ?? null, - 'kota_madya' => $data['kota_madya'] ?? null, - 'provinsi' => $data['provinsi'] ?? null, - - 'jenis_pesawat' => $data['jenis_pesawat'] ?? null, - 'size' => $data['size'] ?? null, - 'kondisi' => $data['kondisi'] ?? null, - 'nama_pesawat' => $data['nama_pesawat'] ?? null, - 'model' => $data['model'] ?? null, - 'nomor_registrasi' => $data['nomor_registrasi'] ?? null, - 'tahun_pembuatan' => $data['tahun_pembuatan'] ?? null, - 'certificate_of_airworthines' => $data['certificate_of_airworthines'] ?? null, - 'certificate_of_registration' => $data['certificate_of_registration'] ?? null, - 'total_service_hours' => $data['total_service_hours'] ?? null, - 'total_service_cycles' => $data['total_service_cycles'] ?? null, - - 'last_a_check' => $data['last_a_check'] ?? null, - 'next_a_check' => $data['next_a_check'] ?? null, - 'last_b_check' => $data['last_b_check'] ?? null, - 'next_b_check' => $data['next_b_check'] ?? null, - 'last_c_check' => $data['last_c_check'] ?? null, - 'next_c_check' => $data['next_c_check'] ?? null, - 'next_d_check' => $data['next_d_check'] ?? null, - 'last_d_check' => $data['last_d_check'] ?? null, - 'deskripsi_maintenence' => $data['deskripsi_maintenence'] ?? null, - - 'instrument_landing_system' => $data['instrument_landing_system'] ?? null, - 'traffic_collision_avoidance_system' => $data['traffic_collision_avoidance_system'] ?? null, - 'windshear' => $data['windshear'] ?? null, - 'electronic_flight' => $data['electronic_flight'] ?? null, - 'winglets' => $data['winglets'] ?? null, - 'deskripsi_konfigurasi' => $data['deskripsi_konfigurasi'] ?? null, - - 'maksimal_penumpang' => $data['maksimal_penumpang'] ?? null, - 'jumlah_kursi' => $data['jumlah_kursi'] ?? null, - 'kursi_pramugari_pramugara' => $data['kursi_pramugari_pramugara'] ?? null, - 'kartu_fitur_keselamatan' => $data['kartu_fitur_keselamatan'] ?? null, - 'sabuk_pengaman' => $data['sabuk_pengaman'] ?? null, - 'lampu_kabin' => $data['lampu_kabin'] ?? null, - 'lampu_pintu_keluar' => $data['lampu_pintu_keluar'] ?? null, - 'intercom_kabin' => $data['intercom_kabin'] ?? null, - 'deskripsi_kabin' => $data['deskripsi_kabin'] ?? null, - - 'badan_pesawat' => $data['badan_pesawat'] ?? null, - 'sayap_pesawat' => $data['sayap_pesawat'] ?? null, - 'ekor_pesawat' => $data['ekor_pesawat'] ?? null, - 'landing_gear' => $data['landing_gear'] ?? null, - 'sistem_pengelasan' => $data['sistem_pengelasan'] ?? null, - 'deskripsi_struktur' => $data['deskripsi_struktur'] ?? null, - - 'gps' => $data['gps'] ?? null, - 'radar' => $data['radar'] ?? null, - 'radio_komunikasi' => $data['radio_komunikasi'] ?? null, - 'lampu_navigasi' => $data['lampu_navigasi'] ?? null, - 'sistem_autopilot' => $data['sistem_autopilot'] ?? null, - 'deskripsi_navigasi' => $data['deskripsi_navigasi'] ?? null, - - 'tangki_bahan_bakar' => $data['tangki_bahan_bakar'] ?? null, - 'saluran_pipa_bahan_bakar' => $data['saluran_pipa_bahan_bakar'] ?? null, - 'pompa_bahan_bakar' => $data['pompa_bahan_bakar'] ?? null, - 'sistem_hidrolik_utama' => $data['sistem_hidrolik_utama'] ?? null, - 'sistem_pendigin_hidrolik' => $data['sistem_pendigin_hidrolik'] ?? null, - 'deskripsi_hidrolik' => $data['deskripsi_hidrolik'] ?? null, - - 'mesin_utama' => $data['mesin_utama'] ?? null, - 'sistem_pendorong' => $data['sistem_pendorong'] ?? null, - 'sistem_pendigin_mesin' => $data['sistem_pendigin_mesin'] ?? null, - 'sistem_pelumasan' => $data['sistem_pelumasan'] ?? null, - 'filter_dan_perangkat_pendukung' => $data['filter_dan_perangkat_pendukung'] ?? null, - 'deskripsi_kondisi_mesin' => $data['deskripsi_kondisi_mesin'] ?? null, - - 'jaket_pelampung' => $data['jaket_pelampung'] ?? null, - 'pintu_darurat' => $data['pintu_darurat'] ?? null, - 'alat_pemadaman_kebakaran' => $data['alat_pemadaman_kebakaran'] ?? null, - 'sistem_alaram_darurat' => $data['sistem_alaram_darurat'] ?? null, - 'sekoci' => $data['sekoci'] ?? null, - 'masker_oxigen' => $data['masker_oxigen'] ?? null, - 'sabuk_pengaman' => $data['sabuk_pengaman'] ?? null, - 'deskripsi_fungsi_keselamatan' => $data['deskripsi_fungsi_keselamatan'] ?? null, - - 'sistem_ventilasi_ac' => $data['sistem_ventilasi_ac'] ?? null, - 'sistem_penerangan_kabin' => $data['sistem_penerangan_kabin'] ?? null, - 'panel_informasi_penumpang' => $data['panel_informasi_penumpang'] ?? null, - 'sistem_hiburan_kabin' => $data['sistem_hiburan_kabin'] ?? null, - 'deskripsi_Interior' => $data['deskripsi_Interior'] ?? null, - - // Validasi untuk faktor dan kesimpulan - 'faktor_positif' => $data['faktor_positif'] ?? null, - 'faktor_negatif' => $data['faktor_negatif'] ?? null, - 'kesimpulan' => $data['kesimpulan'] ?? null, - 'catatan' => $data['catatan'] ?? null, - ]; - } - - - - - private function getUnitData($data, $request): array - { - return [ - 'action' => $data['action'] ?? null, - 'luas_unit' => $this->getFieldData( - $data, - 'luas_unit', - true - ), - 'kondisi_unit' => $data['kondisi_unit'] ?? null, - 'posisi_unit' => $data['posisi_unit'] ?? null, - 'lantai' => $data['lantai'] ?? null, - 'view' => $data['view'] ?? null, - 'bentuk_unit' => $data['bentuk_unit'] ?? null, - ]; - } - - - - /** - * Helper untuk upload file - * - * @param $file - * @param $type - * @return path name - */ - - - public function uploadFile($file, $type) - { - if (!$file->isValid()) { - throw new Exception("Invalid file upload for {$type}"); + return response()->json($data); } - $fileName = time() . '_' . $file->getClientOriginalName(); - $path = $file->storeAs("public/surveyor/{$type}", $fileName); + public function storeFreeze(Request $request) + { - if ($path === false) { - throw new Exception("Failed to store file for {$type}"); + $permohonanId = $request->get('id'); + + // Check for existing freeze request with status 0 + $existingFreeze = Authorization::where('permohonan_id', $permohonanId) + ->where('status', '0') + ->where('request', 'freeze') + ->first(); + + if ($existingFreeze) { + DB::rollBack(); + return redirect()->route('surveyor.index')->with('warning', 'Sudah ada request freeze yang belum diproses untuk permohonan ini.'); + } + + + + $data = [ + 'permohonan_id' => $permohonanId, + 'alasan' => $request->get('alasan'), + 'status' => '0', + 'user_id' => Auth::id(), + 'jenis' => 'sla', + 'request' => 'freeze' + ]; + + $otor = Authorization::create($data); + if($otor) { + DB::commit(); + return redirect()->route('surveyor.index')->with('success', 'Request freeze berhasil dikirim, menunggu persetujuan pejabat terkait'); + } + + return redirect()->route('surveyor.index')->with('error', 'Request freeze gagal dikirim, silahkan coba lagi'); } - return str_replace('public/', '', $path); - } + public function storeDataPembanding(Request $request) + { + try { + DB::beginTransaction(); + + $maxSize = getMaxFileSize('Foto'); + $validator = $request->validate([ + 'permohonan_id' => 'required|exists:permohonan,id', + 'type' => 'required|string', + 'dokument_id' => 'required', + 'foto_objek' => 'nullable|image|max:' . $maxSize, + 'foto_objek_pembanding.*' => 'nullable|image|max:' . $maxSize, + ]); + + $objekPenilaian = $this->formatObjekPenilaian($request); + if ($request->hasFile('foto_objek')) { + $newFoto = $this->handleupdateOrDeleteFile( + $request->file('foto_objek'), + $request['type'] = 'pembanding', + 'objek_penilaian' + ); + + // Update foto_form + $inspeksi = Inspeksi::where('permohonan_id', $request->input('permohonan_id')) + ->where('dokument_id', $request->input('dokument_id')) + ->first(); + + if ($inspeksi) { + $fotoForm = json_decode($inspeksi->foto_form, true) ?: []; + if (!isset($fotoForm['object_jaminan'])) { + $fotoForm['object_jaminan'] = []; + } + if (empty($fotoForm['object_jaminan'])) { + $fotoForm['object_jaminan'][] = ['foto_objek' => $newFoto]; + } else { + $fotoForm['object_jaminan'][0]['foto_objek'] = $newFoto; + } + + $inspeksi->foto_form = json_encode($fotoForm); + $inspeksi->save(); + } + + $objekPenilaian['foto_objek'] = $newFoto; + } - /** - * Helper untuk memetakan array dengan inputannya - * - * @param array $keys Array kunci - * @param array $values Array nilai/input - * @return array - */ - private function mapArrayWithInputs(array $keys, array $values): array - { - $result = []; + $formattedData = [ + 'permohonan_id' => $request->input('permohonan_id'), + 'type' => $request->input('type'), + 'dokument_id' => $request->input('dokument_id'), + 'objek_penilaian' => $objekPenilaian, + 'data_pembanding' => $this->formatDataPembanding($request) + ]; - foreach ($keys as $key) { - // Jika checkbox dicentang, ambil nilai input yang sesuai - // Gunakan nilai dari $values berdasarkan nama checkbox - $result[$key] = $values[$key] ?? null; + + $inspeksi = $this->saveInspeksi($formattedData); + + DB::commit(); + + return response()->json([ + 'success' => true, + 'message' => 'Data berhasil disimpan', + 'data' => $formattedData + ], 200); + + } catch (Exception $e) { + DB::rollBack(); + return response()->json([ + 'success' => false, + 'message' => 'Gagal menyimpan data: ' . $e->getMessage() + ], 500); + } } - return $result; - } + private function formatObjekPenilaian($request) + { + $fields = [ + 'address', + 'village_code', + 'district_code', + 'city_code', + 'province_code', + 'luas_tanah', + 'luas_tanah_bagunan', + 'total', + 'diskon', + 'harga_diskon', + 'status_nara_sumber', + 'harga', + 'nama_nara_sumber', + 'hak_properti', + 'telepon', + 'kordinat_lat', + 'kordinat_lng', + 'jenis_aset', + 'penawaran', + ]; + + $inspeksi = Inspeksi::where('permohonan_id', $request->input('permohonan_id')) + ->where('dokument_id', $request->input('dokument_id')) + ->first(); + + if ($inspeksi) { + $needsSave = false; + + // Handle foto_form + $fotoForm = json_decode($inspeksi->foto_form, true) ?: []; + if (!isset($fotoForm['object_jaminan'])) { + $fotoForm['object_jaminan'] = [['foto_objek' => null]]; + $needsSave = true; + } + + // Handle data_form + $dataForm = json_decode($inspeksi->data_form, true) ?: []; + + // Inisialisasi struktur data jika belum ada + if (!isset($dataForm['bangunan'])) { + $dataForm['bangunan'] = []; + $needsSave = true; + } + + if (!isset($dataForm['tanah'])) { + $dataForm['tanah'] = []; + $needsSave = true; + } + + if (!isset($dataForm['asset'])) { + $dataForm['asset'] = []; + $needsSave = true; + } + + // Update data dengan mempertahankan struktur sesuai/tidak sesuai + foreach ($fields as $field) { + if ($request->filled($field)) { + $newValue = $request->input($field); + + // Fields untuk tanah + if (in_array($field, ['luas_tanah'])) { + // Pastikan struktur array ada sebelum diakses + if (!isset($dataForm['tanah']['luas_tanah'])) { + $dataForm['tanah']['luas_tanah'] = []; + } + + $cekLuas = isset($dataForm['tanah']['luas_tanah']['sesuai']) && $dataForm['tanah']['luas_tanah']['sesuai'] === 'sesuai' + ? 'sesuai' + : 'tidak sesuai'; + + $dataForm['tanah']['luas_tanah'][$cekLuas] = $newValue; + $needsSave = true; + } // Fields untuk bangunan + else if (in_array($field, ['luas_tanah_bagunan'])) { + if (!isset($dataForm['bangunan']['luas_tanah_bagunan'])) { + $dataForm['bangunan']['luas_tanah_bagunan'] = []; + } + + $cekBanguan = isset($dataForm['bangunan']['luas_tanah_bagunan']['sesuai']) && $dataForm['bangunan']['luas_tanah_bagunan']['sesuai'] === 'sesuai' + ? 'sesuai' + : 'tidak sesuai'; + + $dataForm['bangunan']['luas_tanah_bagunan'][$cekBanguan] = $newValue; + $needsSave = true; + } // Fields untuk alamat dalam asset + else if (in_array($field, [ + 'address', + 'village_code', + 'district_code', + 'city_code', + 'province_code' + ])) { + + if (!isset($dataForm['asset']['alamat'])) { + $dataForm['asset']['alamat'] = []; + } + + $alamatStatus = $dataForm['asset']['alamat'] == 'sesuai' ? 'sesuai' : 'tidak sesuai'; + if (!isset($dataForm['asset']['alamat'][$alamatStatus])) { + $dataForm['asset']['alamat'][$alamatStatus] = []; + } + + $dataForm['asset']['alamat'][$alamatStatus][$field] = $newValue; + } // Jenis asset dalam asset + else if ($field === 'jenis_asset') { + $assetStatus = $request->input('asset_status', 'sesuai'); + $dataForm['asset']['jenis_asset'] = [ + $assetStatus => $newValue + ]; + } // Fields lainnya dalam asset + else { + if (!isset($dataForm['asset'][$field])) { + $dataForm['asset'][$field] = []; + } + $dataForm['asset'][$field] = $newValue; + } + $needsSave = true; + } + } + + if ($needsSave) { + $inspeksi->foto_form = json_encode($fotoForm); + $inspeksi->data_form = json_encode($dataForm); + $inspeksi->save(); + } + + $existingFoto = $fotoForm['object_jaminan'][0]['foto_objek'] ?? null; + + // Gabungkan data dari tanah, bangunan, dan asset + $objekPenilaian = array_merge( + ['foto_objek' => $existingFoto], + $dataForm['tanah'] ?? [], + $dataForm['bangunan'] ?? [], + array_reduce($fields, function ($carry, $field) use ($request, $dataForm) { + if (isset($dataForm['asset'][$field])) { + if (is_array($dataForm['asset'][$field])) { + if (isset($dataForm['asset'][$field]['sesuai'])) { + $carry[$field] = $dataForm['asset'][$field]['sesuai']; + } else if (isset($dataForm['asset'][$field]['tidak sesuai'])) { + $carry[$field] = $dataForm['asset'][$field]['tidak sesuai']; + } + } else { + $carry[$field] = $dataForm['asset'][$field]; + } + } else { + $carry[$field] = $request->input($field); + } + return $carry; + }, []) + ); + + } else { + // Inisialisasi data baru + $objekPenilaian = array_reduce($fields, function ($carry, $field) use ($request) { + $carry[$field] = $request->input($field); + return $carry; + }, ['foto_objek' => null]); + } + + return $objekPenilaian; + } + + private function handleupdateOrDeleteFile($file, $type, $prefix) + { + try { + if ($file) { + // Generate nama file unik + $fileName = $prefix . '_' . uniqid() . '_' . time() . '.' . $file->getClientOriginalExtension(); + $path = "{$type}/" . date('Y/m'); + Storage::makeDirectory("public/{$path}"); + $filePath = $file->storeAs("public/{$path}", $fileName); + return str_replace('public/', '', $filePath); + } + + return null; + + } catch (Exception $e) { + Log::error('File upload error: ' . $e->getMessage()); + throw new Exception("Gagal mengupload file: " . $e->getMessage()); + } + } + + private function formatDataPembanding($request) + { + $dataPembanding = []; + $pembandingCount = count($request->input('address_pembanding', [])); + $fotoPembanding = $request->file('foto_objek_pembanding') ?? []; + + $existingData = null; + if ($request->has('permohonan_id') && $request->has('dokument_id')) { + $inspeksi = Inspeksi::where('permohonan_id', $request->input('permohonan_id')) + ->where('dokument_id', $request->input('dokument_id')) + ->first(); + + if ($inspeksi) { + $existingData = json_decode($inspeksi->data_pembanding, true) ?? []; + } + } + + for ($i = 0; $i < $pembandingCount; $i++) { + $pembanding = $this->formatSinglePembanding($request, $i); - /** - * Helper method generic untuk mengambil data field - * - * @param array $data Array sumber data - * @param string $fieldName Nama field - * @param bool $checkKesesuaian Apakah perlu cek kesesuaian - * @param string|null $extraField Field tambahan (misal 'lainnya') - * @return array - */ - private function getFieldData( - array $data, - string $fieldName, - bool $checkKesesuaian = false, - ?string $extraField = null - ): array { - if ($checkKesesuaian) { + $existingFoto = null; + if ($existingData && isset($existingData['data_pembanding'][$i]['foto_objek'])) { + $existingFoto = $existingData['data_pembanding'][$i]['foto_objek']; + } + + // Penanganan foto pembanding + if (isset($fotoPembanding[$i]) && $fotoPembanding[$i]->isValid()) { + $pembanding['foto_objek'] = $this->handleupdateOrDeleteFile( + $fotoPembanding[$i], + 'pembanding', + "pembanding_{$i}" + ); + } else { + $pembanding['foto_objek'] = $existingFoto; + } + + $dataPembanding[] = $pembanding; + } + + return $dataPembanding; + } + + private function formatSinglePembanding($request, $index) + { + $fields = [ + 'address', + 'village_code', + 'district_code', + 'city_code', + 'province_code', + 'tahun', + 'luas_tanah', + 'luas_bangunan', + 'tahun_bangunan', + 'status_nara_sumber', + 'harga', + 'harga_diskon', + 'diskon', + 'total', + 'nama_nara_sumber', + 'peruntukan', + 'penawaran', + 'telepon', + 'hak_properti', + 'kordinat_lat', + 'kordinat_lng', + 'jenis_aset', + 'foto_objek' + ]; + + $pembanding = []; + foreach ($fields as $field) { + $inputName = "{$field}_pembanding"; + $inputValue = $request->input($inputName); + + // Pastikan input adalah array dan index valid + if (is_array($inputValue) && isset($inputValue[$index])) { + $pembanding[$field] = $inputValue[$index]; + } else { + $pembanding[$field] = null; + } + } + + + return $pembanding; + } + + private function saveInspeksi($formattedData) + { + $inspeksi = Inspeksi::updateOrCreate( + [ + 'permohonan_id' => $formattedData['permohonan_id'], + 'dokument_id' => $formattedData['dokument_id'] + ], + [ + 'data_pembanding' => json_encode($formattedData), + 'name' => $formattedData['type'] + ] + ); + + return $inspeksi; + } + + /** + * Form inspeksi. + */ + + public function formInspeksi(Request $request, $id) + { + + $validated = $request->validate([ + 'form' => 'required|in:create-inspeksi', + 'inspeksi' => 'required|exists:permohonan,id', + 'dokument' => 'required', + 'jenisjaminan' => 'required' + ]); + + $dokumentId = $validated['dokument']; + $jaminanId = $validated['jenisjaminan']; + + $permohonan = $this->getPermohonanJaminanId($id, $dokumentId, $jaminanId); + + $link_url_region = Teams::with('regions', 'teamsUsers') + ->whereHas('teamsUsers', function ($query) { + $query->where('user_id', Auth::user()->id); + })->first(); + + $branches = Branch::all(); + $provinces = Province::all(); + + + $surveyor = $id; + $basicData = $this->getCommonData(); + + $inpeksi = Inspeksi::where('permohonan_id', $id)->where('dokument_id', $dokumentId)->first(); + $forminspeksi = null; + if ($inpeksi) { + $forminspeksi = json_decode($inpeksi->data_form, true); + } + + // Default: gunakan data dari debitur + $debitur = Debiture::find($permohonan->debiture_id); + + $provinceCode = $debitur->province_code; + $cityCode = $debitur->city_code; + $districtCode = $debitur->district_code; + + // Jika alamat tidak sesuai, override dengan kode dari alamat + + $cekAlamat = $forminspeksi['asset']['alamat']['tidak sesuai'] ?? null; + + if ($cekAlamat) { + $provinceCode = $cekAlamat['province_code'] ?? $provinceCode; + $cityCode = $cekAlamat['city_code'] ?? $cityCode; + $districtCode = $cekAlamat['district_code'] ?? $districtCode; + } + + // Ambil data menggunakan kode yang telah ditentukan + $cities = City::where('province_code', $provinceCode)->get(); + $districts = District::where('city_code', $cityCode)->get(); + $villages = Village::where('district_code', $districtCode)->get(); + return view('lpj::surveyor.components.inspeksi', compact( + 'permohonan', + 'surveyor', + 'branches', + 'provinces', + 'debitur', + 'cities', + 'districts', + 'villages', + 'link_url_region', + 'forminspeksi', + 'basicData', + 'cekAlamat' + )); + } + + public function getPermohonanJaminanId($id, $dokumentId, $jaminanId) + { + return Permohonan::with([ + 'user', + 'debiture.province', + 'debiture.city', + 'debiture.district', + 'debiture.village', + 'branch', + 'tujuanPenilaian', + 'penilaian', + 'debiture.documents' => function ($query) use ($dokumentId, $jaminanId) { + $query->where('id', $dokumentId) + ->where('jenis_jaminan_id', $jaminanId); + } + ])->findOrFail($id); + } + + public function getCommonData() + { return [ - $data[$fieldName] ?? '' => ($data[$fieldName] ?? '') === 'sesuai' - ? ($data["{$fieldName}_sesuai"] ?? '') - : ($data["{$fieldName}_tidak_sesuai"] ?? '') + 'branches' => Branch::all(), + 'bentukTanah' => BentukTanah::all(), + 'konturTanah' => KonturTanah::all(), + 'posisiKavling' => PosisiKavling::all(), + 'ketinggianTanah' => KetinggianTanah::all(), + 'kondisiFisikTanah' => KondisiFisikTanah::all(), + 'jenisBangunan' => JenisBangunan::all(), + 'kondisiBangunan' => KondisiBangunan::all(), + 'sifatBangunan' => SifatBangunan::all(), + 'spekKategoriBangunan' => SpekKategoritBangunan::all(), + 'spekBangunan' => SpekBangunan::all(), + 'saranaPelengkap' => SaranaPelengkap::all(), + 'arahMataAngin' => ArahMataAngin::all(), + 'lantai' => Lantai::all(), + 'viewUnit' => ViewUnit::all(), + 'golMasySekitar' => GolonganMasySekitar::all(), + 'tingkatKeramaian' => TingkatKeramaian::all(), + 'laluLintasLokasi' => LaluLintasLokasi::all(), + 'jenisPesawat' => JenisPesawat::all(), + 'modelAlatBerat' => ModelAlatBerat::all(), + 'jenisKapal' => JenisKapal::all(), + 'jenisKendaraan' => JenisKendaraan::all(), + 'terletakArea' => TerletakArea::all(), + 'posisiUnit' => PosisiUnit::all(), + 'bentukUnit' => BentukUnit::all(), + 'fasilitasObjek' => FasilitasObjek::all(), + 'merupakanDaerah' => MerupakanDaerah::all(), + 'jenisUnit' => JenisUnit::all(), + 'jenisJaminan' => JenisJaminan::all(), + 'hubCadeb' => HubunganPemilikJaminan::all(), + 'hubPenghuni' => HubunganPenghuniJaminan::all(), + 'perkerasanJalan' => PerkerasanJalan::all(), + 'terletakDiArea' => TerletakArea::all(), + 'tujuanPenilaian' => TujuanPenilaian::all() ]; } - $result = [ - $fieldName => $data[$fieldName] ?? null - ]; + /** + * Denah. + */ - if ($extraField) { - $result[$extraField] = $data["{$fieldName}_{$extraField}"] ?? null; + public function denah(Request $request, $id) + { + $validated = $request->validate([ + 'form' => 'required|in:create-denah', + 'denah' => 'required|exists:permohonan,id', + 'dokument' => 'required', + 'jenisjaminan' => 'required' + ]); + + $dokumentId = $validated['dokument']; + $jaminanId = $validated['jenisjaminan']; + + $permohonan = $this->getPermohonanJaminanId($id, $dokumentId, $jaminanId); + + $denah = null; + + $inpeksi = Inspeksi::where('permohonan_id', $id)->where('dokument_id', $dokumentId)->first(); + $formDenah = null; + if ($inpeksi) { + $formDenah = json_decode($inpeksi->denah_form, true); + } + + // return response()->json($formDenah); + return view('lpj::surveyor.components.denah', compact('permohonan', 'denah', 'formDenah')); } - return $result; - } + /** + * Foto. + */ + + public function foto(Request $request, $id) + { + $validated = $request->validate([ + 'form' => 'required|in:create-foto', + 'foto' => 'required|exists:permohonan,id', + 'dokument' => 'required', + 'jenisjaminan' => 'required' + ]); + + $dokumentId = $validated['dokument']; + $jaminanId = $validated['jenisjaminan']; + $fotoObjekJaminan = FotoObjekJaminan::all(); + + $permohonan = $this->getPermohonanJaminanId($id, $dokumentId, $jaminanId); + + $surveyor = $id; + $branches = Branch::all(); + $provinces = Province::all(); + + $inpeksi = Inspeksi::where('permohonan_id', $id)->where('dokument_id', $dokumentId)->first(); + + $formFoto = null; + if ($inpeksi) { + $formFoto = json_decode($inpeksi->foto_form, true); + } + $fotoJaminan = null; + return view('lpj::surveyor.components.foto', compact('permohonan', 'surveyor', 'branches', 'provinces', 'fotoJaminan', 'formFoto', 'fotoObjekJaminan')); + } + + /** + * Data pembanding. + */ + + public function dataPembanding(Request $request, $id) + { + try { + // Ambil data permohonan dengan eager loading + + $validated = $request->validate([ + 'form' => 'required|in:data-pembanding', + 'pembanding' => 'required|exists:permohonan,id', + 'dokument' => 'required', + 'jenisjaminan' => 'required' + ]); + + $dokumentId = $validated['dokument']; + $jaminanId = $validated['jenisjaminan']; + + $permohonan = $this->getPermohonanJaminanId($id, $dokumentId, $jaminanId); - public function export(string $type) - { - $modelClass = $this->getModelClass($type); + // Ambil data inspeksi + $inspeksi = Inspeksi::where([ + 'permohonan_id' => $id, + 'dokument_id' => $dokumentId + ])->first(); - if (!$modelClass) { + // Inisialisasi variabel + $inspectionData = null; + $comparisons = null; + $fotoForm = null; + + if ($inspeksi) { + + $inspectionData = json_decode($inspeksi->data_form, true); + if (json_last_error() !== JSON_ERROR_NONE) { + throw new Exception('Harap mengisi form inspeksi terlebih dahulu.'); + } + + if ($inspeksi->data_pembanding) { + $comparisons = json_decode($inspeksi->data_pembanding, true); + if (json_last_error() !== JSON_ERROR_NONE) { + throw new Exception('Error decoding comparison data: ' . json_last_error_msg()); + } + } + $fotoForm = json_decode($inspeksi->foto_form, true); + + } + + // Ambil data pendukung + $data = $this->getCommonData(); + $provinces = Province::all(); + + $cities = City::where('province_code', $this->getCodeAlamat('province_code', $inspectionData)) + ->get(); + $districts = District::where('city_code', $this->getCodeAlamat('city_code', $inspectionData))->get(); + $villages = Village::where('district_code', $this->getCodeAlamat('district_code', $inspectionData)) + ->get(); + + return view('lpj::surveyor.components.data-pembanding', compact( + 'permohonan', + 'id', + 'inspectionData', + 'comparisons', + 'data', + 'jaminanId', + 'fotoForm', + 'cities', + 'districts', + 'villages', + 'provinces', + 'inspeksi' + )); + + } catch (Exception $e) { + return redirect() + ->back() + ->with('error', 'Terjadi kesalahan saat memuat data: ' . $e->getMessage()); + } + } + + public function getCodeAlamat($code, $inspectionData) + { + $cekAlamat = isset( + $inspectionData['asset']['alamat']['sesuai'], + ) + ? 'sesuai' + : 'tidak sesuai'; + $selectedProvince = + $inspectionData['asset']['alamat'][$cekAlamat][$code] ?? null; + return $selectedProvince; + } + + public function data(Request $request) + { + + $type = $request->route('type'); + $header = $this->getHeader($request->route('type')); + return view('lpj::surveyor.data.index', compact('header')); + } + + private function getHeader(string $type) + : array + { + return self::HEADERS[$type] ?? []; + } + + public function createData($type) + { + $spekKategoriBagunan = SpekKategoritBangunan::all(); + $header = $this->getHeader($type); + return view('lpj::surveyor.data.form', compact('header', 'spekKategoriBagunan')); + } + + public function storeData(SurveyorRequest $request, $type) + { + $validate = $request->validated(); + if ($validate) { + + try { + $type = $request->route('type'); + + $modelClass = $this->getModelClass($type); + + if (!$modelClass) { + return redirect() + ->route('basicdata.' . $type . '.index') + ->with('error', 'Invalid type specified.'); + } + + if ($type == 'spek-bangunan') { + $validate['spek_kategori_bagunan_id'] = $request->spek_kategori_bagunan_id; + } + + + $data = array_merge($validate, ['status' => true]); + $modelClass::create($data); + + return redirect() + ->route('basicdata.' . $type . '.index') + ->with('success', 'created successfully'); + } catch (Exeception $e) { + return redirect() + ->route('basicdata.' . $type . '.index') + ->with('error', $th->getMessage()); + } + } + } + + private function getModelClass(string $type) + : ?string + { + return $this->modelClasses[$type] ?? null; + } + + public function editData($type, $id) + { + $dataMap = [ + 'bentuk-tanah' => ['Bentuk Tanah', 'bentuk-tanah', BentukTanah::class], + 'kontur-tanah' => ['Kontur Tanah', 'kontur-tanah', KonturTanah::class], + 'posisi-kavling' => ['Posisi Kavling', 'posisi-kavling', PosisiKavling::class], + 'ketinggian-tanah' => ['Ketinggian Tanah', 'ketinggian-tanah', KetinggianTanah::class], + 'kondisi-fisik-tanah' => ['Kondisi Fisik Tanah', 'kondisi-fisik-tanah', KondisiFisikTanah::class], + 'jenis-bangunan' => ['Jenis Bangunan', 'jenis-bangunan', JenisBangunan::class], + 'kondisi-bangunan' => ['Kondisi Bangunan', 'kondisi-bangunan', KondisiBangunan::class], + 'sifat-bangunan' => ['Sifat Bangunan', 'sifat-bangunan', SifatBangunan::class], + 'spek-bangunan' => ['Spek Bangunan', 'spek-bangunan', SpekBangunan::class], + 'spek-kategori-bangunan' => [ + 'Spek Kategori Bangunan', + 'spek-kategori-bangunan', + SpekKategoritBangunan::class + ], + 'sarana-pelengkap' => ['Sarana Pelengkap', 'sarana-pelengkap', SaranaPelengkap::class], + 'lantai-unit' => ['Lantai Unit', 'lantai-unit', Lantai::class], + 'view-unit' => ['View Unit', 'view-unit', ViewUnit::class], + 'gol-mas-sekitar' => [ + 'Golongan Masyarakat Sekitar', + 'gol-mas-sekitar', + GolonganMasySekitar::class + ], + 'jenis-pesawat' => ['Jenis Pasawat', 'jenis-pesawat', JenisPesawat::class], + 'model-alat-berat' => ['Model Alat Berat', 'model-alat-berat', ModelAlatBerat::class], + 'jenis-kapal' => ['Jenis Kapal', 'jenis-kapal', JenisKapal::class], + 'jenis-kendaraan' => ['Jenis Kendaraan', 'jenis-kendaraan', JenisKendaraan::class], + 'jenis-unit' => ['Jenis unit', 'jenis-unit', JenisUnit::class], + 'terletak-area' => ['Terletak di Area', 'terletak-area', TerletakArea::class], + 'merupakan-daerah' => ['Merupakan Daerah', 'merupakan-daerah', MerupakanDaerah::class], + 'posisi-unit' => ['Posisi unit', 'posisi-unit', PosisiUnit::class], + 'bentuk-unit' => ['Bentuk unit', 'bentuk-unit', BentukUnit::class], + 'fasilitas-objek' => ['Fasilitas Umum Dekat Objek', 'fasilitas-objek', FasilitasObjek::class], + 'foto-objek-jaminan' => ['Foto Objek Jaminan', 'foto-objek-jaminan', FotoObjekJaminan::class], + ]; + + + if (!array_key_exists($type, $dataMap)) { + return redirect()->back()->with('error', 'Invalid type specified.'); + } + + [$headers, $routeName, $modelClass] = $dataMap[$type]; + + $header = $dataMap[$type] ?? ''; + $model = $modelClass::findOrFail($id); + + $spekKategoriBagunan = null; + if ($type == 'spek-bangunan') { + $spekKategoriBagunan = SpekKategoritBangunan::all(); + } + + + return view('lpj::surveyor.data.form', compact('header', 'model', 'spekKategoriBagunan')); + } + + public function updateData(SurveyorRequest $request, $type, $id) + { + $validate = $request->validated(); + if ($validate) { + $modelClass = $this->getModelClass($type); + + if ($type == 'spek-bangunan') { + $validate['spek_kategori_bagunan_id'] = $request->spek_kategori_bagunan_id; + } + + if ($type == 'foto-objek-jaminan') { + $validate['kategori'] = $request->kategori; + } + + // Check if the provided type exists in the modelClasses + if (!$modelClass) { + return redirect() + ->route('basicdata.' . $type . '.index') + ->with('error', 'Invalid type specified.'); + } + + $model = $modelClass::findOrFail($id); + $model->update($validate); + + // Redirect back with a success message + return redirect() + ->route('basicdata.' . $type . '.index') + ->with('success', 'Updated successfully'); + } + } + + public function update_analisa($id, Request $request) + { + try { + $permohonan = Permohonan::with([ + 'user', + 'debiture.province', + 'debiture.city', + 'debiture.district', + 'debiture.village', + 'branch', + 'tujuanPenilaian', + 'penilaian', + 'documents', + ])->findOrFail($id); + + $jenisAssetUpdated = false; + if ($request->input('types') == 'jenis_asset') { + $this->updateJenisAsset($permohonan, $request); + $jenisAssetUpdated = true; + } + + if (in_array($request->input('types'), ['analisa_tanah', 'analisa_bangunan', 'analisa_unit'])) { + $key = match ($request->input('types')) { + 'analisa_tanah' => 'luas_tanah', + 'analisa_bangunan' => 'luas_bangunan', + 'analisa_unit' => 'luas_unit', + }; + + $this->updateDetails($permohonan, $key, $request->input($key)); + } + + return response()->json([ + 'success' => true, + 'message' => 'Data berhasil disimpan', + 'jenis_asset' => $jenisAssetUpdated, + ], 200); + } catch (Exception $e) { + return response()->json(['error' => 'Something went wrong', 'message' => $e->getMessage()], 500); + } + } + + private function updateJenisAsset($permohonan, $request) + { + $jenis_jaminan_id = $permohonan->debiture->documents->first()->jenis_jaminan_id; + DokumenJaminan::where('permohonan_id', $permohonan->id) + ->where('jenis_jaminan_id', $jenis_jaminan_id) + ->update([ + 'jenis_jaminan_id' => $request->input('jenis_asset'), + ]); + } + + private function updateDetails($permohonan, $key, $newValue) + { + $document = $permohonan->debiture->documents->first(); + + if (!$document) { + throw new Exception("Document not found"); + } + + $detailsUpdate = DetailDokumenJaminan::where('dokumen_jaminan_id', $document->id)->first(); + + if (!$detailsUpdate) { + throw new Exception("DetailDokumenJaminan not found"); + } + + $datas = json_decode($detailsUpdate->details, true) ?? []; + + if (is_numeric($newValue)) { + $newValue = [$key => $newValue]; + } + + if (!is_array($newValue)) { + throw new InvalidArgumentException("'{$key}' must be an array or valid JSON string"); + } + + foreach ($newValue as $subKey => $value) { + $datas[$subKey] = $value; // Update atau tambahkan key baru + } + + $detailsUpdate->update([ + 'details' => json_encode($datas), + ]); + } + + public function dataForDatatables(Request $request) + { + if (is_null($this->user) || !$this->user->can('debitur.view')) { + // abort(403, 'Sorry! You are not allowed to view users.'); + } + + $query = Permohonan::query(); + + if ($request->has('search') && !empty($request->get('search'))) { + $search = $request->get('search'); + $query->where(function ($q) use ($search) { + $q->where('nomor_registrasi', 'LIKE', '%' . $search . '%'); + $q->orWhere('tanggal_permohonan', 'LIKE', '%' . $search . '%'); + $q->orWhereRelation('user', 'name', 'LIKE', '%' . $search . '%'); + $q->orWhereRelation('debiture', 'name', 'LIKE', '%' . $search . '%'); + $q->orWhereRelation('tujuanPenilaian', 'name', 'LIKE', '%' . $search . '%'); + $q->orWhereRelation('branch', 'name', 'LIKE', '%' . $search . '%'); + $q->orWhere('status', 'LIKE', '%' . $search . '%'); + }); + } + + $query->whereRaw('LOWER(status) = ?', ['assign']); + + if (!Auth::user()->hasRole('administrator')) { + $query->whereHas('penilaian.userPenilai', function ($q) { + $q->where('user_id', Auth::user()->id); + $q->where('role', 'surveyor'); + }); + } + + + if ($request->has('sortOrder') && !empty($request->get('sortOrder'))) { + $order = $request->get('sortOrder'); + $column = $request->get('sortField'); + $query->orderBy($column, $order); + } + + $totalRecords = $query->count(); + + $size = $request->get('size', 10); + if ($size == 0) { + $size = 10; + } + + if ($request->has('page') && $request->has('size')) { + $page = $request->get('page', 1); + $offset = ($page - 1) * $size; + + $query->skip($offset)->take($size); + } + + $filteredRecords = $query->count(); + $data = $query->with([ + 'user', + 'debiture', + 'branch', + 'tujuanPenilaian', + 'jenisFasilitasKredit', + 'penilaian' + ])->get(); + + $pageCount = ceil($totalRecords / $size); + + $currentPage = max(1, $request->get('page', 1)); return response()->json([ - 'message' => 'Invalid type provided.', - 'available_types' => array_keys($this->modelClasses), - ], 400); + 'draw' => $request->get('draw'), + 'recordsTotal' => $totalRecords, + 'recordsFiltered' => $filteredRecords, + 'pageCount' => $pageCount, + 'page' => $currentPage, + 'totalCount' => $totalRecords, + 'data' => $data, + ]); } - // Return Excel download - return Excel::download(new BasicDataSurveyorExport($modelClass), $type . '.xlsx'); + public function dataForDatatablesData(Request $request, $type) + { + if (is_null($this->user) || !$this->user->can('jenis_aset.view')) { + //abort(403, 'Sorry! You are not allowed to view users.'); + } + + $models = [ + 'Bentuk Tanah' => BentukTanah::class, + 'Kontur Tanah' => KonturTanah::class, + 'Posisi Kavling' => PosisiKavling::class, + 'Ketinggian Tanah' => KetinggianTanah::class, + 'Kondisi Fisik Tanah' => KondisiFisikTanah::class, + 'Jenis Bangunan' => JenisBangunan::class, + 'Kondisi Bangunan' => KondisiBangunan::class, + 'Sifat Bangunan' => SifatBangunan::class, + 'Spek Kategori Bangunan' => SpekKategoritBangunan::class, + 'Spek Bangunan' => SpekBangunan::class, + 'Sarana Pelengkap' => SaranaPelengkap::class, + 'Lalu Lintas Depan Lokasi' => LaluLintasLokasi::class, + 'Tingkat Keramaian' => TingkatKeramaian::class, + 'Golongan Masyarakat Sekitar' => GolonganMasySekitar::class, + 'Lantai Unit' => Lantai::class, + 'View Unit' => ViewUnit::class, + 'Perkerasan jalan' => PerkerasanJalan::class, + 'Jenis pesawat' => JenisPesawat::class, + 'Model alat berat' => ModelAlatBerat::class, + 'Jenis kapal' => JenisKapal::class, + 'Jenis kendaraan' => JenisKendaraan::class, + 'Terletak di Area' => TerletakArea::class, + 'Posisi unit' => PosisiUnit::class, + 'Bentuk unit' => BentukUnit::class, + 'Fasilitas Umum Dekat Objek' => FasilitasObjek::class, + 'Merupakan Daerah' => MerupakanDaerah::class, + 'Jenis unit' => JenisUnit::class, + 'Foto Objek Jaminan' => FotoObjekJaminan::class, + ]; + + + if (array_key_exists($type, $models)) { + $query = $models[$type]::query(); + } else { + throw new InvalidArgumentException("Invalid type: $type"); + } + + if ($request->has('search') && !empty($request->get('search'))) { + $search = $request->get('search'); + $query->where(function ($q) use ($search) { + $q->where('code', 'LIKE', "%$search%"); + $q->orWhere('name', 'LIKE', "%$search%"); + }); + } + + // Apply sorting if provided + if ($request->has('sortOrder') && !empty($request->get('sortOrder'))) { + $order = $request->get('sortOrder'); + $column = $request->get('sortField'); + $query->orderBy($column, $order); + } + + // Get the total count of records + $totalRecords = $query->count(); + + // Apply pagination if provided + if ($request->has('page') && $request->has('size')) { + $page = $request->get('page'); + $size = $request->get('size'); + $offset = ($page - 1) * $size; // Calculate the offset + + $query->skip($offset)->take($size); + } + + // Get the filtered count of records + $filteredRecords = $query->count(); + + // Get the data for the current page + + if ($type == 'Spek Bangunan') { + $data = $query->with(['bangunanKategori'])->get(); + } else { + $data = $query->get(); + } + + + // Calculate the page count + $pageCount = ceil($totalRecords / $request->get('size')); + + // Calculate the current page number + $currentPage = 0 + 1; + + + // Return the response data as a JSON object + return response()->json([ + 'draw' => $request->get('draw'), + 'recordsTotal' => $totalRecords, + 'recordsFiltered' => $filteredRecords, + 'pageCount' => $pageCount, + 'page' => $currentPage, + 'totalCount' => $totalRecords, + 'data' => $data, + ]); + } + + public function destroy($id, $type) + { + try { + + $modelClass = $this->getModelClass($type); + + if (!$modelClass) { + return response()->json(['success' => false, 'message' => 'Invalid type specified.'], 400); + } + $model = $modelClass::findOrFail($id); + $model->delete(); + return response()->json(['success' => true, 'message' => 'deleted successfully']); + } catch (ModelNotFoundException $e) { + return response()->json(['success' => false, 'message' => 'not found.'], 404); + } catch (Exception $e) { + return response()->json(['success' => false, 'message' => 'Failed to delete.'], 500); + } + } + + public function getKendaraanData($data, $request) + : array + { + return [ + 'action' => $data['action'] ?? null, + 'tanggal_survey' => $data['tanggal_survey'] ?? null, + 'nama_wakil' => $data['nama_wakil'] ?? null, + 'hub_calon_debitur' => $data['hub_calon_debitur'] ?? null, + 'nama_jalan' => $data['nama_jalan'] ?? null, + 'perumahan_gang' => $data['perumahan_gang'] ?? null, + 'blok_nomor' => $data['blok_nomor'] ?? null, + 'desa_kelurahan' => $data['desa_kelurahan'] ?? null, + 'kecamatan' => $data['kecamatan'] ?? null, + 'kota_madya' => $data['kota_madya'] ?? null, + 'provinsi' => $data['provinsi'] ?? null, + 'kondisi' => $data['kondisi'] ?? null, + 'nomor_polisi' => $data['nomor_polisi'] ?? null, + 'nomor_polis_tidak_sesuai' => $data['nomor_polis_tidak_sesuai'] ?? null, + 'merek' => $data['merek'] ?? null, + 'merek_tidak_sesuai' => $data['merek_tidak_sesuai'] ?? null, + 'warna' => $data['warna'] ?? null, + 'warna_tidak_sesuai' => $data['warna_tidak_sesuai'] ?? null, + 'nomor_rangka' => $data['nomor_rangka'] ?? null, + 'nomor_rangka_tidak_sesuai' => $data['nomor_rangka_tidak_sesuai'] ?? null, + 'nomor_mesin' => $data['nomor_mesin'] ?? null, + 'nomor_mesin_tidak_sesuai' => $data['nomor_mesin_tidak_sesuai'] ?? null, + 'posisi_kilometer' => $data['posisi_kilometer'] ?? null, + 'transmisi' => $data['transmisi'] ?? null, + + + 'mesin_panel_instrument' => $data['mesin_panel_instrument'] ?? null, + 'fungsi_mesin_panel_instrument' => $data['fungsi_mesin_panel_instrument'] ?? null, + 'interior' => $data['interior'] ?? null, + 'interior' => $data['interior'] ?? null, + + 'jumlah_pintu' => $data['jumlah_pintu'] ?? null, + 'rangka_karoseri' => $data['rangka_karoseri'] ?? null, + 'ban' => $data['ban'] ?? null, + 'velg' => $data['velg'] ?? null, + 'bamper_depan' => $data['bamper_depan'] ?? null, + 'bamper_belakang' => $data['bamper_belakang'] ?? null, + 'lampu_depan' => $data['lampu_depan'] ?? null, + 'lampu_belakang' => $data['lampu_belakang'] ?? null, + 'kaca_kendaraan' => $data['kaca_kendaraan'] ?? null, + 'air_conditioner' => $data['air_conditioner'] ?? null, + 'tape_radio_cd' => $data['tape_radio_cd'] ?? null, + 'sensor_parkir' => $data['sensor_parkir'] ?? null, + 'sensor_camera_recorder' => $data['sensor_camera_recorder'] ?? null, + 'lcd' => $data['lcd'] ?? null, + 'sabuk_keselamatan' => $data['sabuk_keselamatan'] ?? null, + 'airbag' => $data['airbag'] ?? null, + 'asuransi' => $data['asuransi'] ?? null, + 'perusahaan_asuransi' => $data['perusahaan_asuransi'] ?? null, + 'tahun_berakhir' => $data['tahun_berakhir'] ?? null, + + + 'fakta_positif' => $data['fakta_positif'] ?? null, + 'fakta_negatif' => $data['fakta_negatif'] ?? null, + 'analisa_makro' => $data['analisa_makro'] ?? null, + 'kesimpulan' => $data['kesimpulan'] ?? null, + 'catatan' => $data['catatan'] ?? null, + ]; + } + + public function getMesinData($data, $request) + : array + { + return [ + 'action' => $data['action'] ?? null, + 'nama_wakil' => $data['nama_wakil'] ?? null, + 'nama_jalan' => $data['nama_jalan'] ?? null, + 'perumahan_gang' => $data['perumahan_gang'] ?? null, + 'blok' => $data['blok'] ?? null, + 'desa_kelurahan' => $data['desa_kelurahan'] ?? null, + 'kecamatan' => $data['kecamatan'] ?? null, + 'kota_madya' => $data['kota_madya'] ?? null, + 'provinsi' => $data['provinsi'] ?? null, + 'hub_calon_debitur' => $data['hub_calon_debitur'] ?? null, + 'tipe_model' => $data['tipe_model'] ?? null, + 'merek' => $data['merek'] ?? null, + 'tahun_pembuatan' => $data['tahun_pembuatan'] ?? null, + 'negara_pembuat' => $data['negara_pembuat'] ?? null, + 'kondisi_mesin' => $data['kondisi_mesin'] ?? null, + 'faktor_positif' => $data['faktor_positif'] ?? null, + 'faktor_negatif' => $data['faktor_negatif'] ?? null, + 'kesimpulan' => $data['kesimpulan'] ?? null, + 'catatan' => $data['catatan'] ?? null, + ]; + } + + public function getAlatBeratData($data, $request) + : array + { + return [ + 'action' => $data['action'] ?? null, + 'tanggal_survey' => $data['tanggal_survey'] ?? null, + 'nama_wakil' => $data['nama_wakil'] ?? null, + 'hub_calon_debitur' => $data['hub_calon_debitur'] ?? null, + 'dengan_wadeb' => $data['dengan_wadeb'] ?? null, + 'nama_jalan' => $data['nama_jalan'] ?? null, + 'perumahan_gang' => $data['perumahan_gang'] ?? null, + 'blok' => $data['blok'] ?? null, + 'desa_kelurahan' => $data['desa_kelurahan'] ?? null, + 'kecamatan' => $data['kecamatan'] ?? null, + 'kota_madya' => $data['kota_madya'] ?? null, + 'provinsi' => $data['provinsi'] ?? null, + 'jenis_model' => $data['jenis_model'] ?? null, + 'nomor_lambung' => $data['nomor_lambung'] ?? null, + 'model_unit' => $data['model_unit'] ?? null, + 'tahun_pembuatan' => $data['tahun_pembuatan'] ?? null, + 'merk' => $data['merk'] ?? null, + 'negara_pembuat' => $data['negara_pembuat'] ?? null, + 'tahun_pembelian' => $data['tahun_pembelian'] ?? null, + 'nomor_faktur' => $data['nomor_faktur'] ?? null, + 'nomor_kontrak' => $data['nomor_kontrak'] ?? null, + 'nama_pemilik' => $data['nama_pemilik'] ?? null, + 'alamat_pemilik' => $data['alamat_pemilik'] ?? null, + 'nomor_asuransi' => $data['nomor_asuransi'] ?? null, + 'nomor_rangka' => $data['nomor_rangka'] ?? null, + 'nomor_mesin' => $data['nomor_mesin'] ?? null, + 'hour_mesters' => $data['hour_mesters'] ?? null, + 'overhaul_mesin' => $data['overhaul_mesin'] ?? null, + + 'mesin_panel' => $data['mesin_panel'] ?? null, + 'fungsi_panel' => $data['fungsi_panel'] ?? null, + 'interior' => $data['interior'] ?? null, + 'rangka_Karoseri' => $data['rangka_Karoseri'] ?? null, + 'ban' => $data['ban'] ?? null, + 'velg' => $data['velg'] ?? null, + 'air_conditioner' => $data['air_conditioner'] ?? null, + 'aksesoris' => $data['aksesoris'] ?? null, + 'lcd' => $data['lcd'] ?? null, + 'perlengkapan' => $data['perlengkapan'] ?? null, + 'asuransi' => $data['asuransi'] ?? null, + 'perusahaan_asuransi' => $data['perusahaan_asuransi'] ?? null, + 'tahun_berakhir' => $data['tahun_berakhir'] ?? null, + 'sensor_kamera' => $data['sensor_kamera'] ?? null, + 'sabuk_keselamatan' => $data['sabuk_keselamatan'] ?? null, + 'air_bag' => $data['air_bag'] ?? null, + + 'faktor_positif' => $data['faktor_positif'] ?? null, + 'faktor_negatif' => $data['faktor_negatif'] ?? null, + 'kesimpulan' => $data['kesimpulan'] ?? null, + 'catatan' => $data['catatan'] ?? null, + ]; + } + + public function export(string $type) + { + $modelClass = $this->getModelClass($type); + + if (!$modelClass) { + + return response()->json([ + 'message' => 'Invalid type provided.', + 'available_types' => array_keys($this->modelClasses), + ], 400); + } + + // Return Excel download + return Excel::download(new BasicDataSurveyorExport($modelClass), $type . '.xlsx'); + } + + private function generateUniqueFileName($file, $prefix = '') + { + $extension = $file->getClientOriginalExtension(); + return $prefix . '_' . uniqid() . '.' . $extension; + } + + private function getTanahData(array $data) + : array + { + return [ + 'tanah' => [ + 'luas_tanah' => $this->getFieldData( + $data, + 'luas_tanah', + true + ), + 'hadap_mata_angin' => [ + $data['hadap_mata_angin'] => $data['hadap_mata_angin'] == 'sesuai' ? $data['hadap_mata_angin_sesuai'] : $data['hadap_mata_angin_tidak_sesuai'] ?? null + ], + 'bentuk_tanah' => $this->getFieldData( + $data, + 'bentuk_tanah', + false, + 'lainnya' + ), + 'kontur_tanah' => $data['kontur_tanah'] ?? [], + 'ketinggian_tanah' => [ + 'ketinggian' => $data['ketinggian_jalan'] ?? null, + 'lebih_tinggi' => $data['ketinggian_lebih_tinggi'] ?? null, + 'lebih_rendah' => $data['ketinggian_lebih_rendah'] ?? null + ], + 'kontur_jalan' => $data['kontur_jalan'] ?? null, + 'ketinggian_jalan' => $data['ketinggian_jalan'] ?? [], + 'posisi_kavling' => $this->getFieldData( + $data, + 'posisi_kavling', + false, + 'lainnya' + ), + + 'tusuk_sate' => $data['tusuk_sate'] ?? null, + 'lockland' => $data['lockland'] ?? null, + 'kondisi_fisik_tanah' => $this->getFieldData( + $data, + 'kondisi_fisik_tanah', + false, + 'lainnya' + ) + ] + ]; + } + + /** + * Helper method generic untuk mengambil data field + * + * @param array $data Array sumber data + * @param string $fieldName Nama field + * @param bool $checkKesesuaian Apakah perlu cek kesesuaian + * @param string|null $extraField Field tambahan (misal 'lainnya') + * + * @return array + */ + private function getFieldData( + array $data, + string $fieldName, + bool $checkKesesuaian = false, + ?string $extraField = null + ) + : array + { + if ($checkKesesuaian) { + return [ + $data[$fieldName] ?? '' => ($data[$fieldName] ?? '') === 'sesuai' + ? ($data["{$fieldName}_sesuai"] ?? '') + : ($data["{$fieldName}_tidak_sesuai"] ?? '') + ]; + } + + $result = [ + $fieldName => $data[$fieldName] ?? null + ]; + + if ($extraField) { + $result[$extraField] = $data["{$fieldName}_{$extraField}"] ?? null; + } + + return $result; + } + + private function getBangunanData($data, $request) + : array + { + $data = $request->all(); + $result = []; + + + foreach ($request->input('nama_bangunan') as $index => $buildingName) { + if (empty($buildingName)) { + continue; + } // Skip if building name is empty + + $buildingData = []; + $buildingData['bagunan'] = $buildingName; + + $specCategories = $request->input('spek_kategori_bangunan'); + $buildingData['spek_kategori_bangunan'] = []; + + if (!empty($specCategories)) { + foreach ($specCategories as $category) { + if (empty($category)) { + continue; + } // Skip empty categories + + $specs = $request->input("spek_bangunan.{$index}.{$category}", []); + + // Only add category if it has specifications + if (!empty($specs)) { + $buildingData['spek_kategori_bangunan'][$category] = $specs; + } + } + } + + // Only add building data if it has specifications + if (!empty($buildingData['spek_kategori_bangunan'])) { + $result[] = $buildingData; + } + } + + + return [ + 'bangunan' => [ + 'luas_tanah_bagunan' => $this->getFieldData( + $data, + 'luas_tanah_bagunan', + true + ), + 'jenis_bangunan' => $data['jenis_bangunan'] ?? null, + 'kondisi_bangunan' => $data['kondisi_bangunan'] ?? null, + 'sifat_bangunan' => $data['sifat_bangunan'] ?? null, + 'sifat_bangunan_input' => $data['sifat_bangunan_input'] ?? null, + 'spesifikasi_bangunan' => $result ?? null, + 'sarana_pelengkap' => $data['sarana_pelengkap'] ?? null, + 'sarana_pelengkap_input' => $data['sarana_pelengkap_input'] ?? null, + ], + ]; + } + + private function getLingkunganData($data, $request) + : array + { + return [ + 'lingkungan' => [ + 'jarak_jalan_utama' => $data['jarak_jalan_utama'] ?? null, + 'jalan_linkungan' => $data['jalan_linkungan'] ?? null, + 'jarak_cbd_point' => $data['jarak_cbd_point'] ?? null, + 'nama_cbd_point' => $data['nama_cbd_point'] ?? null, + 'lebar_perkerasan_jalan' => $data['lebar_perkerasan_jalan'] ?? null, + 'perkerasan_jalan' => $this->getFieldData( + $data, + 'perkerasan_jalan', + false, + 'lainnya' + ), + 'lalu_lintas' => $data['lalu_lintas'] ?? null, + 'gol_mas_sekitar' => $data['gol_mas_sekitar'] ?? null, + 'tingkat_keramaian' => $data['tingkat_keramaian'] ?? null, + 'terletak_diarea' => $this->getFieldData( + $data, + 'terletak_diarea', + false, + 'lainnya' + ), + 'disekitar_lokasi' => $data['disekitar_lokasi'] === 'yes' ? [ + 'kondisi' => $data['kondisi_bagunan_disekitar_lokasi'] ?? null, + 'sifat' => $data['sifat_bagunan_disekitar_lokasi'] ?? null, + ] : $data['disekitar_lokasi'], + 'kondisi_bagunan_disekitar_lokasi' => $data['kondisi_bagunan_disekitar_lokasi'] ?? null, + 'sifat_bagunan_disekitar_lokasi' => $data['sifat_bagunan_disekitar_lokasi'] ?? null, + 'dekat_makam' => $data['dekat_makam'] ?? null, + 'jarak_makam' => $data['jarak_makam'] ?? null, + 'nama_makam' => $data['nama_makam'] ?? null, + 'dekat_tps' => $data['dekat_tps'] ?? null, + 'jarak_tps' => $data['jarak_tps'] ?? null, + 'nama_tps' => $data['nama_tps'] ?? null, + 'dekat_lainnya' => $data['dekat_lainnya'] ?? null, + 'merupakan_daerah' => $data['merupakan_daerah'] ?? null, + 'fasilitas_dekat_object' => $data['fasilitas_dekat_object'] ?? null, + 'fasilitas_dekat_object_input' => $data['fasilitas_dekat_object_input'] ?? null, + ] + ]; + } + + private function getFactData($data, $request) + : array + { + $factData = [ + 'fakta' => [ + 'fakta_positif' => $data['fakta_positif'] ?? null, + 'fakta_negatif' => $data['fakta_negatif'] ?? null, + 'rute_menuju' => $data['rute_menuju'] ?? null, + 'batas_batas' => $data['batas_batas'] ?? null, + 'batas_batas_input' => $data['batas_batas_input'] ?? null, + 'kondisi_lingkungan' => $data['kondisi_lingkungan'] ?? null, + 'kondisi_lain_bangunan' => $data['kondisi_lain_bangunan'] ?? null, + 'informasi_dokument' => $data['informasi_dokument'] ?? null, + 'peruntukan' => $data['peruntukan'] ?? null, + 'kdb' => $data['kdb'] ?? null, + 'kdh' => $data['kdh'] ?? null, + 'gsb' => $data['gsb'] ?? null, + 'max_lantai' => $data['max_lantai'] ?? null, + 'klb' => $data['klb'] ?? null, + 'gss' => $data['gss'] ?? null, + 'pelebaran_jalan' => $data['pelebaran_jalan'] ?? null, + 'nama_petugas' => $data['nama_petugas'] ?? null, + 'keterangan' => $data['keterangan'] ?? null, + ] + ]; + + + $inspeksi = Inspeksi::where('permohonan_id', $request->input('permohonan_id')) + ->where('dokument_id', $request->input('dokument_id')) + ->first(); + + + $fotoTypes = [ + 'foto_gistaru', + 'foto_bhumi', + 'foto_argis_region', + 'foto_tempat' + ]; + + if ($inspeksi) { + $dataForm = json_decode($inspeksi->data_form, true); + foreach ($fotoTypes as $fotoType) { + // Jika ada file baru diupload + if ($request->hasFile($fotoType)) { + $factData[$fotoType] = $this->updateOrDeleteFile($dataForm, $request, $fotoType); + } else { + $factData[$fotoType] = $dataForm[$fotoType] ?? null; + } + } + } else { + foreach ($fotoTypes as $fotoType) { + $factData[$fotoType] = $this->updateOrDeleteFile($data, $request, $fotoType); + } + } + return $factData; + } + + private function updateOrDeleteFile($data, $request, $fileKey) + { + if ($request->hasFile($fileKey)) { + $file = $request->file($fileKey); + if ($file->isValid()) { + $fileName = time() . '_' . $file->getClientOriginalName(); + $path = $file->storeAs("public/surveyor/{$request->type}", $fileName); + + if ($path === false) { + throw new Exception("Failed to store file for {$fileKey}"); + } + if (isset($data[$fileKey]) && $data[$fileKey]) { + $this->deleteFile($data[$fileKey]); + } + return str_replace('public/', '', $path); + } else { + throw new Exception("Invalid file upload for {$fileKey}"); + } + } else if (isset($data[$fileKey]) && $data[$fileKey]) { + return $data[$fileKey]; + } else { + return null; + } + } + + private function deleteFile($filePath) + { + $fullPath = storage_path('app/public/' . $filePath); + if (file_exists($fullPath)) { + unlink($fullPath); + } + } + + private function getKapalData($data, $request) + : array + { + return [ + + 'action' => $data['action'] ?? null, + 'nama_wakil_debitur' => $data['nama_wakil_debitur'] ?? null, + 'hub_calon_debitur' => $data['hub_calon_debitur'] ?? null, + 'dermaga' => $data['dermaga'] ?? null, + 'desa_kelurahan' => $data['desa_kelurahan'] ?? null, + 'kecamatan' => $data['kecamatan'] ?? null, + 'kota_madya' => $data['kota_madya'] ?? null, + 'provinsi' => $data['provinsi'] ?? null, + 'jenis' => $data['jenis'] ?? null, + 'size' => $data['size'] ?? null, + 'kondisi' => $data['kondisi'] ?? null, + 'klasifikasi' => $data['klasifikasi'] ?? null, + + 'nama_kapal' => $data['nama_kapal'] ?? null, + 'pemilik_kapal' => $data['pemilik_kapal'] ?? null, + 'bendera' => $data['bendera'] ?? null, + 'nomor_selar' => $data['nomor_selar'] ?? null, + 'kapal' => $data['kapal'] ?? null, + 'galangan_kapal' => $data['galangan_kapal'] ?? null, + 'kapal_shipyard' => $data['kapal_shipyard'] ?? null, + 'tahun_pembuatan' => $data['tahun_pembuatan'] ?? null, + 'tahun_launcing' => $data['tahun_launcing'] ?? null, + 'dwt' => $data['dwt'] ?? null, + 'lwt' => $data['lwt'] ?? null, + 'gross_tonnage' => $data['gross_tonnage'] ?? null, + 'net_tonnage' => $data['net_tonnage'] ?? null, + 'tenaga_mesin' => $data['tenaga_mesin'] ?? null, + 'loa' => $data['loa'] ?? null, + 'lbp' => $data['lbp'] ?? null, + 'beam' => $data['beam'] ?? null, + 'depth' => $data['depth'] ?? null, + 'draft' => $data['draft'] ?? null, + + + 'lambung_kapal' => $data['lambung_kapal'] ?? null, + 'dek' => $data['dek'] ?? null, + 'struktur_rangka' => $data['struktur_rangka'] ?? null, + 'palka' => $data['palka'] ?? null, + 'pondasi_mesin' => $data['pondasi_mesin'] ?? null, + 'area_mesin' => $data['area_mesin'] ?? null, + 'cat_dan_korosi' => $data['cat_dan_korosi'] ?? null, + 'sistem_pengelasan' => $data['sistem_pengelasan'] ?? null, + 'deskripsi_struktur' => $data['deskripsi_struktur'] ?? null, + + 'sekoci' => $data['sekoci'] ?? null, + 'jaket_pelampung' => $data['jaket_pelampung'] ?? null, + 'alat_pemadaman' => $data['alat_pemadaman'] ?? null, + 'rambu_darurat' => $data['rambu_darurat'] ?? null, + 'sistem_alarm' => $data['sistem_alarm'] ?? null, + 'sistem_pencegah' => $data['sistem_pencegah'] ?? null, + 'kebakaran' => $data['kebakaran'] ?? null, + 'lampu_darurat' => $data['lampu_darurat'] ?? null, + 'deskripsi_peralatan' => $data['deskripsi_peralatan'] ?? null, + + 'gps' => $data['gps'] ?? null, + 'radar' => $data['radar'] ?? null, + 'radio_komunikasi' => $data['radio_komunikasi'] ?? null, + 'lampu_navigasi' => $data['lampu_navigasi'] ?? null, + 'sistem_kendali_otomatis' => $data['sistem_kendali_otomatis'] ?? null, + 'kompas' => $data['kompas'] ?? null, + 'deskripsi_navigasi' => $data['deskripsi_navigasi'] ?? null, + + 'mesin_utama' => $data['mesin_utama'] ?? null, + 'mesin_bantu' => $data['mesin_bantu'] ?? null, + 'pompa_pendingin' => $data['pompa_pendingin'] ?? null, + 'sistem_pelumasan' => $data['sistem_pelumasan'] ?? null, + 'propeller' => $data['propeller'] ?? null, + 'sistem_kelistrikan' => $data['sistem_kelistrikan'] ?? null, + 'deskripsi_mesin_penggerak' => $data['deskripsi_mesin_penggerak'] ?? null, + + 'lampu_navigasi' => $data['lampu_navigasi'] ?? null, + 'sistem_penerangan' => $data['sistem_penerangan'] ?? null, + 'sistem_panel_distribusi' => $data['sistem_panel_distribusi'] ?? null, + 'kabel_perangkat' => $data['kabel_perangkat'] ?? null, + 'deskripsi_kelistrikan' => $data['deskripsi_kelistrikan'] ?? null, + + 'kebersihan_dek_luar' => $data['kebersihan_dek_luar'] ?? null, + 'tangki_limbah' => $data['tangki_limbah'] ?? null, + 'sistem_pengelolaan_limbah' => $data['sistem_pengelolaan_limbah'] ?? null, + 'pengelolaan_air_ballast' => $data['pengelolaan_air_ballast'] ?? null, + 'deskripsi_kebersihan' => $data['deskripsi_kebersihan'] ?? null, + + 'fakta_positif' => $data['fakta_positif'] ?? null, + 'fakta_negatif' => $data['fakta_negatif'] ?? null, + 'analisa_makro' => $data['analisa_makro'] ?? null, + 'kesimpulan' => $data['kesimpulan'] ?? null, + 'catatan' => $data['catatan'] ?? null, + + ]; + } + + private function getPesawatData($data, $request) + : array + { + return [ + 'action' => $data['action'] ?? null, + 'tanggal_survey' => $data['tanggal_survey'] ?? null, + 'nama_wakil' => $data['nama_wakil'] ?? null, + 'hub_calon_debitur' => $data['hub_calon_debitur'] ?? null, + 'bandara' => $data['bandara'] ?? null, + 'desa_kelurahan' => $data['desa_kelurahan'] ?? null, + 'kecamatan' => $data['kecamatan'] ?? null, + 'kota_madya' => $data['kota_madya'] ?? null, + 'provinsi' => $data['provinsi'] ?? null, + + 'jenis_pesawat' => $data['jenis_pesawat'] ?? null, + 'size' => $data['size'] ?? null, + 'kondisi' => $data['kondisi'] ?? null, + 'nama_pesawat' => $data['nama_pesawat'] ?? null, + 'model' => $data['model'] ?? null, + 'nomor_registrasi' => $data['nomor_registrasi'] ?? null, + 'tahun_pembuatan' => $data['tahun_pembuatan'] ?? null, + 'certificate_of_airworthines' => $data['certificate_of_airworthines'] ?? null, + 'certificate_of_registration' => $data['certificate_of_registration'] ?? null, + 'total_service_hours' => $data['total_service_hours'] ?? null, + 'total_service_cycles' => $data['total_service_cycles'] ?? null, + + 'last_a_check' => $data['last_a_check'] ?? null, + 'next_a_check' => $data['next_a_check'] ?? null, + 'last_b_check' => $data['last_b_check'] ?? null, + 'next_b_check' => $data['next_b_check'] ?? null, + 'last_c_check' => $data['last_c_check'] ?? null, + 'next_c_check' => $data['next_c_check'] ?? null, + 'next_d_check' => $data['next_d_check'] ?? null, + 'last_d_check' => $data['last_d_check'] ?? null, + 'deskripsi_maintenence' => $data['deskripsi_maintenence'] ?? null, + + 'instrument_landing_system' => $data['instrument_landing_system'] ?? null, + 'traffic_collision_avoidance_system' => $data['traffic_collision_avoidance_system'] ?? null, + 'windshear' => $data['windshear'] ?? null, + 'electronic_flight' => $data['electronic_flight'] ?? null, + 'winglets' => $data['winglets'] ?? null, + 'deskripsi_konfigurasi' => $data['deskripsi_konfigurasi'] ?? null, + + 'maksimal_penumpang' => $data['maksimal_penumpang'] ?? null, + 'jumlah_kursi' => $data['jumlah_kursi'] ?? null, + 'kursi_pramugari_pramugara' => $data['kursi_pramugari_pramugara'] ?? null, + 'kartu_fitur_keselamatan' => $data['kartu_fitur_keselamatan'] ?? null, + 'sabuk_pengaman' => $data['sabuk_pengaman'] ?? null, + 'lampu_kabin' => $data['lampu_kabin'] ?? null, + 'lampu_pintu_keluar' => $data['lampu_pintu_keluar'] ?? null, + 'intercom_kabin' => $data['intercom_kabin'] ?? null, + 'deskripsi_kabin' => $data['deskripsi_kabin'] ?? null, + + 'badan_pesawat' => $data['badan_pesawat'] ?? null, + 'sayap_pesawat' => $data['sayap_pesawat'] ?? null, + 'ekor_pesawat' => $data['ekor_pesawat'] ?? null, + 'landing_gear' => $data['landing_gear'] ?? null, + 'sistem_pengelasan' => $data['sistem_pengelasan'] ?? null, + 'deskripsi_struktur' => $data['deskripsi_struktur'] ?? null, + + 'gps' => $data['gps'] ?? null, + 'radar' => $data['radar'] ?? null, + 'radio_komunikasi' => $data['radio_komunikasi'] ?? null, + 'lampu_navigasi' => $data['lampu_navigasi'] ?? null, + 'sistem_autopilot' => $data['sistem_autopilot'] ?? null, + 'deskripsi_navigasi' => $data['deskripsi_navigasi'] ?? null, + + 'tangki_bahan_bakar' => $data['tangki_bahan_bakar'] ?? null, + 'saluran_pipa_bahan_bakar' => $data['saluran_pipa_bahan_bakar'] ?? null, + 'pompa_bahan_bakar' => $data['pompa_bahan_bakar'] ?? null, + 'sistem_hidrolik_utama' => $data['sistem_hidrolik_utama'] ?? null, + 'sistem_pendigin_hidrolik' => $data['sistem_pendigin_hidrolik'] ?? null, + 'deskripsi_hidrolik' => $data['deskripsi_hidrolik'] ?? null, + + 'mesin_utama' => $data['mesin_utama'] ?? null, + 'sistem_pendorong' => $data['sistem_pendorong'] ?? null, + 'sistem_pendigin_mesin' => $data['sistem_pendigin_mesin'] ?? null, + 'sistem_pelumasan' => $data['sistem_pelumasan'] ?? null, + 'filter_dan_perangkat_pendukung' => $data['filter_dan_perangkat_pendukung'] ?? null, + 'deskripsi_kondisi_mesin' => $data['deskripsi_kondisi_mesin'] ?? null, + + 'jaket_pelampung' => $data['jaket_pelampung'] ?? null, + 'pintu_darurat' => $data['pintu_darurat'] ?? null, + 'alat_pemadaman_kebakaran' => $data['alat_pemadaman_kebakaran'] ?? null, + 'sistem_alaram_darurat' => $data['sistem_alaram_darurat'] ?? null, + 'sekoci' => $data['sekoci'] ?? null, + 'masker_oxigen' => $data['masker_oxigen'] ?? null, + 'sabuk_pengaman' => $data['sabuk_pengaman'] ?? null, + 'deskripsi_fungsi_keselamatan' => $data['deskripsi_fungsi_keselamatan'] ?? null, + + 'sistem_ventilasi_ac' => $data['sistem_ventilasi_ac'] ?? null, + 'sistem_penerangan_kabin' => $data['sistem_penerangan_kabin'] ?? null, + 'panel_informasi_penumpang' => $data['panel_informasi_penumpang'] ?? null, + 'sistem_hiburan_kabin' => $data['sistem_hiburan_kabin'] ?? null, + 'deskripsi_Interior' => $data['deskripsi_Interior'] ?? null, + + // Validasi untuk faktor dan kesimpulan + 'faktor_positif' => $data['faktor_positif'] ?? null, + 'faktor_negatif' => $data['faktor_negatif'] ?? null, + 'kesimpulan' => $data['kesimpulan'] ?? null, + 'catatan' => $data['catatan'] ?? null, + ]; + } + + private function getUnitData($data, $request) + : array + { + return [ + 'action' => $data['action'] ?? null, + 'luas_unit' => $this->getFieldData( + $data, + 'luas_unit', + true + ), + 'kondisi_unit' => $data['kondisi_unit'] ?? null, + 'posisi_unit' => $data['posisi_unit'] ?? null, + 'lantai' => $data['lantai'] ?? null, + 'view' => $data['view'] ?? null, + 'bentuk_unit' => $data['bentuk_unit'] ?? null, + ]; + } + + /** + * Helper untuk memetakan array dengan inputannya + * + * @param array $keys Array kunci + * @param array $values Array nilai/input + * + * @return array + */ + private function mapArrayWithInputs(array $keys, array $values) + : array + { + $result = []; + + foreach ($keys as $key) { + // Jika checkbox dicentang, ambil nilai input yang sesuai + // Gunakan nilai dari $values berdasarkan nama checkbox + $result[$key] = $values[$key] ?? null; + } + + return $result; + } } -} diff --git a/resources/views/surveyor/index.blade.php b/resources/views/surveyor/index.blade.php index 4bf99f5..42f0af1 100644 --- a/resources/views/surveyor/index.blade.php +++ b/resources/views/surveyor/index.blade.php @@ -104,7 +104,7 @@ } function freezeInputSurveyor(data) { - + document.getElementById('permohonan_id').value = data; }