<?php

namespace Modules\Lpj\Http\Controllers;

use Illuminate\Http\Request;
use Barryvdh\DomPDF\Facade\Pdf;  // https://github.com/barryvdh/laravel-dompdf
use Illuminate\Support\Facades\Storage;
use Modules\Lpj\Models\Permohonan;
use Modules\Lpj\Models\Inspeksi;
use Modules\Lpj\Models\Penilai;
use Modules\Lpj\Models\Laporan;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
use Modules\Lpj\Exports\KertasKerjaExport;
use Modules\Lpj\Http\Controllers\SurveyorController;
use Modules\Location\Models\Province;
use Modules\Location\Models\City;
use Modules\Location\Models\District;
use Modules\Location\Models\Village;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\App;
use App\Helpers\Lpj;
use Modules\Lpj\Http\Requests\FormSurveyorRequest;
use Modules\Lpj\Models\Authorization;
use Modules\Lpj\Models\Debiture;
use Modules\Lpj\Services\SaveFormInspesksiService;
use Modules\Lpj\Services\PreviewLaporanService;

class PenilaiController extends Controller
{
    public $user;
    protected $surveyorController;
    protected $inspeksiService;
    protected $previewLaporanService;


    public function __construct(SurveyorController $surveyorController, SaveFormInspesksiService $inspeksiService, PreviewLaporanService $previewLaporanService)
    {
        $this->surveyorController = $surveyorController;
        $this->inspeksiService = $inspeksiService;
        $this->previewLaporanService = $previewLaporanService;
    }

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        return view('lpj::penilai.index');
    }

    /**
     * Show the form for creating a new resource.
     */
    public function lampiran(Request $request)
    {

        $permohonanId = $request->query('permohonanId');
        $documentId = $request->query('documentId');
        $jaminanId = $request->query('jaminanId');
        $basicData =  $this->surveyorController->getCommonData();
        $permohonan = $this->surveyorController->getPermohonanJaminanId($permohonanId, $documentId, $jaminanId);
        $inpeksi = Inspeksi::where('permohonan_id', $permohonanId)->where('dokument_id', $documentId)->first();
        $penilai = Penilai::where('permohonan_id', $permohonanId)->where('dokument_id', $documentId)->first();

        $formFoto = null;
        if ($inpeksi) {
            $formFoto = json_decode($inpeksi->foto_form, true);
            $forminspeksi = json_decode($inpeksi->data_form, true);
            $formDenah = json_decode($inpeksi->denah_form, true);
        }

        return view('lpj::penilai.lampiran', compact('permohonan', 'formFoto', 'forminspeksi', 'basicData', 'penilai', 'formDenah'));
    }

    public function create()
    {
        return view('lpj::create');
    }



    public function sederhana(Request $request, $id)
    {

        $documentId = $request->query('documentId');
        $jaminanId = $request->query('jaminanId');
        $permohonan = $this->surveyorController->getPermohonanJaminanId($id, $documentId, $jaminanId);
        $basicData =  $this->surveyorController->getCommonData();
        $provinces = Province::all();

        $noLpSederhana =  $this->generateNoLaporan($permohonan, $documentId, 'lpj');

        $inspeksi = Inspeksi::where('permohonan_id', $id)->where('dokument_id', $documentId)->first();
        $lpj = Penilai::updateOrCreate(
            [
                'permohonan_id' => $id,
                'dokument_id' => $documentId,
            ],
            [
                'type_penilai' => 'sederhana',
            ]
        );

        $forminspeksi = null;
        $lpjData = null;
        if ($inspeksi) {
            $forminspeksi = json_decode($inspeksi->data_form, true);
        }

        if ($lpj) {
            $lpjData = json_decode($lpj->lpj, true);
        }
        $debitur = Debiture::find($permohonan->debiture_id);

        $provinceCode = $debitur->province_code;
        $cityCode     = $debitur->city_code;
        $districtCode = $debitur->district_code;
        $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();

        if ($forminspeksi) {
            if (isset($forminspeksi['alamat']['sesuai']['province_code'])) {
                $cities = City::where('province_code', $forminspeksi['alamat']['sesuai']['province_code'])->get();
            }

            if (isset($forminspeksi['alamat']['sesuai']['city_code'])) {
                $districts = District::where('city_code', $forminspeksi['alamat']['sesuai']['city_code'])->get();
            }

            if (isset($forminspeksi['alamat']['sesuai']['district_code'])) {
                $villages = Village::where('district_code', $forminspeksi['alamat']['sesuai']['district_code'])->get();
            }
        }

        return view('lpj::penilai.components.lpj-sederhana-standar', compact('permohonan', 'forminspeksi', 'basicData', 'inspeksi', 'lpjData', 'provinces', 'cekAlamat', 'cities', 'districts', 'villages'));
    }

    public function standar(Request $request, $id)
    {

        $documentId = $request->query('documentId');
        $jaminanId = $request->query('jaminanId');

        $permohonan = $this->surveyorController->getPermohonanJaminanId($id, $documentId, $jaminanId);

        if ($permohonan->status == 'proses-laporan') {
            //return redirect()->back()->with('error', 'Masih dalam proses laporan');
        }

        $basicData =  $this->surveyorController->getCommonData();
        $noLpSederhana =  $this->generateNoLaporan($permohonan, $documentId, 'lpj');

        $provinces = Province::all();
        $inspeksi = Inspeksi::where('permohonan_id', $id)->where('dokument_id', $documentId)->first();
        $lpj = Penilai::updateOrCreate(
            [
                'permohonan_id' => $id,
                'dokument_id' => $documentId,
            ],
            [
                'type_penilai' => 'standar',
            ]
        );

        $forminspeksi = null;
        $lpjData = null;
        if ($inspeksi) {
            $forminspeksi = json_decode($inspeksi->data_form, true);
        }

        if ($lpj) {
            $lpjData = json_decode($lpj->lpj, true);
        }
        $debitur = Debiture::find($permohonan->debiture_id);

        $provinceCode = $debitur->province_code;
        $cityCode     = $debitur->city_code;
        $districtCode = $debitur->district_code;
        $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();

        if ($forminspeksi) {
            if (isset($forminspeksi['alamat']['sesuai']['province_code'])) {
                $cities = City::where('province_code', $forminspeksi['alamat']['sesuai']['province_code'])->get();
            }

            if (isset($forminspeksi['alamat']['sesuai']['city_code'])) {
                $districts = District::where('city_code', $forminspeksi['alamat']['sesuai']['city_code'])->get();
            }

            if (isset($forminspeksi['alamat']['sesuai']['district_code'])) {
                $villages = Village::where('district_code', $forminspeksi['alamat']['sesuai']['district_code'])->get();
            }
        }

        return view('lpj::penilai.components.lpj-sederhana-standar', compact('permohonan', 'forminspeksi', 'basicData', 'inspeksi', 'lpjData', 'provinces', 'cekAlamat', 'cities', 'districts', 'villages'));
    }

    public function resume(Request $request)
    {
        $permohonanId = $request->query('permohonanId');
        $documentId = $request->query('documentId');
        $jaminanId = $request->query('jaminanId');

        $permohonan = $this->surveyorController->getPermohonanJaminanId($permohonanId, $documentId, $jaminanId);

         if ($permohonan->status == 'proses-laporan') {
            return redirect()->back()->with('error', 'Masih dalam proses laporan');
        }

        $nomorLaporan =     $this->generateNoLaporan($permohonan, $documentId, 'resume');
        $inspeksi = Inspeksi::where('permohonan_id', $permohonanId)->where('dokument_id', $documentId)->first();
        $noLpresume =  $this->generateNoLaporan($permohonan, $documentId, 'resume');
        Penilai::updateOrCreate(
            [
                'permohonan_id' => $permohonanId,
                'dokument_id' => $documentId,
            ],
            [
                'type_penilai' => 'resume',
            ]
        );


        $resume = Penilai::where('permohonan_id', $permohonanId)->where('dokument_id', $documentId)->first();
        $lpjData = null;
        $resumeData = null;
        if ($resume) {
            $resumeData = json_decode($resume->resume, true);
        }
        $forminspeksi = null;

        if ($inspeksi) {
            $forminspeksi = json_decode($inspeksi->data_form, true);
        }

        return view('lpj::penilai.components.resume', compact('permohonan', 'resumeData', 'forminspeksi', 'nomorLaporan'));
    }

    public function memo(Request $request)
    {
        $req = $this->getRequestQueryId($request);

        $data = $this->getDataPermohonanWithPenilaiAndInspeksi($req['permohonanId'], $req['documentId'], $req['jaminanId']);
        $permohonan = $data['permohonan'];
         if ($permohonan->status == 'proses-laporan') {
            return redirect()->back()->with('error', 'Masih dalam proses laporan');
        }

        $nomorLaporan =     $this->generateNoLaporan($permohonan, $req['documentId'], 'memo');
        $inspeksi = Inspeksi::where('permohonan_id', $req['permohonanId'])->where('dokument_id', $req['documentId'])->first();
        $penilai = Penilai::where('permohonan_id', $req['permohonanId'])->where('dokument_id', $req['documentId'])->first();
        $provinces = Province::all();
        $basicData =  $this->surveyorController->getCommonData();
        Penilai::updateOrCreate(
            [
                'permohonan_id' => $req['permohonanId'],
                'dokument_id' => $req['documentId'],
            ],
            [
                'type_penilai' => 'memo',
            ]
        );

        $formFoto = $formPeta = $cities = $districts = $villages = $memo = null;
        if ($inspeksi) {
            $formFoto = json_decode($inspeksi->foto_form, true);
            $formPeta = json_decode($inspeksi->data_form, true);
            if (isset($penilai->memo)) {
                $memo = json_decode($penilai->memo);
            }
            if (isset($memo->lokasi->province_code)) {
                $cities = City::where('province_code', $memo->lokasi->province_code)->get();
            }

            if (isset($memo->lokasi->city_code)) {
                $districts = District::where('city_code', $memo->lokasi->city_code)->get();
            }

            if (isset($memo->lokasi->district_code)) {
                $villages = Village::where('district_code', $memo->lokasi->district_code)->get();
            }
        }

        return view('lpj::penilai.components.memo', compact('permohonan', 'formFoto', 'formPeta', 'provinces', 'basicData', 'memo', 'cities', 'districts', 'villages', 'nomorLaporan'));
    }


    /**
     * Show the specified resource.
     */
    public function show($id)
    {
        $permohonan = Permohonan::with(['debiture.documents.jenisjaminan', 'region.teams.teamsUsers.user', 'penilaian', 'documents.inspeksi','jenisPenilaian','laporanExternal'])->find($id);


        // return response()->json(['permohonan' => $permohonan]);
        return view('lpj::penilai.show', compact('permohonan'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id)
    {
        $permohonan = Permohonan::with('debiture')->find($id);
        return view('lpj::penilai.edit', compact('permohonan'));
    }


    public function storePaparan(Request $request, $id)
    {
        try {
            $permohonan = Permohonan::findOrFail($id);

            $permohonan->update([
                'status' => 'proses-paparan'
            ]);

            Authorization::updateOrCreate(
                [
                    'permohonan_id' => $id,
                    'jenis' => 'paparan'
                ],
                [
                    'request' => 'paparan'
                ]
            );


            if ($request->hasFile('file_paparan')) {
                // Menyimpan atau memperbarui data Penilai
                $penilai = Penilai::updateOrCreate(
                    [
                        'permohonan_id' => $request->permohonan_id,
                        'dokument_id' => $request->dokument_id,
                    ]
                );

                // Menyimpan fil
                $file = $request->file('file_paparan');
                $path = $file->store('public/file_paparan');

                $penilai->file_paparan = $path;
                $penilai->save();
            }


            return redirect()
                ->route('penilai.show', ['id' => $id])->with('success', 'diperbarui ke status paparan dan dikirim ke So untuk proses lebih lanjut.');
        } catch (\Exception $e) {
            return redirect()->route('penilai.show', ['id' => $id])->with('error', 'Terjadi kesalahan saat memproses permohonan.');
        }
    }


    /**
     * Update the specified resource in storage.
     */
    public function paparan(Request $request)
    {

        $permohonanId = $request->query('permohonanId');
        $documentId = $request->query('documentId');
        $jaminanId = $request->query('jaminanId');

        $permohonan = $this->surveyorController->getPermohonanJaminanId($permohonanId, $documentId, $jaminanId);
        $penilai = Penilai::where('permohonan_id', $permohonanId)->where('dokument_id', $documentId)->first();
        $inspeksi = Inspeksi::where('permohonan_id', $permohonanId)->where('dokument_id', $documentId)->first();
        $formFoto = null;
        if ($inspeksi) {
            $formFoto = json_decode($inspeksi->foto_form, true);
            $forminspeksi = json_decode($inspeksi->data_form, true);
        }

        return view('lpj::penilai.components.paparan', compact('permohonan', 'formFoto', 'penilai', 'forminspeksi', 'inspeksi'));
    }


    public function rap(Request $request)
    {

        $permohonanId = $request->query('permohonanId');
        $documentId = $request->query('documentId');
        $jaminanId = $request->query('jaminanId');
        $provinces = Province::all();
        $permohonan = $this->surveyorController->getPermohonanJaminanId($permohonanId, $documentId, $jaminanId);

         if ($permohonan->status == 'proses-laporan') {
            return redirect()->back()->with('error', 'Masih dalam proses laporan');
        }

        $nomorLaporan =     $this->generateNoLaporan($permohonan, $documentId, 'rap');
        $basicData =  $this->surveyorController->getCommonData();
        $inspeksi = Inspeksi::where('permohonan_id', $permohonanId)->where('dokument_id', $documentId)->first();
        Penilai::updateOrCreate(
            [
                'permohonan_id' => $permohonanId,
                'dokument_id' => $documentId,
            ],
            [
                'type_penilai' => 'rap',
            ]
        );

        $resume = Penilai::where('permohonan_id', $permohonanId)->where('dokument_id', $documentId)->first();

        $lpjData = null;
        $rap = null;
        $forminspeksi = null;
        if ($resume) {
            $forminspeksi = json_decode($inspeksi->data_form, true);
            $rap = json_decode($resume->rap, true);
        }
        // Default: gunakan data dari debitur
        $debitur = Debiture::find($permohonan->debiture_id);

        $provinceCode = $debitur->province_code;
        $cityCode     = $debitur->city_code;
        $districtCode = $debitur->district_code;

        $cekAlamat = $forminspeksi['asset']['alamat']['tidak sesuai'] ?? null;

        if ($cekAlamat) {
            $provinceCode = $cekAlamat['province_code'] ?? $provinceCode;
            $cityCode     = $cekAlamat['city_code'] ?? $cityCode;
            $districtCode = $cekAlamat['district_code'] ?? $districtCode;
        }

        $cities    = City::where('province_code', $provinceCode)->get();
        $districts = District::where('city_code', $cityCode)->get();
        $villages  = Village::where('district_code', $districtCode)->get();

        if ($forminspeksi) {
            if (isset($forminspeksi['alamat']['sesuai']['province_code'])) {
                $cities = City::where('province_code', $forminspeksi['alamat']['sesuai']['province_code'])->get();
            }

            if (isset($forminspeksi['alamat']['sesuai']['city_code'])) {
                $districts = District::where('city_code', $forminspeksi['alamat']['sesuai']['city_code'])->get();
            }

            if (isset($forminspeksi['alamat']['sesuai']['district_code'])) {
                $villages = Village::where('district_code', $forminspeksi['alamat']['sesuai']['district_code'])->get();
            }
        }

        return view('lpj::penilai.components.rap-penilai', compact(
            'permohonan',
            'rap',
            'provinces',
            'cities',
            'districts',
            'villages',
            'forminspeksi',
            'nomorLaporan',
            'basicData',
            'cekAlamat'
        ));
    }


    public function call_report(Request $request)
    {

        $permohonanId = $request->query('permohonanId');
        $documentId = $request->query('documentId');
        $jaminanId = $request->query('jaminanId');
        $provinces = Province::all();
        $permohonan = $this->surveyorController->getPermohonanJaminanId($permohonanId, $documentId, $jaminanId);
         if ($permohonan->status == 'proses-laporan') {
            return redirect()->back()->with('error', 'Masih dalam proses laporan');
        }
        $nomorLaporan =     $this->generateNoLaporan($permohonan, $documentId, 'call-report');
        $basicData =  $this->surveyorController->getCommonData();
        $inspeksi = Inspeksi::where('permohonan_id', $permohonanId)->where('dokument_id', $documentId)->first();
        $call = Penilai::updateOrCreate(
            [
                'permohonan_id' => $permohonanId,
                'dokument_id' => $documentId,
            ],
            [
                'type_penilai' => 'call-report',
            ]
        );

        // $lpjData = null;
        $callReport = null;
        if ($call && isset($call->call_report)) {
            $callReport = json_decode($call->call_report, true);
        }

        $forminspeksi = json_decode($inspeksi->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;

        $cekAlamat = $forminspeksi['asset']['alamat']['tidak sesuai'] ?? null;

        if ($cekAlamat) {
            $provinceCode = $cekAlamat['province_code'] ?? $provinceCode;
            $cityCode     = $cekAlamat['city_code'] ?? $cityCode;
            $districtCode = $cekAlamat['district_code'] ?? $districtCode;
        }

        $cities    = City::where('province_code', $provinceCode)->get();
        $districts = District::where('city_code', $cityCode)->get();
        $villages  = Village::where('district_code', $districtCode)->get();

        if ($forminspeksi) {

            if (isset($forminspeksi['alamat']['sesuai']['province_code'])) {
                $cities = City::where('province_code', $forminspeksi['alamat']['sesuai']['province_code'])->get();
            }

            if (isset($forminspeksi['alamat']['sesuai']['city_code'])) {
                $districts = District::where('city_code', $forminspeksi['alamat']['sesuai']['city_code'])->get();
            }

            if (isset($forminspeksi['alamat']['sesuai']['district_code'])) {
                $villages = Village::where('district_code', $forminspeksi['alamat']['sesuai']['district_code'])->get();
            }
        }

        return view('lpj::penilai.components.call-report', compact('permohonan', 'basicData', 'nomorLaporan', 'forminspeksi', 'cities', 'districts', 'villages', 'cekAlamat', 'callReport'));
    }



    public function dataForDatatables(Request $request)
    {
        if (is_null($this->user) || !$this->user->can('penilai.view')) {
            //abort(403, 'Sorry! You are not allowed to view users.');
        }

        // Retrieve data from the database
        $query = Permohonan::query();

        // Apply search filter if provided
        $query = $query->orderBy('nomor_registrasi', 'desc');
        if ($request->has('search') && !empty($request->get('search'))) {
            $search = $request->get('search');
            $columns = ['debiture.name', 'branch.name', 'user.name', 'tujuanPenilaian.name', 'jenisfasilitasKredit.name'];

            $query->where(function ($q) use ($search, $columns) {
                $q->where('nomor_registrasi', 'LIKE', '%' . $search . '%');
                foreach ($columns as $column) {
                    $q->orWhereRelation(explode('.', $column)[0], explode('.', $column)[1], 'LIKE', '%' . $search . '%');
                }
            });
        }

        $query->whereRaw('LOWER(status) IN (?, ?, ?, ?, ?, ?,?, ?, ?, ?, ?, ?)', ['assign', 'survey-completed', 'proses-laporan', 'paparan', 'proses-paparan', 'paparan', 'revisi-laporan', 'revisi-paparan', 'request-freeze', 'freeze', 'reject-freeze','unfreeze-sla']);

        if (!Auth::user()->hasRole('administrator')) {
            $query->whereHas('penilaian.userPenilai', function ($q) {
                $q
                ->whereIn('role', ['surveyor', 'penilai'])
                    ->where('user_id', Auth::user()->id);
            });
        }

        // Apply sorting if provided
        if ($request->has('sortOrder') && !empty($request->get('sortOrder'))) {
            $order  = $request->get('sortOrder');
            $column = $request->get('sortField');
            $query->orderBy($column, $order);
        } else {
            $query->orderBy('updated_at', 'DESC');
        }

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

            $query->skip($offset)->take($size);
        }

        // Get the filtered count of records
        $filteredRecords = $query->count();

        // Get the data for the current page
        $data = $query->with([
            'user',
            'debiture',
            'branch',
            'tujuanPenilaian',
            'jenisfasilitasKredit',
            'penilaian.userPenilai',
            'penilai',
            'nilaiPlafond',
            'penawaran'
        ])->get();

        // Calculate the page count
        $pageCount = ceil($totalRecords / $request->get('size'));

        // Calculate the current page number
        $currentPage = $request->get('page', 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 export_kertas_kerja(Request $request)
    {
        $permohonanId = $request->query('permohonanId');
        $documentId = $request->query('documentId');
        $jaminanId = $request->query('jaminanId');
        // Fetch the data from the database
        $data = Inspeksi::where('permohonan_id', $permohonanId)
            ->where('dokument_id', $documentId)
            ->first();

        $permohonan = $this->surveyorController->getPermohonanJaminanId(
            $permohonanId,
            $documentId,
            $jaminanId
        );
        // Check if data exists
        if (!$data) {
            return response()->json(['message' => 'Data not found'], 404);
        }

        // Decode the JSON fields
        $dataForm = json_decode($data->data_form, true);
        $fotoForm = json_decode($data->foto_form, true);
        $denahForm = json_decode($data->denah_form, true);
        $dataPembanding = json_decode($data->data_pembanding, true);

        // Prepare the data for export
        $exportData = [
            'objek' => [
                'jenis_aset' => $dataForm['asset']['jenis_asset']['sesuai'] ?? '',
                'luas_tanah' => $dataForm['tanah']['luas_tanah']['tidak sesuai'] ?? '',
                'harga' => $dataForm['asset']['harga'] ?? '',
                'tanggal_penawaran' => $dataForm['tanggal_penawaran'] ?? '',
                'diskon' => $dataForm['diskon'] ?? '',
                'no_telepon' => $dataForm['no_telepon'] ?? '',
                'nama_nara_sumber' => $dataForm['nama_nara_sumber'] ?? '',
                'status_nara_sumber' => $dataForm['status_nara_sumber'] ?? '',
                'alamat' => $dataForm['alamat'] ?? '',
                // Add other fields as necessary
            ],
            'pembanding1' => [],
            'pembanding2' => [],
            'pembanding3' => [],
            'foto_peta' => [
                'foto_tempat' => $dataForm['foto_tempat'] ?? [],
                'foto_gistaru' => $dataForm['foto_gistaru'] ?? [],
                'foto_bhumi' => $dataForm['foto_bhumi'] ?? [],
                'foto_argis_region' => $dataForm['foto_argis_region'] ?? [],
            ],
            'foto_objek' => $fotoForm['object_jaminan'] ?? [],
            'foto_objek1' => [], // Populate with relevant data
            'foto_objek2' => [], // Populate with relevant data
            'tanggal_penilaian' => $data->tanggal_penilaian ?? '',
            'nama_pemilik' => $data->nama_pemilik ?? '',
            'lokasi_lengkap' => $data->lokasi_lengkap ?? '',
        ];

        if(isset($dataPembanding)){
            // Extract data pembanding
            if (isset($dataPembanding['data_pembanding'])) {
                foreach ($dataPembanding['data_pembanding'] as $index => $pembanding) {
                    if ($index == 0) {
                        $exportData['pembanding1'] = $pembanding;
                    } elseif ($index == 1) {
                        $exportData['pembanding2'] = $pembanding;
                    } elseif ($index == 2) {
                        $exportData['pembanding3'] = $pembanding;
                    }
                }
            }
        }

        // Now create the export
        // return response()->json([ 'data' => $fotoForm]);

        // return view('lpj::component.kertas-kerja-tes
        // ', compact('permohonan', 'data'));
        return Excel::download(new KertasKerjaExport($exportData), 'kertas-kerja.xlsx');
    }



    public function import_kertas_kerja(Request $request)
    {

        $validatedData = $request->validate([
            'permohonan_id' => 'required|integer',
            'document_id' => 'required|integer',
            'kertas_kerja' => 'required|file|mimes:pdf',
        ]);

        try {
            // Simpan file kertas kerja
            if ($request->hasFile('kertas_kerja')) {
                $file = $request->file('kertas_kerja');
                $filePath = $this->surveyorController->uploadFile($file, 'kertas_kerja');
                Penilai::updateOrCreate(
                    [
                        'permohonan_id' => $validatedData['permohonan_id'],
                        'dokument_id' => $validatedData['document_id'],
                    ],
                    [
                        'kertas_kerja' => $filePath,
                    ]
                );

                return response()->json(['success' => true, 'message' => 'Kertas kerja berhasil diunggah.']);
            }

            return response()->json(['success' => false, 'message' => 'File kertas kerja tidak ditemukan.'], 400);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => 'Terjadi kesalahan: ' . $e->getMessage()], 500);
        }
    }


    public function status($id)
    {
        $penilai = Penilai::find($id);
        return response()->json(['data' => $penilai]);
    }

    public function checkStatusLpj(Request $request)
    {
        $permohonanId = $request->query('permohonanId');
        $documentId = $request->query('documentId');

        $statusLpj = Penilai::where('permohonan_id', $permohonanId)
            ->where('dokument_id', $documentId)
            ->first();

        return response()->json(['status' => $statusLpj ? $statusLpj->type : null]);
    }

    public function saveStatusLpj(Request $request)
    {


        Penilai::updateOrCreate(
            [
                'permohonan_id' => $request->permohonan_id,
                'dokument_id' => $request->document_i
            ],
            [
                'type' => $request->type,
                'type_penilai' => $request->type,
            ]
        );

        return response()->json(['success' => true]);
    }



    public function storePenilaian($id)
    {
        try {

            $penilai = Penilai::where('permohonan_id', $id)->get();

            $rap = $penilai->some(function ($item) {
                return strtolower($item->type_penilai) === 'rap';
            });
            $allComplete = $penilai->every(function ($item) {

                if ($item->type_penilai === 'rap') {
                    return !empty($item->type_penilai) && (
                        !empty($item->memo) ||
                        !empty($item->resume) ||
                        !empty($item->lpj) ||
                        !empty($item->rap)
                    );
                }


                return !empty($item->type_penilai) && (
                    !empty($item->memo) ||
                    !empty($item->resume) ||
                    !empty($item->lpj) ||
                    !empty($item->rap) ||
                    !empty($item->call_report)
                ) && !empty($item->kertas_kerja);
            });


            if (!$allComplete) {
                $message = $rap
                    ? 'Harap Mengisi laporan terlebih dahulu'
                    : 'Harap Mengisi laporan terlebih dahulu atau kertas kerja';

                return response()->json([
                    'success' => false,
                    'message' => $message,
                ], 400);
            }


            $permohonan = Permohonan::findOrFail($id);

            if ($permohonan->status === 'proses-laporan') {
                /*return response()->json([
                    'success' => false,
                    'message' => 'Masih proses laporan',
                ], 400);*/
            }

            if ($permohonan->status === 'proses-paparan') {
                return response()->json([
                    'success' => false,
                    'message' => 'Masih proses paparan',
                ]);
            }


            // $cekLpj = $this->checkDataLpj($type, $statusLpj);
            // if ($permohonan->status_bayar === 'sudah_bayar' && $cekLpj) {
            //      return response()->json([
            //          'success' => false,
            //          'message' => 'Harap mengisi LPJ terlebih dahulu',
            //      ]);
            // }


            $permohonan->update([
                'status' => 'proses-laporan',
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Berhasil Megirim reported ke so'
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Terjadi kesalahan',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function uploadTempPhoto(Request $request)
    {
        $validatedData = $request->validate([
            'permohonan_id' => 'required|integer',
            'dokument_id'   => 'required|integer',
        ]);

        $memo = Penilai::firstOrNew([
            'permohonan_id' => $validatedData['permohonan_id'],
            'dokument_id'   => $validatedData['dokument_id'],
        ]);

        $existingData = $memo->exists && $memo->memo ? json_decode($memo->memo, true) : [];
        $existingData['foto'] = $existingData['foto'] ?? [];

        if ($request->hasFile('file')) {

            $files = $request->file('file');

            if (!is_array($files)) {
                $files = [$files];
            }
            foreach ($files as $file) {

                $filename = time() . '_' . $file->getClientOriginalName();
                $path = $file->storeAs('temp_photos', $filename, 'public');
                $existingData['foto'][] = $path;

            }
            // Simpan data memo
            $memo->memo = json_encode($existingData);
            $memo->save();

            return response()->json(['success' => true, 'data' => $existingData]);
        }
        return response()->json(['success' => false], 400);
    }


    public function deleteTempPhoto(Request $request)
    {
        $validatedData = $request->validate([
            'permohonan_id' => 'required|integer',
            'dokument_id'   => 'required|integer',
            'path'          => 'required|string',
        ]);

        $memo = Penilai::firstOrNew([
            'permohonan_id' => $validatedData['permohonan_id'],
            'dokument_id'   => $validatedData['dokument_id'],
        ]);

        $fotoMemo = json_decode($memo->memo, true);
        if (isset($fotoMemo['foto']) && is_array($fotoMemo['foto'])) {
            $fotoMemo['foto'] = array_filter($fotoMemo['foto'], function ($photo) use ($validatedData) {
                return basename($photo) !== basename($validatedData['path']);
            });

            $fotoMemo['foto'] = array_values($fotoMemo['foto']);
            $memo->memo = json_encode($fotoMemo);
            $memo->save();
            return response()->json(['success' => true, 'message' => 'Foto berhasil dihapus']);
        }

        return response()->json(['success' => false, 'message' => 'Foto tidak ditemukan'], 400);
    }

    public function storeResume(Request $request)
    {
        try {
            $validatedData = $request->validate([
                'permohonan_id' => 'required',
                'dokument_id' => 'required',

                'resume' => 'required|array',
                'fakta_positif' => 'nullable|array',
                'fakta_negatif' => 'nullable|array',
                'type' => 'required',
                'action' => 'required',
                'keterangan' => 'nullable|array'
            ]);


            Penilai::updateOrCreate(
                [
                    'permohonan_id' => $validatedData['permohonan_id'],
                    'dokument_id' => $validatedData['dokument_id'],

                ],
                [
                    'resume' => json_encode($validatedData['resume']),
                ]
            );

            $inspeksi = Inspeksi::where('permohonan_id', $validatedData['permohonan_id'])
                ->where('dokument_id', $validatedData['dokument_id'])
                ->first();
            if ($inspeksi) {
                // Get existing data_form
                $existingData = json_decode($inspeksi->data_form, true) ?: [];

                // Structure the fakta data correctly
                $existingFaktaData = $existingData['fakta'] ?? [];

                // Gabungkan data baru dengan data yang sudah ada
                $updatedFaktaData = array_merge($existingFaktaData, [
                    'fakta_positif' => $validatedData['fakta_positif'] ?? $existingFaktaData['fakta_positif'] ?? null,
                    'fakta_negatif' => $validatedData['fakta_negatif'] ?? $existingFaktaData['fakta_negatif'] ?? null,
                    'keterangan' => $validatedData['keterangan'] ?? $existingFaktaData['keterangan'] ?? null,
                ]);
                $existingData['fakta'] = $updatedFaktaData;

                $inspeksi->update([
                    'data_form' => json_encode($existingData),
                ]);
            } else {
                // If inspeksi
                $newData = [
                    'fakta' => [
                        'fakta_positif' => $validatedData['fakta_positif'] ?? null,
                        'fakta_negatif' => $validatedData['fakta_negatif'] ?? null,
                        'keterangan' => $validatedData['keterangan'] ?? null,
                    ],
                ];

                Inspeksi::updateOrCreate([
                    'permohonan_id' => $validatedData['permohonan_id'],
                    'dokument_id' => $validatedData['dokument_id']
                ],[
                    'data_form' => json_encode($newData),
                    'name' => $validatedData['type']
                ]);
            }


            return response()->json([
                'success' => true,
                'message' => 'Berhasil saved resume',
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Terjadi kesalahan',
                'error' => $e->getMessage()
            ], 500);
        }
    }


    public function storeMemoWithPhotos(Request $request)
    {
        try {
            $validatedData = $request->validate([
                'permohonan_id' => 'required|integer',
                'document_id'   => 'required|integer',
                'memo'          => 'required',
            ]);

            $newMemoData = json_decode($validatedData['memo'], true);

            $memo = Penilai::firstOrNew(
                [
                    'permohonan_id' => $validatedData['permohonan_id'],
                    'dokument_id'   => $validatedData['document_id'],
                ]
            );

            $existingMemoData = isset($memo->memo) ? json_decode($memo->memo, true) : [];
            $mergedMemoData = array_merge($existingMemoData, $newMemoData);

            $memo->memo = json_encode($mergedMemoData);
            $memo->save();

            return response()->json([
                'success' => true,
                'message' => 'Memo dan foto berhasil disimpan',
            ]);
        } catch (Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Terjadi kesalahan: ' . $e->getMessage(),
            ], 500);
        }
    }

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

            $validatedData = $request->all();
            $result = $this->inspeksiService->storeInspeksi($validatedData, $request->input('type'), $request);

            $data = [];

            $kategoriUnik = ['tanah', 'bangunan', 'apartemen-kantor', 'alat-berat', 'mesin', 'kendaraan', 'pesawat', 'kapal', 'sarana_pelengkap_penilai'];

            foreach ($kategoriUnik as $kategori) {
                // Dynamically generate keys
                $luasKey = 'luas_' . $kategori;
                $nilaiKey1 = 'nilai_' . $kategori . '_1';
                $nilaiKey2 = 'nilai_' . $kategori . '_2';

                // Collect data if exists
                if ($request->has($luasKey)) {
                    $data[$luasKey] = $request->input($luasKey);
                }
                if ($request->has($nilaiKey1)) {
                    $data[$nilaiKey1] = $request->input($nilaiKey1);
                }
                if ($request->has($nilaiKey2)) {
                    $data[$nilaiKey2] = $request->input($nilaiKey2);
                }
            }

            $data['total_nilai_pasar_wajar'] = $request->input('total_nilai_pasar_wajar');
            $data['likuidasi'] = $request->input('likuidasi');
            $data['likuidasi_nilai_1'] = $request->input('likuidasi_nilai_1');
            $data['likuidasi_nilai_2'] = $request->input('likuidasi_nilai_2');
            $data['keterangan_penilai'] = $request->input('keterangan_penilai') ?? [];

            $npwData = [];
            $npwCounter = 1;


            while ($request->has("name_npw_{$npwCounter}")) {
                $npwData[] = [
                    'name' => $request->input("name_npw_{$npwCounter}"),
                    'luas' => $request->input("luas_npw_{$npwCounter}"),
                    'nilai_1' => $request->input("nilai_npw_{$npwCounter}_1"),
                    'nilai_2' => $request->input("nilai_npw_{$npwCounter}_2")
                ];
                $npwCounter++;
            }

            if (!empty($npwData)) {
                $data['npw_tambahan'] = $npwData;
            }

            // Update atau buat data baru
            $penilai = Penilai::updateOrCreate(
                [
                    'permohonan_id' => $request->permohonanId,
                    'dokument_id' =>  $request->input('dokument_id'),
                ],
                [
                    'lpj' => json_encode($data),
                ]
            );
            DB::commit();
            return response()->json([
                'success' => true,
                'message' => 'Berhasil menyimpan LPJ',
                'data' => $result
            ], 200);
        } catch (\Throwable $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => 'Terjadi kesalahan saat menyimpan LPJ',
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ], 500);
        }
    }

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

            $validatedData = $request->all();
            $result = $this->inspeksiService->storeInspeksi($validatedData, $request->input('type'), $request);

            $data = [
                'kepada' => $request->input('kepada'),
                'dari' => $request->input('dari'),
                'nomor_rap' => $request->input('nomor_rap'),
                'tanggal' => $request->input('tanggal'),
                'perihal' => $request->input('perihal')
            ];

            Penilai::updateOrCreate(
                [
                    'permohonan_id' => $request->permohonanId,
                    'dokument_id' => $request->documentId,

                ],
                [
                    'rap' => json_encode($data),
                ]
            );
            DB::commit();
            return response()->json([
                'success' => true,
                'message' => 'Berhasil menyimpan LPJ',
                'data' => $result
            ], 200);
        } catch (\Throwable $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => 'Terjadi kesalahan saat menyimpan LPJ',
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ], 500);
        }
    }

    public function storeCallReport(Request $request)
    {
        try {

            // DB::beginTransaction();
            $validated = $request->validate([
                'permohonan_id' => 'required|exists:permohonan,id',
                'dokument_id' => 'required',
                'data' => 'required',
                'fakta_positif' => 'nullable|array',
                'fakta_negatif' => 'nullable|array',
                'type' => 'required',
                'action' => 'required',
                'keterangan' => 'nullable|array',

            ]);


            Penilai::updateOrCreate(
                [
                    'permohonan_id' => $validated['permohonan_id'],
                    'dokument_id' => $validated['dokument_id'],
                ],
                [
                    'call_report' => json_encode($validated['data']),
                ]
            );

            $inspeksi = Inspeksi::where('permohonan_id', $validated['permohonan_id'])
                ->where('dokument_id', $validated['dokument_id'])
                ->first();
            if ($inspeksi) {
                // Get existing data_form
                $existingData = json_decode($inspeksi->data_form, true) ?: [];

                // Structure the fakta data correctly
                $existingFaktaData = $existingData['fakta'] ?? [];

                // Gabungkan data baru dengan data yang sudah ada
                $updatedFaktaData = array_merge($existingFaktaData, [
                    'fakta_positif' => $validated['fakta_positif'] ?? $existingFaktaData['fakta_positif'] ?? null,
                    'fakta_negatif' => $validated['fakta_negatif'] ?? $existingFaktaData['fakta_negatif'] ?? null,
                    'keterangan' => $validated['keterangan'] ?? $existingFaktaData['keterangan'] ?? null,
                ]);
                $existingData['fakta'] = $updatedFaktaData;

                $inspeksi->update([
                    'data_form' => json_encode($existingData),
                ]);
            } else {
                // If inspeksi
                $newData = [
                    'fakta' => [
                        'fakta_positif' => $validated['fakta_positif'] ?? null,
                        'fakta_negatif' => $validated['fakta_negatif'] ?? null,
                        'keterangan' => $validated['keterangan'] ?? null,
                    ],
                ];



                Inspeksi::updateOrCreate([
                    'permohonan_id' => $validated['permohonan_id'],
                    'dokument_id' => $validated['dokument_id']
                ],[
                    'data_form' => json_encode($newData),
                    'name' => $validated['type']
                ]);
            }
            // DB::commit();
            return response()->json([
                'success' => true,
                'message' => 'Berhasil menyimpan data',
            ], 200);
        } catch (\Throwable $e) {
            // DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => 'Terjadi kesalahan saat menyimpan data',
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ], 500);
        }
    }

    public function print_out(Request $request)
    {
        $documentId = $request->query('documentId');
        $jaminanId = $request->query('jaminanId');
        $permohonanId = $request->query('permohonanId');
        $statusLpj = $request->query('statusLpj');
        $tipeLaporan = $request->query('type');

        $permohonan = $this->surveyorController->getPermohonanJaminanId(
            $permohonanId,
            $documentId,
            $jaminanId
        );

        $basicData =  $this->surveyorController->getCommonData();

        $inspeksi = Inspeksi::where('permohonan_id', $permohonanId)->where('dokument_id', $documentId)->first();
        $lpj = Penilai::where('permohonan_id', $permohonanId)->where('dokument_id', $documentId)->first();

        $nomorLaporan = getNomorLaporan($permohonanId, $documentId);
        $tanggalLaporan =  $lpj->created_at ?? null;
        $forminspeksi = null;
        $lpjData = null;
        $formFoto  = null;

        if ($inspeksi) {
            $forminspeksi = json_decode($inspeksi->data_form, true);
            $formFoto = json_decode($inspeksi->foto_form, true);
            // $denahForm = json_decode($data->denah_form, true);
            $dataPembanding = json_decode($inspeksi->data_pembanding, true);
        }

        if ($lpj) {
            $lpjData = json_decode($lpj->lpj, true);
            $memo = json_decode($lpj->memo, true);
            $resumeData = json_decode($lpj->resume, true);
            $rap = json_decode($lpj->rap, true);
            $report = json_decode($lpj->call_report, true);
        }

        $inputAddress = $forminspeksi['asset']['alamat']['sesuai'] ?? $forminspeksi['asset']['alamat']['tidak sesuai'] ?? [];

        $alamat = [
            'address' => $inputAddress['address'] ?? null,
            'village_code' => getWilayahName($inputAddress['village_code'] ?? null, 'village'),
            'district_code' => getWilayahName($inputAddress['district_code'] ?? null, 'district'),
            'city_code' => getWilayahName($inputAddress['city_code'] ?? null, 'city'),
            'province_code' => getWilayahName($inputAddress['province_code'] ?? null, 'province')
        ];

        $viewLaporan = $this->getViewLaporan($tipeLaporan);
        try {

            if ($statusLpj) {
                //   $pdf = view('lpj::' . $viewLaporan, compact(
                $pdf = PDF::loadView('lpj::' . $viewLaporan, compact(
                    'permohonan',
                    'forminspeksi',
                    'lpjData',
                    'formFoto',
                    'basicData',
                    'inspeksi',
                    'lpj',
                    'statusLpj',
                    'alamat',
                    'dataPembanding',
                    'nomorLaporan',
                    'memo',
                    'resumeData',
                    'tanggalLaporan',
                    'rap',
                    'report'
                ));
                // return $pdf;
                $cleanNomorLaporan = str_replace(['/', '\\'], '-', $nomorLaporan);
                $pdf->setPaper('A4', 'portrait');
                $pdf->set_option('isHtml5ParserEnabled', true);
                $pdf->set_option('isPhpEnabled', true);
                return response($pdf->output(), 200)
                    ->header('Content-Type', 'application/pdf')
                    ->header('Content-Disposition', 'inline; filename="Laporan_' . $tipeLaporan . '_' . $permohonan->debiture->name . '_' . $cleanNomorLaporan . '.pdf"');
                // return  $pdf->stream();
            } else {
                // $pdf = view('lpj::' . $viewLaporan, compact(
                $pdf = PDF::loadView('lpj::' . $viewLaporan, compact(
                    'permohonan',
                    'forminspeksi',
                    'lpjData',
                    'formFoto',
                    'basicData',
                    'inspeksi',
                    'lpj',
                    'statusLpj',
                    'alamat',
                    'dataPembanding',
                    'nomorLaporan',
                    'memo',
                    'resumeData',
                    'tanggalLaporan',
                    'rap',
                    'report'
                ));
                // return $pdf;
                $cleanNomorLaporan = str_replace(['/', '\\'], '-', $nomorLaporan);
                $pdf->setPaper('A4', 'portrait');
                $pdf->set_option('isHtml5ParserEnabled', true);
                $pdf->set_option('isPhpEnabled', true);
                return  $pdf->download('Laporan_' . $tipeLaporan . '_' . $permohonan->debiture->name . '_' . $cleanNomorLaporan . '_data.pdf');
            }
        } catch (\Exception $e) {
            Log::error('PDF generation failed: ' . $e->getMessage());
            return response()->json(['error' => 'Failed to generate PDF. Please check the log for details.' . $e->getMessage()], 500);
        }
    }

    public function print_out_laporan($permohonan_id, $document_id, $jaminan_id)
    {
        // jika tidak ada id kembalikan ke halaman sebelumnya
        if (!$permohonan_id || !$document_id || !$jaminan_id) {
            return redirect()->back()->with('error', 'Laporan tidak valid');
        }
        return $this->previewLaporanService->printOutLaporan($permohonan_id, $document_id, $jaminan_id);
    }

    private function getViewLaporan($tipe)
    {
        $viewMap = [
            'sederhana' => 'penilai.components.print-out-sederhana',
            'standar' => 'penilai.components.print-out-standar',
            'resume' => 'penilai.components.print-resume',
            'memo' => 'penilai.components.print-memo',
            'rap' => 'penilai.components.print-out-rap',
            'call-report' => 'penilai.components.print-out-call-report'
        ];
        return $viewMap[$tipe] ?? 'penilai.components.print-resume';
    }



    // mengambil data dari fungsi permohonan di surveyor, dan table
    // penilai, inspeksi
    private function getDataPermohonanWithPenilaiAndInspeksi($permohonanId, $documentId, $jaminanId)
    {
        return [
            'permohonan' => $this->surveyorController->getPermohonanJaminanId($permohonanId, $documentId, $jaminanId),
            'penilai' => Penilai::where('permohonan_id', $permohonanId)->where('dokument_id', $documentId)->first(),
            'inspeksi' => Inspeksi::where('permohonan_id', $permohonanId)->where('dokument_id', $documentId)->first()
        ];
    }


    // pengunaan request query by id permohonan, documentId, jaminan , inspeksi
    protected function getRequestQueryId(Request $request)
    {
        return [
            'permohonanId' => $request->query('permohonanId'),
            'documentId' => $request->query('documentId'),
            'jaminanId' => $request->query('jaminanId'),
        ];
    }

    public function checkPrintOutLaporan(Request $request)
    {
        $permohonanId = $request->query('permohonanId');
        $documentId = $request->query('documentId');

        // Ambil data berdasarkan ID
        $statusLpj = Penilai::where('permohonan_id', $permohonanId)
            ->where('dokument_id', $documentId)
            ->first();

        // Jika data tidak ditemukan, kembalikan status null
        if (!$statusLpj) {
            return response()->json(['status' => null]);
        }

        // Tentukan tipe berdasarkan kondisi
        $type = $statusLpj->type_penilai ?? null;

        if ($type === 'memo') {
            return $this->checkDataMemo($type, $statusLpj);
        }

        if ($type === 'resume') {
            return $this->checkDataResume($type, $statusLpj);
        }


        if ($type === 'standar' || $type === 'sederhana') {
            return $this->checkDataLpj($type, $statusLpj);
        }

        if ($type === 'rap') {
            return $this->checkDataRap($type, $statusLpj);
        }



        // Kembalikan respons dengan tipe yang sesuai
        return response()->json(['status' => $type]);
    }


    public function generateNoLaporan($permohonan, $documentId, $type)
    {
        $typeMapping = ['lpj' => 'LPJ', 'memo' => 'MAK', 'rap' => 'RAP', 'call-report' => 'CR'];

        // Cek apakah data sudah ada
        $laporan = Laporan::where([
            'permohonan_id' => $permohonan->id,
            'dokumen_jaminan_id' => $documentId,
        ])->first();

        if ($laporan) {

            $nomorArray = explode('/', $laporan->nomor_laporan);
            $nomorArray[2] = $typeMapping[$type] ?? 'RES';
            $laporan->update([
                'nomor_laporan' => implode('/', $nomorArray)
            ]);
        } else {

            $laporan = Laporan::create([
                'permohonan_id' => $permohonan->id,
                'dokumen_jaminan_id' => $documentId,
                'nomor_laporan' => implode('/', [
                    $permohonan->debiture->branch->code,
                    generateLpjUniqueCode(3),
                    $typeMapping[$type] ?? 'RSM',
                    $permohonan->nomor_registrasi,
                    onRomawi(date('m')),
                    substr(date('Y'), -2)
                ])
            ]);
        }

        return $laporan->nomor_laporan;
    }


    public function checkDataMemo($type, $statusLpj)
    {
        // Ambil data JSON dari statusLpj
        $data = json_decode($statusLpj->memo, true) ?? [];

        $validationRules = [
            'memo' => [
                'kepada',
                'dari',
                'nomor_memo',
                'tanggal',
                'perihal',
                'jenis_asset_tidak_sesuai',
                'lokasi.lokasi',
                'lokasi.province_code',
                'lokasi.city_code',
                'lokasi.district_code',
                'lokasi.village_code',
                'lokasi.penilai',
                'terlampir',
                'hasil_survey',
                'kesimpulan_saran',
            ],
        ];

        // Validasi data JSON
        if (isset($validationRules[$type])) {
            $missingFields = [];

            foreach ($validationRules[$type] as $field) {
                $keys = explode('.', $field);
                $value = $data;

                foreach ($keys as $key) {
                    if (!isset($value[$key])) {
                        $missingFields[] = $field;
                        break;
                    }
                    $value = $value[$key];
                }
            }

            // Jika ada field yang kosong, kembalikan error
            if (!empty($missingFields)) {
                return response()->json([
                    'status' => null,
                    'message' => "Silahkan lengkapi data memo terlebih dahulu.",
                    'missing_fields' => $missingFields,
                ], 400);
            }
        }

        // Jika data valid
        return response()->json([
            'status' => $type,
            'message' => "Data memo valid.",
        ]);
    }




    public function checkDataResume($type, $statusLpj)
    {
        // Ambil data JSON dari statusLpj
        $data = json_decode($statusLpj->resume, true) ?? [];

        $validationRules = [
            'resume' => [
                'fisik'
            ],
        ];

        // Validasi data JSON
        if (isset($validationRules[$type])) {
            $missingFields = [];

            foreach ($validationRules[$type] as $field) {
                $keys = explode('.', $field);
                $value = $data;

                foreach ($keys as $key) {
                    if (!isset($value[$key])) {
                        $missingFields[] = $field;
                        break;
                    }
                    $value = $value[$key];
                }

                // Validasi khusus untuk array fisik dan sesuai_imb
                if ($field === 'fisik' || $field === 'sesuai_imb') {
                    if (empty($value) || !is_array($value)) {
                        $missingFields[] = $field;
                        continue;
                    }

                    // Validasi struktur data di dalam array
                    foreach ($value as $item) {
                        $requiredKeys = ['sertifikat', 'luas_tanah', 'nilai'];
                        foreach ($requiredKeys as $requiredKey) {
                            if (!isset($item[$requiredKey])) {
                                $missingFields[] = $field . '.' . $requiredKey;
                            }
                        }
                    }
                }
            }

            // Jika ada field yang kosong, kembalikan error
            if (!empty($missingFields)) {
                return response()->json([
                    'status' => null,
                    'message' => "Silahkan lengkapi data resume terlebih dahulu.",
                    'missing_fields' => $missingFields,
                ], 400);
            }
        }

        // Jika data valid
        return response()->json([
            'status' => $type,
            'message' => "Data resume valid.",
        ]);
    }

    public function checkDataLpj($type, $statusLpj)
    {
        // Ambil data JSON dari statusLpj
        $data = json_decode($statusLpj->lpj, true) ?? [];

        $validationRules = [
            'lpj' => [
                'luas_tanah',
                'nilai_tanah_1',
                'nilai_tanah_2',
                'luas_bangunan',
                'nilai_bangunan_1',
                'nilai_bangunan_2',
                'total_nilai_pasar_wajar',
                'likuidasi',
                'likuidasi_nilai_1',
                'likuidasi_nilai_2',
                'asuransi_luas_bangunan',
                'asuransi_nilai_1',
                'asuransi_nilai_2',
                'npw_tambahan'
            ],
        ];

        // Validasi data JSON
        if (isset($validationRules[$type])) {
            $missingFields = [];

            foreach ($validationRules[$type] as $field) {
                // Penanganan khusus untuk field yang boleh null
                if (in_array($field, ['sarana_pelengkap_penilai', 'nilai_sarana_pelengkap_1', 'nilai_sarana_pelengkap_2'])) {
                    continue;
                }

                if (!isset($data[$field])) {
                    $missingFields[] = $field;
                    continue;
                }

                // Validasi khusus untuk npw_tambahan
                if ($field === 'npw_tambahan' && is_array($data[$field])) {
                    foreach ($data[$field] as $index => $item) {
                        $requiredKeys = ['name', 'luas', 'nilai_1', 'nilai_2'];
                        foreach ($requiredKeys as $key) {
                            if (!isset($item[$key])) {
                                $missingFields[] = "npw_tambahan[$index].$key";
                            }
                        }
                    }
                }
            }


            // Jika ada field yang kosong, kembalikan error
            if (!empty($missingFields)) {
                return response()->json([
                    'status' => null,
                    'message' => "Silahkan lengkapi data LPJ terlebih dahulu.",
                    'missing_fields' => $missingFields,
                ], 400);
            }
        }

        // Jika data valid
        return response()->json([
            'status' => $type,
            'message' => "Data LPJ valid.",
        ]);
    }

    public function checkDataRap($type, $statusLpj)
    {
        // Ambil data JSON dari statusLpj
        $data = json_decode($statusLpj->rap, true) ?? [];

        $requiredFields = [
            'dari',
            'kepada',
            'perihal',
            'tanggal',
            'nomor_rap'
        ];

        // Cek apakah ada field yang kosong
        $missingFields = [];
        foreach ($requiredFields as $field) {
            if (!isset($data[$field]) || empty($data[$field])) {
                $missingFields[] = $field;
            }
        }

        // Jika ada field yang kosong, kembalikan error
        if (!empty($missingFields)) {
            return response()->json([
                'status' => null,
                'message' => "Silahkan lengkapi data RAP terlebih dahulu.",
                'missing_fields' => $missingFields
            ], 400);
        }

        // Jika semua data terisi
        return response()->json([
            'status' => $type,
            'message' => "Data RAP valid."
        ]);
    }


    public function revisiSurveyor(Request $request, $id)
    {
        $permohonan = Permohonan::findOrFail($id);

        if ($permohonan->status === 'proses-laporan') {
            return response()->json([
                'success' => false,
                'message' => 'Masih proses laporan',
            ], 400);
        }

        if ($permohonan->status === 'proses-paparan') {
            return response()->json([
                'success' => false,
                'message' => 'Masih proses paparan',
            ], 400);
        }


        $permohonan->update([
            'status' => 'revisi-survey',
            'keterangan' => $request->message,
            'submitted_at' => now()
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Berhasil Revisi Ke surveyor',
        ], 200);
    }

    public function showLaporanInspeksi(
        $permohonan_id,
        $dokumen_id,
        $jaminan_id,
        Request $request)
    {
        if ($request->type == 'penilai') {
            $back = route('penilai.show', $permohonan_id);
        }else{
            $back = route('surveyor.show', $permohonan_id);
        }

        return $this->previewLaporanService->previewLaporan($permohonan_id, $dokumen_id, $jaminan_id, $back);
    }

    public function showInspectionReportReview($permohonan_id, $dokumen_id, $jaminan_id)
    {

    }
}
