<?php

    namespace Modules\Lpj\Http\Controllers;

    use App\Http\Controllers\Controller;
    use Exception;
    use Illuminate\Http\JsonResponse;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Auth;
    use Illuminate\Support\Facades\Validator;
    use Maatwebsite\Excel\Facades\Excel;
    use Modules\Lpj\Models\Debiture;
    use Modules\Lpj\Models\DokumenJaminan;
    use Modules\Lpj\Models\JenisPenilaian;
    use Modules\Lpj\Models\Penilai;
    use Modules\Lpj\Models\Permohonan;
    use Modules\Lpj\Models\Regions;

    class RegistrasiController extends Controller
    {
        public $user;

        public function index()
        {
            return view('lpj::registrasi.index');
        }

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

            // Retrieve data from the database
            $query = Permohonan::query()
                               ->whereIn('status', ['preregister', 'revisi']);


            // Apply search filter if provided
            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 . '%');
                });
            }

            // 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(['user', 'debiture', 'branch', 'tujuanPenilaian'])->get();

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

            // Calculate the current page number
            $currentPage = 0 + 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 edit($id)
        {
            return view('lpj::registrasi.edit', compact('id'));
        }

        public function setData(Request $request)
        : JsonResponse
        {
            $data  = [];
            $datas = [];

            if (request()->ajax()) {
                $id    = $request->id;
                $datas = Permohonan::find($id);

                if ($datas) {
                    $jenisPenilaians = null;
                    $regions         = null;
                    $regions         = Regions::pluck('name', 'id');
                    $jenisPenilaians = JenisPenilaian::pluck('name', 'id');

                    $data['status']                      = 'success';
                    $data['regions']                     = $regions;
                    $data['jenisPenilaians']             = $jenisPenilaians;
                    $data['datas']                       = $datas;
                    $data['message'] ['message_success'] = ["data successfully found"];
                } else {
                    $data['status']                   = 'error';
                    $data['datas']                    = null;
                    $data['message'] ['message_data'] = ["data not found"];
                }
            } else {
                $data['status']                  = 'error';
                $data['message']['message_ajax'] = ["no ajax request"];
            }

            return response()->json($data);
        }

        public function show($id)
        {
            $permohonan = Permohonan::find($id);
            $debitur    = Debiture::find($permohonan->debiture_id);
            $documents  = DokumenJaminan::with('pemilik', 'detail')->where('permohonan_id', $id)->get();
            return view('lpj::registrasi.show', compact('id', 'permohonan', 'documents', 'debitur'));
        }

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

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

                return redirect()->route('registrasi.index')->with('success', 'Submit Revision successfully');
            } catch (Exception $e) {
                return redirect()
                    ->route('registrasi.index')
                    ->with('error', 'Failed to create permohonan' . $e->getMessage());

            }
        }

        public function update(Request $request, $id)
        : JsonResponse
        {
            // init
            $data     = [];
            $dataku   = [];
            $tindakan = null;
            if (request()->ajax()) {
                $validator = RegistrasiController::rulesEditnya($request, $id);

                if ($validator['fails']) {
                    $data['message'] = $validator['errors'];
                    $data['status']  = 'error';
                } else {
                    try {
                        $tindakan = $request->tindakan;
                        $dataku   = [
                            'registrasi_by' => Auth::id(),
                            'registrasi_at' => now(),
                        ];

                        if ($tindakan == 0) {
                            $dataku['jenis_penilaian_id'] = $request->jenis_penilaian;
                            $dataku['region_id']          = $request->region;
                            $dataku['status']             = 'registered';
                            if ($request->catatan2) {
                                $dataku['registrasi_catatan'] = $request->catatan2;
                            }
                        } else {
                            $dataku['registrasi_catatan'] = $request->catatan;
                            $dataku['status']             = 'revisi';
                        }

                        $data['dataku'] = $dataku;

                        $modal = Permohonan::find($id);

                        $modal->update($dataku);

                        if ($modal && $request->jenis_laporan) {
                            foreach ($modal->documents as $document) {
                                Penilai::updateOrCreate(
                                    [
                                        'permohonan_id' => $id,
                                        'dokument_id'   => $document->id
                                    ],
                                    ['type' => $request->jenis_laporan]
                                );
                            }
                        }
                        //
                        $data['status']                      = 'success';
                        $data['message'] ['message_success'] = ['Regitrasi ' . $modal->nomor_registrasi . ' successfully'];
                    } catch (Exception $e) {
                        $data['status']                        = 'error';
                        $data['message'] ['message_try_catch'] = ['Regitrasi updated failed.'];
                    }
                }
            } else {
                $data['status']                   = 'error';
                $data['message'] ['message_ajax'] = ["no ajax request"];
            }

            return response()->json($data);
        }

        public function rulesEditnya($request, $id)
        {
            $tindakan         = null;
            $jenis_penilaian  = null;
            $validate_catatan = '';
            $tindakan         = $request->tindakan;
            $jenis_penilaian  = $request->jenis_penilaian;

            $validateIt = [
                // 'name' diambil dari definisi parameter yang di kirim pada POST Data
                'tindakan' => 'required',
            ];

            $messageIt = [
                'tindakan.required' => 'Silahkan pilih Tindakan',
            ];

            if ($tindakan == 0) {
                $validateIt['jenis_penilaian']          = ['required'];
                $messageIt ['jenis_penilaian.required'] = 'Silahkan pilih Jenis Penilaian';

                // INTERNAL
                if (1 == $jenis_penilaian) {
                    $validateIt['region']          = ['required'];
                    $messageIt ['region.required'] = 'Silahkan pilih Region';
                }
            } else if ($tindakan == 1) {
                $validateIt['catatan']          = ['required'];
                $messageIt ['catatan.required'] = 'Silahkan isi Catatan';
            }

            $validator = Validator::make($request->all(), $validateIt, $messageIt);

            $data['fails']  = $validator->fails();
            $data['errors'] = $validator->errors();

            return $data;
        }
    }
