<?php

    namespace Modules\Lpj\Http\Controllers;

    use App\Http\Controllers\Controller;
    use Exception;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Auth;
    use Maatwebsite\Excel\Facades\Excel;
    use Modules\Lpj\Exports\LaporanAdminKreditExport;
    use Modules\Lpj\Models\LaporanAdminKredit;
    use Modules\Lpj\Models\Permohonan;

    class LaporanAdminKreditController extends Controller
    {
        public $user;

        /**
         * Display a listing of the resource.
         */
        public function index()
        {
            $permohonan = Permohonan::where(['status' => 'done'])->get();
            foreach ($permohonan as $_permohonan) {
                $npw = 0;
                if (isset($_permohonan->penilai->lpj)) {
                    $npw = json_decode($_permohonan->penilai->lpj, true);
                    $npw = $npw['total_nilai_pasar_wajar'] ?? 0;
                }

                $dataAdk = [
                    '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 (!empty($detail->dokumen_nomor) && is_array($detail->dokumen_nomor))
                                ? ($detail->jenisLegalitasJaminan->name ?? '') . "\n" . implode(', ', $detail->dokumen_nomor)
                                : null;
                        });
                    })->filter()->unique()->implode(', '),
                ];

                LaporanAdminKredit::updateOrCreate([
                    'debiture_id' => $_permohonan->debiture_id,
                ], $dataAdk);
            }


            $laporans = LaporanAdminKredit::with('debiture')->paginate(10);
            return view('lpj::laporan_admin_kredit.index', compact('laporans'));
        }

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

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

            if ($request->has('tanggal_awal') && $request->has('tanggal_akhir')) {
                $query->whereBetween('tanggal_kunjungan', [$request->tanggal_awal, $request->tanggal_akhir]);
            }

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

                if (isset($search_->search)) {
                    $query->where(function ($q) use ($search_) {
                        $q->where('kode_register_t24', 'LIKE', '%' . $search_->search . '%')
                          ->orWhere('jenis_agunan', 'LIKE', '%' . $search_->search . '%')
                          ->orWhere('nama_pemilik', 'LIKE', '%' . $search_->search . '%')
                          ->orWhereHas('debiture', function ($query) use ($search_) {
                              $query->where('name', 'LIKE', '%' . $search_->search . '%');
                          });
                    });
                }

                if (isset($search_->tanggal_awal) && isset($search_->tanggal_akhir)) {
                    $query->whereBetween('tanggal_kunjungan', [$search_->tanggal_awal, $search_->tanggal_akhir]);
                }
            }

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

            // 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()
        {
            return Excel::download(new LaporanAdminKreditExport, 'laporan_admin_kredit.xlsx');
        }

        public function edit($id)
        {
            $laporanAdminKredit = LaporanAdminKredit::with('debiture.branch')->find($id);
            return view('lpj::laporan_admin_kredit.form', compact('laporanAdminKredit'));
        }

        public function update(Request $request, $id)
        {
            $request->validate([
                'kode_register_t24' => 'nullable',
                'cif' => 'required',
                'keterangan' => 'nullable|string',
                'kolektibilitas' => 'nullable|string|in:1,2,3,4,5',
            ]);

            try {
                $laporanAdminKredit = LaporanAdminKredit::find($id);

                // Update only the editable fields
                $laporanAdminKredit->update([
                    'kode_register_t24' => $request->kode_register_t24,
                    'keterangan' => $request->keterangan,
                    'kolektibilitas' => $request->kolektibilitas,
                    'updated_by' => Auth::id(),
                ]);

                // Update CIF in the debiture table if needed
                if ($laporanAdminKredit->debiture) {
                    $laporanAdminKredit->debiture->update([
                        'cif' => $request->cif,
                        'updated_by' => Auth::id(),
                    ]);
                }

                return redirect()
                    ->route('admin-kredit.laporan.index')
                    ->with('success', 'Laporan Admin Kredit updated successfully');
            } catch (Exception $e) {
                return redirect()
                    ->route('admin-kredit.laporan.edit', $id)
                    ->with('error', 'Failed to update Laporan Admin Kredit');
            }
        }
    }
