<?php

namespace Modules\Lpj\Http\Controllers;

use App\Http\Controllers\Controller;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Modules\Lpj\Http\Requests\PenilaianRequest;
use Modules\Lpj\Models\Authorization;
use Modules\Lpj\Models\JenisPenilaian;
use Modules\Lpj\Models\LaporanAdminKredit;
use Modules\Lpj\Models\Penilaian;
use Modules\Lpj\Models\PenilaianTeam;
use Modules\Lpj\Models\Permohonan;
use Modules\Lpj\Models\StatusPermohonan;
use Modules\Lpj\Models\Teams;
use Modules\Lpj\Models\Inspeksi;
use Modules\Lpj\Models\Penilai;
use Modules\Lpj\Models\Regions;
use Modules\Location\Models\Province;
use Modules\Location\Models\City;
use Modules\Location\Models\District;
use Modules\Location\Models\Village;
use Modules\Usermanagement\Models\User;
use Modules\Lpj\Http\Controllers\SurveyorController;
use Modules\Lpj\Http\Controllers\PenilaiController;
use Modules\Lpj\Http\Requests\FormSurveyorRequest;

class PenilaianController extends Controller
{
    public $user;
    protected $surveyorController;
    protected $penilaiController;

    public function __construct(SurveyorController $surveyorController, PenilaiController $penilaiController)
    {
        $this->surveyorController = $surveyorController;
        $this->penilaiController = $penilaiController;
    }


    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $status_permohonan = StatusPermohonan::all();

