<?php

namespace Modules\Lpj\Services;

use Modules\Lpj\Models\Inspeksi;
use Illuminate\Http\Request;

class SaveFormInspesksiService
{
    public function storeInspeksi(array $validatedData, string $type, Request $request)
    {
        try {
            $inspeksi = Inspeksi::firstOrNew(
                [
                    'permohonan_id' => $request->input('permohonan_id'),
                    'dokument_id' => $request->input('dokument_id')
                ]
            );

            $inspeksi->name = $request->input('type');

            $processedData = $this->getActionSpecificRules($validatedData, $type, $request, $inspeksi);

            // Merge data lama dengan data baru
            $existingData = json_decode($inspeksi->data_form, true) ?: [];

            $fotoTypes = [
                'foto_gistaru',
                'foto_bhumi',
                'foto_argis_region',
                'foto_tempat',
                'foto_sentuh_tanahku',
                'upload_gs'
            ];

            foreach ($fotoTypes as $fotoType) {
                if (isset($existingData[$fotoType])) {
                    $processedData[$fotoType] = $existingData[$fotoType];
                }
            }

            $mergedData = $this->arrayMergeRecursive($existingData, $processedData);

            if (isset($existingData['signature']) && !isset($processedData['signature'])) {
                $mergedData['signature'] = $existingData['signature'];
            }

            $inspeksi->data_form = json_encode($mergedData);
            $inspeksi->save();

            return [
                'success' => true,
                'message' => 'Data berhasil disimpan',
            ];


        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => 'Gagal menyimpan data',
                'error' => $e->getMessage()
            ];
        }
    }


    private function getActionSpecificRules($data, $action, $request, $inspeksi): array
    {
        $allowedActions = [
            'apartemen-kantor' => 'getUnitData',
            'tanah' => 'getTanahData',
            'bangunan' => 'getBangunanData',
            'kapal' => 'getKapalData',
            'kendaraan' => 'getKendaraanData',
            'mesin' => 'getMesinData',
            'pesawat' => 'getPesawatData',
            'alat-berat' => 'getAlatBeratData',
            'lingkungan' => 'getLingkunganData',
            'fakta' => 'getFactData',
            'informasi' => 'getFactData',
            'rap' => 'getRapData',
        ];

        $rules = [];
        $hasAssetDescriptionRules = false;
        $hasFactaData = false;



        $pisah = array_filter(
            explode(',', $action),
            function ($act) use ($allowedActions) {
                return isset($allowedActions[trim($act)]);
            }
        );

        // dd($pisah);

        foreach ($pisah as $act) {
            $act = trim($act); // Bersihkan spasi
            if (isset($allowedActions[$act])) {
                $method = $allowedActions[$act];

                $actionRules = $this->$method($data, $request, $inspeksi);
                $rules = array_merge($rules, $actionRules);

                // Cek apakah act memerlukan asset description rules
                if (in_array($act, ['apartemen-kantor', 'tanah', 'bangunan', 'rap'])) {
                    $hasAssetDescriptionRules = true;
                }

                // Cek apakah act memerlukan fakta data
                if (in_array($act, ['rap'])) {
                    $hasFactaData = true;
                }
            }

        }

        if ($hasAssetDescriptionRules) {
            $rules = array_merge($rules, $this->getAssetData($data));
        }

        if ($hasFactaData) {
            $rules = array_merge($rules, $this->getFactData($data, $request,  $inspeksi));
        }

        return $rules;
    }


    private function getUnitData($data, $request): array
    {


        $luas_unit_key = ($data['luas_unit'] ?? null) === 'sesuai' ? 'sesuai' : 'tidak sesuai';
        $luas_unit = [];

        $hasil_luas_unit = $luas_unit_key === 'sesuai'
            ? ($data['luas_unit_sesuai'] ?? null)
            : ($data['luas_unit_tidak_sesuai'] ?? null);

        // Masukkan key baru yang sesuai
        $luas_unit[$luas_unit_key] = preg_replace('/[^0-9.,]/', '', $hasil_luas_unit);

        return [
            'action' => $data['action'] ?? null,
            'luas_unit' => $luas_unit,
            '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,
        ];
    }

    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,
        ];

        $alamatKey = ($data['alamat_sesuai'] ?? null) === 'sesuai' ? 'sesuai' : 'tidak sesuai';
        $alamat = [];
        $alamat[$alamatKey] = $alamatData;


        $jenis_asset = [];
        if (($data['jenis_asset'] ?? null) === 'tidak sesuai') {
            $jenis_asset['tidak sesuai'] = $data['jenis_asset_tidak_sesuai'] ?? null;

            if ($data['jenis_asset_tidak_sesuai'] === 'Lainnya') {
                $jenis_asset['Lainnya'] = $data['jenis_asset_lainnya'] ?? null;
            }
        } else {
            $jenis_asset['sesuai'] = $data['jenis_asset_name'] ?? null;
        }


        return [
            'asset' => [
                'debitur_perwakilan' => $data['debitur_perwakilan'] ?? [],
                'jenis_asset' => $jenis_asset ?? null,
                'alamat' => $alamat ?? null,
                'hub_cadeb' => [
                    $data['hub_cadeb'] ?? null => ($data['hub_cadeb'] ?? null) === 'sesuai'
                        ? ($data['hub_cadeb_sesuai'] ?? null)
                        : ($data['hub_cadeb_tidak_sesuai'] ?? null)
                    ],
                'hub_cadeb_penghuni' => [
                    $data['hub_cadeb_penghuni'] ?? null => ($data['hub_cadeb_penghuni'] ?? null) === 'sesuai'
                        ? ($data['hub_cadeb_penghuni_sesuai'] ?? null)
                        : ($data['hub_penghuni_tidak_sesuai'] ?? null)
                ],

                'pihak_bank' => $data['pihak_bank'] ?? null,

                'kordinat_lng' => $data['kordinat_lng'] ?? null,
                'kordinat_lat' => $data['kordinat_lat'] ?? null,
                // 'nomor_nib' => $data['nomor_nib'] ?? null
        ]
            ];
    }

    private function getTanahData(array $data): array
    {
        //luas tanah key
        // Luas tanah key
        $luas_tanah_key = ($data['luas_tanah'] ?? null) === 'sesuai' ? 'sesuai' : 'tidak sesuai';
        $luas_tanah = [];
        $hasil_tanah = $luas_tanah_key === 'sesuai'
            ? ($data['luas_tanah_sesuai'] ?? null)
            : ($data['luas_tanah_tidak_sesuai'] ?? null);
        $luas_tanah[$luas_tanah_key] = preg_replace('/[^0-9.,]/', '', $hasil_tanah);

        // Hadap mata angin key
        $hadap_mata_angin_key = ($data['hadap_mata_angin'] ?? null) === 'sesuai' ? 'sesuai' : 'tidak sesuai';
        $hadap_mata_angin = [];
        $hasil_hadap_mata_angin = $hadap_mata_angin_key === 'sesuai'
            ? ($data['hadap_mata_angin_sesuai'] ?? null)
            : ($data['hadap_mata_angin_tidak_sesuai'] ?? null);
        $hadap_mata_angin[$hadap_mata_angin_key] = $hasil_hadap_mata_angin;

        $tusuk_sate_key = ($data['tusuk_sate'] ?? null) === 'Ya' ? 'Ya' : 'Tidak';

        $tusuk_sate = [];
        $tusuk_sate[$tusuk_sate_key] = $data['tusuk_sate_ya'] ?? "Tidak";


        return [
            'tanah' => [
                'luas_tanah' => $luas_tanah,
                'hadap_mata_angin' => $hadap_mata_angin,
                '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' => $tusuk_sate,
                'lockland' => $data['lockland'] ?? null,
                'kondisi_fisik_tanah' => $this->getFieldData(
                    $data,
                    'kondisi_fisik_tanah',
                    false,
                    'lainnya'
                )
            ]
        ];
    }


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



        $luas_tanah_bagunan_key = ($data['luas_tanah_bagunan'] ?? null) === 'sesuai' ? 'sesuai' : 'tidak sesuai';
        $luas_tanah_bagunan = [];

        $hasil_tanah_bagunan = $luas_tanah_bagunan_key === 'sesuai'
            ? ($data['luas_bangunan_sesuai'] ?? null)
            : ($data['luas_tanah_bagunan_tidak_sesuai'] ?? null);

        // Masukkan key baru yang sesuai
        $luas_tanah_bagunan[$luas_tanah_bagunan_key] = preg_replace('/[^0-9.,]/', '', $hasil_tanah_bagunan);


        return [
            'bangunan' => [
                'luas_tanah_bagunan' => $luas_tanah_bagunan,
                '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'] ?? null) === 'yes' ? [
    'kondisi' => $data['kondisi_bagunan_disekitar_lokasi'] ?? null,
    'sifat' => $data['sifat_bagunan_disekitar_lokasi'] ?? null,
] : ($data['disekitar_lokasi'] ?? null),

                '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, $inspeksi): 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,
            ]
        ];






        return $factData;
    }

    private function getRapData($data, $request, $inspeksi): array
    {

        $dataForm = json_decode($inspeksi->data_form, true);

        $perizinanData = isset($dataForm['perizinan']) ? $dataForm['perizinan'] : [];

        if ($request->has('perizinan')) {
            foreach ($request->perizinan as $key => $perizinanName) {
                // Cek apakah ada file baru yang diupload
                if ($request->hasFile("perizinan_file.{$key}")) {
                    // Jika ada file baru, tambahkan/update data
                    $file = $request->file("perizinan_file.{$key}");
                    $path = $file->store('perizinan', 'public');

                    // Cek apakah perizinan dengan nama yang sama sudah ada
                    $existingIndex = array_search($perizinanName, array_column($perizinanData, 'perizinan'));

                    if ($existingIndex !== false) {
                        // Update file untuk perizinan yang sudah ada
                        $perizinanData[$existingIndex] = [
                            'perizinan' => $perizinanName,
                            'perizinan_file' => $path
                        ];
                    } else {
                        // Tambah perizinan baru
                        $perizinanData[] = [
                            'perizinan' => $perizinanName,
                            'perizinan_file' => $path
                        ];
                    }
                }
            }
        }

        $data['perizinan'] = $perizinanData;

        $partisiResult = [];
        if (isset($data['partisi'])) {
            foreach ($data['partisi'] as $name => $values) {
                if (!empty($values['value'])) {
                    $partisiResult[$name] = [
                        'nama' => $values['nama'],
                        'value' => $values['value']
                    ];
                }
            }
        }

        $brosurData = isset($dataForm['brosur_price_list']) ? $dataForm['brosur_price_list'] : [];

        if ($request->has('brosur_price_list')) {
            foreach ($request->brosur_price_list as $key => $jenis) {
                // Cek apakah ada file baru yang diupload
                if ($request->hasFile("brosur_price_list_file.{$key}")) {
                    // Jika ada file baru, tambahkan/update data
                    $file = $request->file("brosur_price_list_file.{$key}");
                    $path = $file->store('brosur-pricelist', 'public');

                    // Cek apakah jenis brosur yang sama sudah ada
                    $existingIndex = array_search($jenis, array_column($brosurData, 'jenis'));

                    if ($existingIndex !== false) {
                        // Update file untuk jenis yang sudah ada
                        $brosurData[$existingIndex] = [
                            'jenis' => $jenis,
                            'file_path' => $path
                        ];
                    } else {
                        // Tambah jenis brosur baru
                        $brosurData[] = [
                            'jenis' => $jenis,
                            'file_path' => $path
                        ];
                    }
                }
            }
        }

        $data['brosur_price_list'] = $brosurData;
        $rapData = [
            'perizinan' => $perizinanData ?? null,
            'brosur_price_list' => $brosurData ?? null,

            'pengalaman_developer' => $data['pengalaman_developer'] ?? null,
            'developer_anggota' => $data['developer_anggota'] ?? null,
            'lainnya_developer' => $data['lainnya_developer'] ?? null,
            'kapan_mulai_dibangun' => $data['kapan_mulai_dibangun'] ?? null,
            'kondisi_perumahan' => $data['kondisi_perumahan'] ?? null,
            'progres_pembangunan' => $data['progres_pembangunan'] ?? null,
            'kontraktor' => $data['kontraktor'] ?? null,
            'lingkungan_sekitar' => $data['lingkungan_sekitar'] ?? null,
            'komplek_disekitar' => $data['komplek_disekitar'] ?? null,
            'pusat_keramaian' => $data['pusat_keramaian'] ?? null,
            'transportasi_umum' => $data['transportasi_umum'] ?? null,
            'lainnya_kondisi' => $data['lainnya_kondisi'] ?? null,
            'partisi' => $partisiResult ?? null,
            'jumlah_unit' => $data['jumlah_unit'] ?? null,
            'batas_batas_perumahan' => $data['batas_batas_perumahan'] ?? null,
            'fasus_fasum' => $data['fasus_fasum'] ?? null,
            'progres_penjualan' => $data['progres_penjualan'] ?? null,
            'harga_unit' => $data['harga_unit'] ?? null,
            'target_market' => $data['target_market'] ?? null,
            'kerjasama_dengan_bank' => $data['kerjasama_dengan_bank'] ?? null,
            'rute_menuju_lokasi' => $data['rute_menuju_lokasi'] ?? null,
            'properti_sejenis' => $data['properti_sejenis'] ?? null,
        ];

        return $rapData;
    }

    private function getKapalData($data, $request): array
    {

        $alamatData = [
            '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 [

            'action' => $data['action'] ?? null,
            'nama_wakil_debitur' => $data['nama_wakil_debitur'] ?? null,
            'hub_calon_debitur' => $data['hub_calon_debitur'] ?? null,
            'dermaga' => $data['dermaga'] ?? null,
            'nama_jalan' => $data['nama_jalan'] ?? null,
        'perumahan_gang' => $data['perumahan_gang'] ?? null,
        'blok_nomor' => $data['blok_nomor'] ?? null,
        'bandara' => $data['bandara'] ?? null,
        'asset' => [
            'alamat'  => [
                  'sesuai' => $alamatData
              ],
          ],
            'jenis_kapal' => $data['jenis_kapal'] ?? null,
            'jenis_kapal_lainnya' => $data['jenis_kapal_lainnya'] ?? 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
    {
        $alamatData = [
            '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 [
            '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,
            'asset' => [
                'alamat'  => [
                      'sesuai' => $alamatData
                  ],
              ],
            'masa_stnk' => $data['masa_stnk'] ?? null,
            'masa_pajak' => $data['masa_pajak'] ?? null,
            'kendaraan' => $data['kendaraan'] ?? null,
            'kendaraan_input' => $data['kendaraan_input'] ?? 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,
            'transmisi_input' => $data['transmisi_input'] ?? null,
            'mesin_panel_instrument' => $data['mesin_panel_instrument'] ?? null,
            'mesin_panel_instrument_input' => $data['mesin_panel_instrument_input'] ?? null,
            'fungsi_mesin_panel_instrument' => $data['fungsi_mesin_panel_instrument'] ?? null,
            'fungsi_mesin_panel_instrument_input' => $data['fungsi_mesin_panel_instrument_input'] ?? null,
            'interior' => $data['interior'] ?? null,
            'interior_input' => $data['interior_input'] ?? null,
            'jumlah_pintu' => $data['jumlah_pintu'] ?? null,
            'jumlah_pintu_input' => $data['jumlah_pintu_input'] ?? null,
            'rangka_karoseri' => $data['rangka_karoseri'] ?? null,
            'rangka_karoseri_input' => $data['rangka_karoseri_input'] ?? null,
            'ban' => $data['ban'] ?? null,
            'ban_input' => $data['ban_input'] ?? null,
            'velg' => $data['velg'] ?? null,
            'velg_input' => $data['velg_input'] ?? null,



            'bamper_depan' => $data['bamper_depan'] ?? null,
            'bamper_depan_input' => $data['bamper_depan_input'] ?? null,
            'bamper_belakang' => $data['bamper_belakang'] ?? null,
            'bamper_belakang_input' => $data['bamper_belakang_input'] ?? null,
            'lampu_depan' => $data['lampu_depan'] ?? null,
            'lampu_depan_input' => $data['lampu_depan_input'] ?? null,
            'lampu_belakang' => $data['lampu_belakang'] ?? null,
            'lampu_belakang_input' => $data['lampu_belakang_input'] ?? null,
            'kaca_kendaraan' => $data['kaca_kendaraan'] ?? null,
            'kaca_kendaraan_input' => $data['kaca_kendaraan_input'] ?? null,
            'air_conditioner' => $data['air_conditioner'] ?? null,
            'air_conditioner_input' => $data['air_conditioner_input'] ?? null,
            'tape_radio_cd' => $data['tape_radio_cd'] ?? null,
            'tape_radio_cd_input' => $data['tape_radio_cd_input'] ?? null,
            'sensor_parkir' => $data['sensor_parkir'] ?? null,
            'sensor_parkir_input' => $data['sensor_parkir_input'] ?? null,
            'sensor_camera_recorder' => $data['sensor_camera_recorder'] ?? null,
            'sensor_camera_recorder_input' => $data['sensor_camera_recorder_input'] ?? null,
            'lcd' => $data['lcd'] ?? null,
            'lcd_input' => $data['lcd_input'] ?? null,
            'sabuk_keselamatan' => $data['sabuk_keselamatan'] ?? null,
            'sabuk_keselamatan_input' => $data['sabuk_keselamatan_input'] ?? null,
            'airbag' => $data['airbag'] ?? null,
            'airbag_input' => $data['airbag_input'] ?? null,
            'asuransi' => $data['asuransi'] ?? null,
            'asuransi_input' => $data['asuransi_input'] ?? 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
    {
        $alamatData = [
            '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 [
            '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_nomor' => $data['blok_nomor'] ?? null,
            'asset' => [
              'alamat'  => [
                    'sesuai' => $alamatData
                ],
            ],
            '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,
            'mesin_panel_input' => $data['mesin_panel_input'] ?? null,
            'fungsi_panel' => $data['fungsi_panel'] ?? null,
            'fungsi_panel_input' => $data['fungsi_panel_input'] ?? null,
            'interior' => $data['interior'] ?? null,
            'interior_input' => $data['interior_input'] ?? null,
            'rangka_Karoseri' => $data['rangka_Karoseri'] ?? null,
            'rangka_Karoseri_input' => $data['rangka_Karoseri_input'] ?? null,
            'ban' => $data['ban'] ?? null,
            'ban_input' => $data['ban_input'] ?? null,
            'velg' => $data['velg'] ?? null,
            'velg_input' => $data['velg_input'] ?? null,
            'air_conditioner' => $data['air_conditioner'] ?? null,
            'air_conditioner_input' => $data['air_conditioner_input'] ?? null,
            'aksesoris' => $data['aksesoris'] ?? null,
            'aksesoris_input' => $data['aksesoris_input'] ?? null,
            'lcd' => $data['lcd'] ?? null,
            'lcd_input' => $data['lcd_input'] ?? null,
            'perlengkapan' => $data['perlengkapan'] ?? null,
            'perlengkapan_input' => $data['perlengkapan_input'] ?? null,
            'asuransi' => $data['asuransi'] ?? null,
            'asuransi_input' => $data['asuransi_input'] ?? 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,

            'fakta_positif' => $data['fakta_positif'] ?? null,
            'fakta_negatif' => $data['fakta_negatif'] ?? null,
            'kesimpulan' => $data['kesimpulan'] ?? null,
            'catatan' => $data['catatan'] ?? null,
        ];
    }

    private function getPesawatData($data, $request): array
    {
        $alamatData = [
            '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 [
            '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,
            'bandara' => $data['bandara'] ?? null,
            'asset' => [
                'alamat'  => [
                      'sesuai' => $alamatData
                  ],
              ],
            'jenis_pesawat' => $data['jenis_pesawat'] ?? null,
            'jenis_pesawat_lainnya' => $data['jenis_pesawat_lainnya'] ?? 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

            'fakta_positif' => $data['fakta_positif'] ?? null,
            'fakta_negatif' => $data['fakta_negatif'] ?? null,
            'kesimpulan' => $data['kesimpulan'] ?? null,
            'catatan' => $data['catatan'] ?? null,
        ];
    }

    private function arrayMergeRecursive(array $arr1, array $arr2): array
    {
        foreach ($arr2 as $key => $value) {
            if ($key === 'signature' && isset($arr1['signature'])) {
                // Gabungkan 'signature' secara spesifik
                $arr1['signature'] = array_merge_recursive((array) $arr1['signature'], (array) $value);
            } elseif (is_array($value) && isset($arr1[$key]) && is_array($arr1[$key])) {
                // Rekursif untuk elemen array
                $arr1[$key] = $this->arrayMergeRecursive($arr1[$key], $value);
            } else {
                // Ganti nilai lama dengan nilai baru
                $arr1[$key] = $value;
            }
        }

        // Hapus key lama yang tidak ada di array baru kecuali 'signature'
        $arr1 = array_intersect_key($arr1, $arr2 + ['signature' => true]);

        return $arr1;
    }

    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}");
            }
        } elseif (isset($data[$fileKey]) && $data[$fileKey]) {
            return $data[$fileKey] ?? null;
        } else {
            return null;
        }
    }

    private function deleteFile($filePath)
    {
        $fullPath = storage_path('app/public/' . $filePath);
        if (file_exists($fullPath)) {
            unlink($fullPath);
        }
    }


    /**
     * 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 {
        $result = [];

        if ($checkKesesuaian) {
            $isSesuai = ($data[$fieldName] ?? '') === 'sesuai';
            $fieldKey = $isSesuai ? "{$fieldName}_sesuai" : "{$fieldName}_tidak_sesuai";

            // Hanya simpan key yang dipilih
            if ($isSesuai) {
                $result['sesuai'] = $data[$fieldKey] ?? null;
            } else {
                $result['tidak sesuai'] = $data[$fieldKey] ?? null;
            }
        } else {
            $result[$fieldName] = $data[$fieldName] ?? null;

            if ($extraField) {
                $result[$extraField] = $data["{$fieldName}_{$extraField}"] ?? null;
            }
        }

        // Hapus key dengan nilai null untuk memastikan hanya key yang valid yang disimpan
        return array_filter($result, fn ($value) => $value !== null);
    }


}
