<?php

namespace Modules\Lpj\Services;
use Modules\Lpj\Models\Permohonan;
use Illuminate\Http\Request;
class LaporanDebitureService
{
    public function dataForDatatables(Request $request)
    {

        // Retrieve data from the database
        $query = Permohonan::query();
        $query = $query->where('status', 'done');

        // Apply search filter if provided
        if ($request->has('search') && !empty($request->get('search'))) {
            $search = json_decode($request->get('search'));

            if (isset($search->start_date) || isset($search->end_date)) {
                $query->whereBetween('tanggal_permohonan', [
                    $search->start_date ?? '1900-01-01',
                    $search->end_date ?? now()->toDateString()
                ]);
            }

            // Filter by branch if provided
            if (isset($search->debiture_id) && !empty($search->debiture_id)) {
                $query->where('debiture_id', $search->debiture_id);
            }

            if (isset($search->search)) {

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

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

        // Get the total count of records
        $totalRecords = $query->count();

        // Apply pagination if provided
        if ($request->has('page') && $request->has('size')) {
            $page   = $request->get('page');
            $size   = $request->get('size');
            $offset = ($page - 1) * $size; // Calculate the offset

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

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

        // Get the data for the current page
        $data = $query->with(['debiture.branch'])->get();

        $data = $data->map(function ($permohonan) {
            $luas_tanah      = 0;
            $luas_bangunan   = 0;
            $nilai_tanah     = 0;
            $nilai_bangunan  = 0;
            $npw             = 0;
            $nilai_liquidasi = 0;

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

                $luas_tanah    = $lpj['luas_tanah'] ?? 0;
                $luas_bangunan = $lpj['luas_bangunan'] ?? 0;
                // Calculate nilai_tanah dynamically by looking for all keys that start with 'nilai_tanah_'
                $nilai_tanah = str_replace('.', '', $lpj['nilai_tanah_2'] ?? 0);

                $nilai_bangunan  = str_replace('.', '', $lpj['nilai_bangunan_2'] ?? 0);
                $nilai_liquidasi = str_replace('.', '', $lpj['likuidasi_nilai_2'] ?? 0);
            }

            return [
                'id'                        => $permohonan->id,
                'nomor_registrasi'          => $permohonan->nomor_registrasi,
                'jenis_penilaian'           => $permohonan->jenisPenilaian?->name,
                'tujuan_penilaian'          => $permohonan->tujuanPenilaian?->name,
                'jenis_fasilitas_kredit'    => $permohonan->jenisFasilitasKredit?->name,
                'branch'                    => $permohonan->debiture->branch?->name,
                'pemohon'                   => $permohonan->creator?->name,
                'cif'                       => $permohonan->debiture->cif,
                'name'                      => $permohonan->debiture?->name,
                'jenis_agunan'              => $permohonan->documents?->pluck('jenisJaminan.name')
                                                                     ->unique()
                                                                     ->implode(', '),
                'alamat_agunan'             => $permohonan->documents?->map(function ($document) {
                    return formatAlamat($document);
                })->unique()->implode(', '),
                'bukti_kepemilikan' => (function () use ($permohonan) {
                    $legalitasItems = $permohonan->documents?->flatMap(function ($document) {
                        return $document->detail->map(function ($detail) {
                            // Jika tidak ada jenis legalitas jaminan, lewati
                            if (empty($detail->jenisLegalitasJaminan)) {
                                return null;
                            }

                            // Hanya tampilkan detail yang memiliki dokumen_jaminan
                            if (empty($detail->dokumen_jaminan)) {
                                return null;
                            }

                            // Tampilkan nama legalitas jaminan saja
                            return $detail->jenisLegalitasJaminan->name ?? '';
                        });
                    })->filter()->unique()->values()->toArray();

                    // Buat daftar bernomor
                    $result = '';
                    foreach ($legalitasItems as $index => $item) {
                        $result .= ($index + 1) . '. ' . $item . "\n";
                    }

                    return $result;
                })(),
                'nama_pemilik'              => $permohonan->documents?->pluck('pemilik.name')
                                                                     ->unique()
                                                                     ->implode(', '),
                'luas_tanah'                => $luas_tanah . ' m²',
                'nilai_tanah'               => formatRupiah($nilai_tanah, 2),
                'luas_bangunan'             => $luas_bangunan . ' m²',
                'nilai_bangunan'            => formatRupiah($nilai_bangunan, 2),
                'nilai_njop'                => formatRupiah($permohonan->nilai_njop, 2),
                'nilai_pasar_wajar'         => formatRupiah($npw, 2),
                'nilai_likuidasi'           => formatRupiah($nilai_liquidasi, 2),
                'tanggal_documen_diterima'  => $permohonan->documents?->map(function ($document) {
                    return $document->created_at->format('d-m-Y');
                }),
                'tanggal_spk'               => '',
                'nomor_spk'                 => '',
                'tanggal_rencana_kunjunagn' => '',
                'tanggal_kunjungan'         => '',
                'taggal_delivered'          => '',
                'jangka_waktu_sla'          => '',
                'nama_penilai'              => $permohonan->penilaian?->_user_penilai?->userPenilaiTeam?->name,
                'nama_team_leader'          => $permohonan->penilaian?->teams,
                'saran'                     => '',
                'catatan'                   => '',


                'tanggal_permohonan' => $permohonan->tanggal_permohonan,
                'tanggal_laporan'    => $permohonan->approval_dd_at ?? $permohonan->approval_eo_at ?? '',
                'tanggal_review'     => $permohonan->penilaian?->tanggal_kunjungan ?? '',
            ];
        });

        // 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,
        ]);
    }
}