        return view('lpj::penilaian.index', compact('status_permohonan'));
    }

    /**
     * Store a newly created resource in storage.
     */

    public function store(PenilaianRequest $request)
    {
        $validatedData = $request->validated();

        if ($validatedData) {
            try {
                DB::beginTransaction();

                $penilaian                     = Penilaian::create($validatedData);
                $validatedData['penilaian_id'] = $penilaian->id;

                $teams_ids = [];
                $user_ids  = [];
                $roles     = [];

                if ($validatedData['surveyor_id'] === 'pilih_dari_region') {
                    $surveyor_region_id = $validatedData['surveyor_region_id'];

                    // Hapus team_id sebelumnya di Permohonan jika ada
                    $permohonan = Permohonan::where('nomor_registrasi', $request->nomor_registrasi)->first();
                    if ($permohonan) {
                        $permohonan->update([
                            'region_id' => $surveyor_region_id,
                        ]);
                    }

                    $teams_ids[] = $surveyor_region_id;
                    $user_ids[]  = null;
                    $roles[]     = 'surveyor';
                } else {
                    $permohonan  = Permohonan::where('nomor_registrasi', $request->nomor_registrasi)->first();

                    if (isset($validatedData['penilai_surveyor_id'])) {
                        if ($validatedData['penilai_surveyor_id'] == 'pilih_dari_region') {
                            $teams_ids[] = $validatedData['surveyor_penilai_region_id'];
                            $user_ids[]  = null;

                        } else {
                            $teams_ids[] = $validatedData['teams_id'];
                            $user_ids[] = $validatedData['penilai_surveyor_id'];
                        }

                    } else {
                        $teams_ids[] = $validatedData['teams_id'];
                        $user_ids[] = $validatedData['surveyor_id'];

                    }

                    $roles[] = 'surveyor';
                }

                if ($validatedData['penilai_id'] === 'pilih_dari_region') {
                    $penilaian_region_id = $validatedData['penilai_region_id'];

                    // Hapus team_id sebelumnya di Permohonan jika ada
                    $permohonan = Permohonan::where('nomor_registrasi', $request->nomor_registrasi)->first();
                    if ($permohonan) {
                        $permohonan->update([
                            'region_id' => $penilaian_region_id,
                        ]);
                    }

                    $teams_ids[] = $penilaian_region_id;
                    $user_ids[]  = null;
                    $roles[]     = 'penilai';
                } else {
                    $permohonan  = Permohonan::where('nomor_registrasi', $request->nomor_registrasi)->first();


                    if (isset($validatedData['penilai_surveyor_id'])) {
                        if ($validatedData['penilai_surveyor_id'] == 'pilih_dari_region') {


                            $permohonan->update([
                                'region_id' => $validatedData['surveyor_penilai_region_id'],
                            ]);

                            $teams_ids[] = $validatedData['surveyor_penilai_region_id'];
                            $user_ids[]  = null;
                        } else {
                            $teams_ids[] = $validatedData['teams_id'];
                            $user_ids[] = $validatedData['penilai_surveyor_id'];
                        }
                    } else {
                        $teams_ids[] = $validatedData['teams_id'];
                        $user_ids[] = $validatedData['penilai_id'];
                    }

                    $roles[] = 'penilai';
                }

                // dd($validatedData['penilai_region_id'],$validatedData['teams_id']);
                foreach ($teams_ids as $key => $teams_id) {
                    PenilaianTeam::create([
                        'penilaian_id' => $validatedData['penilaian_id'],
                        'team_id'      => $teams_id,
                        'user_id'      => $user_ids[$key],
                        'role'         => $roles[$key],
                    ]);
                }

                if ($validatedData['surveyor_id'] === 'pilih_dari_region' || $validatedData['penilai_id'] === 'pilih_dari_region' || $validatedData['penilai_surveyor_id'] === 'pilih_dari_region') {
                    $status = 'reassign';
                } else {
                    $status = 'assign';
                }

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

                DB::commit();
                return response()->json(['success' => true, 'message' => 'Data berhasil di-assign.'], 200);
            } catch (Exception $e) {
                dd($e);
                DB::rollBack();

                return response()->json(['error' => $e->getMessage()]);
            }
        }
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create($id)
    {
        return view('lpj::penilaian.form');
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, $id)
    {
        try {
            DB::beginTransaction();
            $penilaian = Penilaian::where('nomor_registrasi', $request->nomor_registrasi)->first();

            $surveyTeam = null;
            $penilaiTeam = null;
            $penilaianId = $penilaian->id;

            $penilainTeam = PenilaianTeam::where('penilaian_id', $penilaianId)->get();


            foreach ($penilainTeam as $item) {
                if ($item->role === 'surveyor' && $item->user_id === null) {
                    $item->update([
                        'user_id' => $request->surveyor_id,
                        'role'    => 'surveyor',
                    ]);
                    $surveyTeam = $item->team_id;
                }

                if ($item->role === 'penilai' && $item->user_id === null) {
                    $item->update([
                        'user_id' => $request->penilai_id,
                        'role'    => 'penilai',
                    ]);

                }

                if ($item->role === 'penilai' && $surveyTeam) {
                    $penilaiTeam = $item->team_id;
                }
            }

            $permohonan = Permohonan::where('nomor_registrasi', $request->nomor_registrasi);

            if ($surveyTeam && $penilaiTeam) {
                $permohonan->update([
                    'region_id' => $penilaiTeam,
                ]);
            }
            $permohonan->update([
                'status' => 'assign',
            ]);
            DB::commit();
            return response()->json(['success' => true, 'message' => 'Data berhasil di-assign.'], 200);
        } catch (Exception $e) {
            DB::rollBack();
            return response()->json(['success' => false, 'error' => $e->getMessage()]);
        }
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function assignment($id)
    {
        $permohonan = Permohonan::with([
            'user',
            'debiture.province',
            'debiture.city',
            'debiture.district',
            'debiture.village',
            'branch',
            'tujuanPenilaian',
        ])->findOrFail($id);

        $idPenilaian = $permohonan->jenis_penilaian_id;
        $idRegion    = $permohonan->region_id;

        $jenisPenilaian = JenisPenilaian::find($idPenilaian);

        $userTeam = Teams::with(['regions', 'teamsUsers.user'])->whereHas('regions', function ($q) use ($idRegion) {
            $q->where('id', $idRegion);
        })->get();

        $teamPenilai = $userTeam->flatMap(function ($team) {
            return $team->teamsUsers->filter(function ($teamUser) {
                return $teamUser->user->roles->contains(function ($role) {
                    return $role->name === 'surveyor' || $role->name === 'penilai' || $role->name === 'administrator';
                });
            })->map(function ($teamUser) {
                return $teamUser->user;
            });
        })->unique('id');

        $existingTeamIds = $userTeam->pluck('id')->toArray();

        $updateTeamPenilai = Teams::with(['regions', 'teamsUsers', 'teamsUsers.user'])->whereNotIn(
            'id',
            $existingTeamIds,
        )->get();

        $regionName = null;
        foreach ($userTeam as $item) {
            $regionName = $item->regions;
        }

        $penilaian = Penilaian::where('nomor_registrasi', $permohonan->nomor_registrasi)->first();

        $penilaianTeam = collect();
        if ($penilaian && $penilaian->id) {
            $penilaianTeam = PenilaianTeam::where('penilaian_id', $penilaian->id)->get();
        }

        // dd($penilaianTeam);

        return view(
            'lpj::penilaian.form',
            compact(
                'permohonan',
                'teamPenilai',
                'jenisPenilaian',
                'penilaian',
                'regionName',
                'updateTeamPenilai',
                'penilaianTeam',
            ),
        );
    }

    /**
     * Remove the specified resource from storage.
     */

    public function revisi(PenilaianRequest $request, $nomor_registrasi)
    {
        $validatedData = $request->validated();
        if ($validatedData) {
            try {
                if (isset($validatedData['dokumen']) && $request->hasFile('dokumen')) {
                    $file_name = $validatedData['dokumen']->getClientOriginalName();
                    $validatedData['dokumen']->storeAs('public/dokumen_revisi', $file_name);
                }

                $dataToUpdate = [
                    'keterangan' => $validatedData['keterangan'],
                    'dokumen'    => 'dokumen_revisi/' . $file_name,
                    'status'     => 'revisi',
                ];


                $permohonan = Permohonan::where('nomor_registrasi', $nomor_registrasi)->first();

                $permohonan->update($dataToUpdate);
                return redirect()->route('penilaian.index')->with('success', 'Penilaian berhasil direvisi');
            } catch (Exception $e) {
                return redirect()->route('penilaian.index')->with('error', $e->getMessage());
            }
        }
    }


    public function dataForDatatables(Request $request)
    {
        if (is_null($this->user) || !$this->user->can('debitur.view')) {
        }

        $query = Permohonan::query();

        if ($request->has('search') && !empty($request->get('search'))) {
            $search = $request->get('search');
            $query->where(function ($q) use ($search) {
                $q->where('nomor_registrasi', 'LIKE', '%' . $search . '%');
                $q->orWhere('tanggal_permohonan', 'LIKE', '%' . $search . '%');
                $q->orWhereRelation('user', 'name', 'LIKE', '%' . $search . '%');
                $q->orWhereRelation('debiture', 'name', 'LIKE', '%' . $search . '%');
                $q->orWhereRelation('tujuanPenilaian', 'name', 'LIKE', '%' . $search . '%');
                $q->orWhereRelation('branch', 'name', 'LIKE', '%' . $search . '%');
                $q->orWhere('status', 'LIKE', '%' . $search . '%');
            });
        }

        $query->whereIn('status', ['registered', 'registrasi-final', 'reassign']);


        if (Auth::user()->roles[0]->name !== 'administrator') {

            $query->whereHas('region.teams.teamsUsers.user', function ($q) {
                $q->where('id', Auth::user()->id);
            });
        }

        if ($request->has('sortOrder') && !empty($request->get('sortOrder'))) {
            $order  = $request->get('sortOrder');
            $column = $request->get('sortField');
            $query->orderBy($column, $order);
        }

        $totalRecords = $query->count();

        $size = $request->get('size', 10);
        if ($size == 0) {
            $size = 10;
        }

        if ($request->has('page') && $request->has('size')) {
            $page   = $request->get('page', 1);
            $offset = ($page - 1) * $size;

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

        $filteredRecords = $query->count();
        $data            = $query->with(
            ['user', 'debiture', 'branch', 'tujuanPenilaian', 'jenisPenilaian', 'region.teams.teamsUsers.user',
        ]
        )->get();

        $pageCount = ceil($totalRecords / $size);

        $currentPage = max(1, $request->get('page', 1));
        return response()->json([
            'draw'            => $request->get('draw'),
            'recordsTotal'    => $totalRecords,
            'recordsFiltered' => $filteredRecords,
            'pageCount'       => $pageCount,
            'page'            => $currentPage,
            'totalCount'      => $totalRecords,
            'data'            => $data,
        ]);
    }


    public function otorisator(Request $request)
    {
        $type    = $request->route('type');
        $headers = [
            'pelaporan'  => 'Pelaporan',
            'pembayaran' => 'Pembayaran',
            'pembatalan' => 'Pembatalan',
            'sla'        => 'SLA',
            'paparan' => 'Paparan'
        ];

        $regions = Regions::all();

        $header = $headers[$type] ?? 'Pelaporan';

        switch ($header) {
            case 'SLA':
                return view('lpj::penilaian.otorisator.index-sla', compact('header'));
            case 'Paparan':
                return view('lpj::penilaian.paparan-so', compact('header'));
            default:
                return view('lpj::penilaian.otorisator.index', compact('header', 'regions'));
        }

    }

    public function show($id, $type)
    {
        $headers = [
            'Pelaporan'  => 'Pelaporan',
            'Pembayaran' => 'Pembayaran',
            'Pembatalan' => 'Pembatalan',
            'SLA'        => 'SLA',
            'Paparan' => 'Paparan'
        ];

        $header     = $headers[$type] ?? 'Pelaporan';
        $authorization = null;
        if ($header === 'SLA') {
            $authorization = Authorization::with(['user','permohonan.lampiranDokumen.jenisLampiran'])->find($id);
            $permohonan = Permohonan::with(['lampiranDokumen.jenisLampiran'])->find($authorization->permohonan_id);
        } else {
            $permohonan = Permohonan::with(['lampiranDokumen.jenisLampiran'])->find($id);
        }
        if ($header === 'SLA') {
            return view('lpj::penilaian.otorisator.sla', compact('permohonan', 'header', 'authorization'));
        }
        if ($header === 'Paparan') {
            $authorization = Authorization::with(['user'])->where('permohonan_id', $id)->first();
            return view('lpj::penilaian.otorisator.show', compact('permohonan', 'header', 'authorization'));
        }
        return view('lpj::penilaian.otorisator.show', compact('permohonan', 'header', 'authorization'));
    }

    public function otorisatorUpdate(Request $request, $id, $context)
    {
        if ($context === 'Freze SLA' || $context === 'Unfreeze SLA') {
            $authorization = Authorization::with(['user'])->find($id);
            if (!$authorization) {
                return response()->json([
                    'message' => 'Data authorization SLA tidak ditemukan.',
                ], 404);
            }
            $permohonan = Permohonan::find($authorization->permohonan_id);
        } elseif ($context === 'Paparan') {
            $authorization = Authorization::with(['user'])->find($id);
            if (!$authorization) {
                return response()->json([
                    'message' => 'Data authorization Paparan tidak ditemukan.',
                ], 404);
            }
            $permohonan = Permohonan::find($authorization->permohonan_id);
        } else {
            $permohonan = Permohonan::find($id);
        }

        if (!$permohonan) {
            return response()->json([
                'message' => 'Data permohonan tidak ditemukan.',
            ], 404);
        }

        switch (strtolower($context)) {
            case 'pembayaran':

                $newStatus = $permohonan->status_bayar === 'sudah_bayar' ? 'belum_bayar' : 'sudah_bayar';

                $permohonan->update([
                    'status_bayar' => $newStatus,
                    'keterangan'   => $request->keterangan,
                ]);
                break;

            case 'pembatalan':
                $permohonan->update([
                    'status'     => 'batal',
                    'keterangan' => $request->keterangan,
                ]);
                break;

            case 'pelaporan':
                $role = Auth::user()->roles[0]->name;
                $status = 'done';
                $approvalField = null;

                $lpj_ = optional(json_decode($permohonan->penilai->lpj));
                $npw = $lpj_->total_nilai_pasar_wajar ?? 0;
                $npw = str_replace('.', '', $npw);


                if ($role === 'senior-officer') {
                    $approvalField = 'approval_so';
                    $status = $npw <=1000000000 ? 'done' : 'proses-laporan';
                } elseif ($role === 'EO Appraisal') {
                    $approvalField = 'approval_eo';
                    $status = $npw <=5000000000 ? 'done' : 'proses-laporan';
                } elseif ($role === 'DD Appraisal') {
                    $approvalField = 'approval_dd';
                    $status = 'done';
                }

                if ($status == 'done' && $permohonan->status_bayar === 'sudah_bayar' && $permohonan->penilai->type_penilai === 'standar' || $permohonan->penilai->type_penilai === 'sederhana') {
                    $_permohonan = Permohonan::with(['documents.jenisJaminan','penilaian._user_penilai','penilai','documents.detail.jenisLegalitasJaminan'])->find($permohonan->id);

                    if (isset($_permohonan->penilai->lpj)) {
                        $npw = json_decode($_permohonan->penilai->lpj, true);
                        $npw = $npw['total_nilai_pasar_wajar'] ?? 0;
                    }

                    $dataAdk = [
                        'debiture_id'       => $_permohonan->debiture_id,
                        'jenis_agunan'      => $_permohonan->documents->pluck('jenisJaminan.name')->unique()->implode(', '),
                        'alamat_agunan'     => $_permohonan->documents->map(function ($document) {
                            return formatAlamat($document);
                        })->unique()->implode(', '),
                        'nama_pemilik'      => $_permohonan->documents->pluck('pemilik.name')->unique()->implode(', '),
                        'tanggal_kunjungan' => $_permohonan->penilaian->tanggal_kunjungan,
                        'nama_penilai'      => $_permohonan->penilaian->_user_penilai->userPenilaiTeam->name,
                        'nilai_likuidasi'   => $_permohonan->nilai_liquidasi,
                        'nilai_pasar_wajar' => str_replace('.', '', $npw),
                        'bukti_kepemilikan' => $_permohonan->documents->flatMap(function ($document) {
                            return $document->detail->map(function ($detail) {
                                return $detail->jenisLegalitasJaminan->name ?? null;
                            });
                        })->filter()->unique()->implode(', '),

                    ];
                    LaporanAdminKredit::create($dataAdk);
                }

                if ($approvalField) {
                    $this->updatePermohonan($permohonan, $status, $approvalField, $request->keterangan);
                }
                break;

            case 'freze sla':
                if (Auth::user()->roles[0]->name === 'senior-officer' || Auth::user()->roles[0]->name === 'administrator' && $authorization->approve_so === null) {
                    $authorization->update([
                        'status'         => '3',
                        'status_so' => '1',
                        'approve_so'    => Auth::user()->id,
                        'approve_so_at' => now(),
                        'keterangan_so'     => $request->message,
                    ]);
                } elseif (Auth::user()->roles[0]->name === 'EO Appraisal' || Auth::user()->roles[0]->name === 'administrator'  && $authorization->approve_so && $authorization->approve_eo === null) {
                    $status = '2';
                    if (in_array($permohonan->nilai_plafond_id, [1, 2])) {
                        $status = '1';
                        $permohonan->update([
                            'status'         => $authorization->request
                        ]);
                    }

                    $authorization->update([
                        'status'         => $status,
                        'status_eo' => '1',
                        'approve_eo'    => Auth::user()->id,
                        'approve_eo_at' => now(),
                        'keterangan_eo'     => $request->message,
                    ]);
                } elseif (Auth::user()->roles[0]->name === 'DD Appraisal' || Auth::user()->roles[0]->name === 'administrator'  && $authorization->approve_so && $authorization->approve_eo  && $authorization->approve_dd === null) {
                    $authorization->update([
                        'status'         => '1',
                        'status_dd' => '1',
                        'approve_dd'    => Auth::user()->id,
                        'approve_dd_at' => now(),
                        'keterangan_dd'     => $request->message,
                    ]);

                    $permohonan->update([
                        'status'         => $authorization->request
                    ]);
                }
                break;
            case 'paparan':
                if (Auth::user()->roles[0]->name === 'senior-officer' || Auth::user()->roles[0]->name === 'administrator' && $authorization->approve_so === null) {
                    $status = '3';
                    if (in_array($permohonan->nilai_plafond_id, [3])) {
                        $status = '1';
                        $permohonan->update([
                            'status'         => $authorization->request
                        ]);
                    }
                    $authorization->update([
                        'status'         => $status,
                        'status_so' => '1',
                        'approve_so'    => Auth::user()->id,
                        'approve_so_at' => now(),
                        'keterangan_so'     => $request->keterangan,
                    ]);

                    $permohonan->update([
                        'tanggal_paparan' => $request->tanggalPaparan,
                        'keterangan'      => $request->keterangan
                    ]);

                } elseif (Auth::user()->roles[0]->name === 'EO Appraisal') {
                    $status = '2';
                    if (in_array($permohonan->nilai_plafond_id, [1,2, 3])) {
                        $status = '1';
                        $permohonan->update([
                            'status'         => $authorization->request
                        ]);
                    }
                    $authorization->update([
                        'status'         => $status,
                        'status_eo' => '1',
                        'approve_eo'    => Auth::user()->id,
                        'approve_eo_at' => now(),
                        'keterangan_eo'     => $request->keterangan,
                    ]);
                } elseif (Auth::user()->roles[0]->name === 'DD Appraisal' || Auth::user()->roles[0]->name === 'administrator'  && $authorization->approve_so  && $authorization->approve_dd === null) {
                    $authorization->update([
                        'status'         => '1',
                        'status_dd' => '1',
                        'approve_dd'    => Auth::user()->id,
                        'approve_dd_at' => now(),
                        'keterangan_dd'     => $request->keterangan,
                    ]);

                    $permohonan->update([
                        'status'         => 'paparan'
                    ]);
                }
                break;
            case 'unfreeze sla':
                $authorization->update([
                    'request'         => 'unfreeze-sla',
                ]);
                $permohonan->update([
                    'status'         => 'unfreeze-sla',
                ]);
                break;

            default:
                return response()->json([
                    'message' => 'Konteks otorisasi tidak valid.',
                ], 400);
        }


        return response()->json([
            'message' => 'Otorisasi berhasil dilakukan.',
            'data'    => $permohonan,
        ]);
    }

    public function updatePermohonan($permohonan, $status, $approvalField, $message)
    {


        $permohonan->update([
            'status'         => $status,
            $approvalField   => Auth::user()->id,
            "{$approvalField}_at" => now(),
            'keterangan'     => $message,
        ]);
    }

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


        // Tentukan status berdasarkan otorisator
        $status = match ($otorisator) {
            'Pelaporan'  => 'proses-laporan',
            'Pembayaran' => 'proses',
            'Pembatalan' => 'batal',
            'SLA'        => 'request-freeze',
            'Paparan' => 'proses-paparan',
            default      => '',
        };


        $query = Permohonan::query();

        // Pencarian berdasarkan parameter search
        if ($request->has('search') && !empty($request->get('search'))) {
            $search = $request->get('search');

            $query->where(function ($q) use ($search) {
                $q->where('nomor_registrasi', 'LIKE', '%' . $search . '%');
                $q->orWhere('tanggal_permohonan', 'LIKE', '%' . $search . '%');
                $q->orWhereRelation('user', 'name', 'LIKE', '%' . $search . '%');
                $q->orWhereRelation('debiture', 'name', 'LIKE', '%' . $search . '%');
                $q->orWhereRelation('tujuanPenilaian', 'name', 'LIKE', '%' . $search . '%');
                $q->orWhereRelation('branch', 'name', 'LIKE', '%' . $search . '%');
                $q->orWhereRelation('region', 'name', 'LIKE', '%' . $search . '%');
                $q->orWhere('status', 'LIKE', '%' . $search . '%');
            });
        }


        if (!empty($otorisator)) {
            if ($status == 'proses') {
                $query->whereIn('status_bayar', ['sudah_bayar', 'belum_bayar']);
            } elseif ($status == 'proses-laporan') {
                $query->whereRaw('LOWER(status) = ?', [strtolower($status)]);
            } elseif ($status == 'batal') {
                $query->whereRaw('LOWER(status) = ?', [strtolower($status)]);
            } elseif ($status == 'request-freeze') {
                $query->whereRaw('LOWER(status) = ?', [strtolower($status)]);
            } elseif ($status == 'proses-paparan') {
                $query->whereRaw('LOWER(status) IN (?, ?)', ['proses-paparan', 'paparan']);
            }
        }

        // Filter berdasarkan region user yang login
        // if ($status == 'proses-laporan') {
        //     $requestedRegion = $request->get('search');

        //     if ($requestedRegion) {
        //         $query->whereHas('region', function ($q) use ($requestedRegion) {
        //             $q->where('name', $requestedRegion);
        //         });
        //     } else {
        //         $query->whereHas('region.teams.teamsUsers', function ($q) {
        //             $q->where('user_id', Auth::id());
        //         });
        //     }
        // } else {
        if (Auth::user()->hasRole('senior-officer')) {
            $query->whereHas('region.teams.teamsUsers', function ($q) {
                $q->where('user_id', Auth::id());
            });
        }
        // }




        // Sorting berdasarkan sortField dan sortOrder
        if ($request->has('sortOrder') && !empty($request->get('sortOrder'))) {
            $order  = $request->get('sortOrder');
            $column = $request->get('sortField');
            $query->orderBy($column, $order);
        }

        // Hitung total records
        $totalRecords = $query->count();

        // Pagination (default page size 10)
        $size = $request->get('size', 10);
        if ($size == 0) {
            $size = 10;
        }

        if ($request->has('page') && $request->has('size')) {
            $page   = $request->get('page', 1);
            $offset = ($page - 1) * $size;

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

        // Filtered records
        $filteredRecords = $query->count();

        // Ambil data dengan relasi
        $data = $query->with([
            'user',
            'debiture',
            'branch',
            'tujuanPenilaian',
            'nilaiPlafond',
            'penilaian.userPenilai' => function ($q) {
                $q->where('role', 'penilai')->with(['user', 'team.regions']);
            },
            'penilai',
            'approveSo',
            'approveEo',
            'approveDd',
            'authorization.approveSo',
            'authorization.approveEo',
            'authorization.approveDd'
        ])->get();



        // Hitung jumlah halaman
        $pageCount = ceil($totalRecords / $size);

        // Ambil current page
        $currentPage = max(1, $request->get('page', 1));

        // Return JSON response
        return response()->json([
            'draw'            => $request->get('draw'),
            'recordsTotal'    => $totalRecords,
            'recordsFiltered' => $filteredRecords,
            'pageCount'       => $pageCount,
            'page'            => $currentPage,
            'totalCount'      => $totalRecords,
            'data'            => $data,
        ]);
    }

    public function view_laporan(Request $request)
    {

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

        $permohonan = $this->surveyorController->getPermohonanJaminanId($id, $documentId, $jaminanId);
        $basicData =  $this->surveyorController->getCommonData();
        $provinces = Province::all();
        $inspeksi = Inspeksi::where('permohonan_id', $id)->where('dokument_id', $documentId)->first();
        $lpj = Penilai::where('permohonan_id', $id)
            ->where('dokument_id', $documentId)
            ->first();
        $penilai = $lpj;

        $forminspeksi = null;
        $lpjData = null;
        if ($inspeksi) {
            $forminspeksi = json_decode($inspeksi->data_form, true);
        }
        $nomorLaporan =   $this->penilaiController->generateNoLaporan($permohonan, $documentId, $lpj->type_penilai);


        $formFoto = $formPeta = $cities = $districts = $villages = $memo = null;

        if ($lpj) {
            $lpjData = json_decode($lpj->lpj, true);
            $resumeData = json_decode($lpj->resume, true);
            $callReport = json_decode($lpj->call_report, true);
            if (isset($lpj->memo)) {
                $memo = json_decode($lpj->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();
            }
            $rap = json_decode($lpj->rap, true);
        }

        if (empty($lpj->type_penilai)) {
            return redirect()->back()->with('error', 'Masih diproses');
        }

        $viewLaporan = $this->getViewLaporan($lpj->type_penilai);

        if (empty($viewLaporan)) {
            return redirect()->back()->with('error', 'Laporan belum dibuat');
        }

        return view('lpj::' . $viewLaporan, compact('permohonan', 'forminspeksi', 'basicData', 'inspeksi', 'lpjData', 'provinces', 'resumeData', 'rap', 'memo', 'cities', 'districts', 'villages', 'formFoto', 'formPeta', 'nomorLaporan', 'penilai', 'callReport'));
    }

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

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

            $validatedRequest = app(FormSurveyorRequest::class);
            $this->surveyorController->store($validatedRequest);

            $data = [
                'luas_tanah_penilai' => $request->input('luas_tanah_penilai'),
                'nilai_tanah_1' => $request->input('nilai_tanah_1'),
                'nilai_tanah_2' => $request->input('nilai_tanah_2'),
                'luas_bangunan_penilai' => $request->input('luas_bangunan_penilai'),
                'nilai_bangunan_1' => $request->input('nilai_bangunan_1'),
                'nilai_bangunan_2' => $request->input('nilai_bangunan_2'),
                'sarana_pelengkap_penilai' => $request->input('sarana_pelengkap_penilai'),
                'nilai_sarana_pelengkap_1' => $request->input('nilai_sarana_pelengkap_1'),
                'nilai_sarana_pelengkap_2' => $request->input('nilai_sarana_pelengkap_2'),
                'total_nilai_pasar_wajar' => $request->input('total_nilai_pasar_wajar'),
                'likuidasi' => $request->input('likuidasi'),
                'likuidasi_nilai_1' => $request->input('likuidasi_nilai_1'),
                'likuidasi_nilai_2' => $request->input('likuidasi_nilai_2'),
                'asuransi_luas_bangunan' => $request->input('asuransi_luas_bangunan'),
                'asuransi_nilai_1' => $request->input('asuransi_nilai_1'),
                'asuransi_nilai_2' => $request->input('asuransi_nilai_2'),
            ];

            // Update atau buat data baru
            Penilai::updateOrCreate(
                [
                    'permohonan_id' => $request->permohonanId,
                    'dokument_id' => $request->documentId,

                ],
                [
                    'lpj' => json_encode($data),
                ]
            );
            DB::commit();
            return response()->json([
                'success' => true,
                'message' => 'Berhasil Update Laporan penilai',
                'data' => $request->all(),
            ], 200);
        } catch (\Throwable $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => 'Terjadi kesalahan',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function revisiLaporan(Request $request, $id)
    {
        // dd($id);
        if ($request->dataHeader == 'Paparan' || $request->dataHeader == 'Freze SLA') {
            $authorization = Authorization::find($id);
            $permohonan = Permohonan::find($authorization->permohonan_id);
        } else {
            $permohonan = Permohonan::find($id);
            $userRole   = Auth::user()->roles[0]->name;
        }

        if ($permohonan->status === 'proses-paparan') {
            if ($authorization) {
                $authorization->delete();
            }

            $status = 'revisi-paparan';
        } elseif ($permohonan->status === 'request-freeze') {
            if ($authorization) {
                $authorization->delete();
            }

            $status = 'reject-freeze';
        } elseif ($permohonan->status === 'proses-laporan' && $userRole === 'senior-officer') {
            $status = 'revisi-laporan';
        } elseif ($permohonan->status === 'proses-laporan' && $userRole === 'EO Appraisal') {
            $permohonan->update([
                'approval_so'    => 0,
                'approval_so_at' => null,
            ]);
            $status = 'revisi-laporan';
        } elseif ($permohonan->status === 'proses-laporan' && $userRole === 'DD Appraisal') {
            $permohonan->update([
                'approval_so'    => 0,
                'approval_so_at' => null,
                'approval_eo'    => 0,
                'approval_eo_at' => null,

            ]);
            $status = 'revisi-laporan';
        } else {
            return response()->json([
                'success' => false,
                'message' => 'Tidak ada tindakan yang dapat dilakukan untuk status saat ini.',
            ], 400);
        }

        // Perbarui status dan informasi lainnya
        $permohonan->update([
            'status' => $status,
            'keterangan' => $request->keterangan,
            'submitted_at' => now(),
        ]);

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

}
