<?php

    namespace Modules\Lpj\Http\Controllers;

    use App\Http\Controllers\Controller;
    use Carbon\Carbon;
    use Exception;
    use Illuminate\Http\JsonResponse;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Auth;
    use Illuminate\Support\Facades\DB;
    use Illuminate\Support\Facades\Storage;
    use Illuminate\Support\Facades\Validator;
    use Maatwebsite\Excel\Facades\Excel;
    use Modules\Lpj\Models\PenawaranTender;
    use Modules\Lpj\Models\Permohonan;
    use Modules\Lpj\Models\Regions;

    // use Modules\Location\Models\City;
    // use Modules\Location\Models\District;
    // use Modules\Location\Models\Province;
    // use Modules\Location\Models\Village;
    // use Modules\Lpj\Exports\DebitureExport;
    // use Modules\Lpj\Http\Requests\DebitureRequest;
    // use Modules\Lpj\Http\Requests\DokumenJaminanRequest;
    // use Modules\Lpj\Models\Branch;
    // use Modules\Lpj\Models\Debiture;
    // use Modules\Lpj\Models\DokumenJaminan;
    // use Modules\Lpj\Models\JenisJaminan;
    // use Modules\Lpj\Models\JenisLegalitasJaminan;
    // use Modules\Lpj\Models\PemilikJaminan;

    class RegistrasiFinalController extends Controller
    {
        public $user;

        public function index()
        {
            return view('lpj::registrasifinal.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 =PenawaranTender::query()
                                   ->select('penawaran.*', 'tujuan_penilaian_kjpp.name as tujuan_penilaian_kjpp_name')
                                   ->leftJoin('tujuan_penilaian_kjpp', 'tujuan_penilaian_kjpp.id','=','penawaran.tujuan_penilaian_kjpp_id')
                                   ->where('penawaran.status','=','registrasi-final')
                                   ->withCount('penawarandetails');

            // 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->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();
            $data = $query->with(['permohonan.debiture'])->get();
            // dd($data);
            $i = 0;
            foreach ($data as $obj) {
                if ($obj->tanggal_penilaian_sebelumnya) {
                    $data[$i]->tanggal_penilaian_sebelumnya = Carbon::parse($obj->tanggal_penilaian_sebelumnya)->format(
                        'd F Y H:i:s',
                    );
                }

                if ($obj->biaya_kjpp_sebelumnya) {
                    $data[$i]->biaya_kjpp_sebelumnya = formatRupiah($obj->biaya_kjpp_sebelumnya);
                }

                // date_range
                if ($obj->start_date && $obj->end_date) {
                    $data[$i]->date_range = Carbon::parse($obj->start_date)->format('d M Y') . ' - ' . Carbon::parse(
                            $obj->end_date,
                        )->format('d M Y');
                }

                $i++;
            }


            // 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 show($id)
        {
            $permohonan = Permohonan::find($id);
            $document = PenawaranTender::where('nomor_registrasi','=',$permohonan->nomor_registrasi)->first();
            if ($document) {
                $pdfSPK_path         = Storage::url($document->spk_dokumen_path);
                $permohonan->pdfSPK_path = '| <a download href="' . $pdfSPK_path . '" class="badge badge-sm badge-outline" target="_blank">Dokumen SPK.pdf &nbsp;&nbsp;<i class="ki-filled ki-cloud-download"></i></a>';
            }

            return view('lpj::registrasifinal.show', compact('id', 'permohonan'));
        }

        public function edit($id)
        {
            $doc_pdf='';
            $permohonan = Permohonan::find($id);
            $document = PenawaranTender::where('nomor_registrasi','=',$permohonan->nomor_registrasi)->first();
            if ($document) {
                $pdfSPK_path         = Storage::url($document->spk_dokumen_path);
                $doc_pdf = '<a download href="' . $pdfSPK_path . '" class="badge badge-sm badge-outline" target="_blank">Dokumen SPK.pdf &nbsp;&nbsp;<i class="ki-filled ki-cloud-download"></i></a>';
            }

            return view('lpj::registrasifinal.edit', compact('id','doc_pdf'));
        }

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

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

                if ($datas) {
                    $penawaran = null;
                    $regions   = null;
                    $regions   = Regions::pluck('name', 'id');
                    $penawaran = PenawaranTender::where('nomor_registrasi', '=', $datas->nomor_registrasi)->first();

                    $penawaranString = "";
                    if ($penawaran->status) {
                        $penawaranString   = convertSlug($penawaran->status);
                        $penawaran->status = $penawaranString;
                    }

                    if ($datas->dokumen) {
                        $pdfSPK_path    = Storage::url($datas->dokumen);
                        $datas->dokumen = $pdfSPK_path;
                    }

                    $data['status']                     = 'success';
                    $data['regions']                    = $regions;
                    $data['penawaran']                  = $penawaran;
                    $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 update(Request $request, $id)
        : JsonResponse {
            // init
            $data           = [];
            $dataPermohonan = [];
            $dataPenawaran  = [];

            if (request()->ajax()) {
                $validator = RegistrasiFinalController::rulesEditnya($request, $id);

                if ($validator['fails']) {
                    $data['message'] = $validator['errors'];
                    $data['status']  = 'error';
                } else {
                    DB::beginTransaction();
                    try {
                        // update table permohonan => status (registrasi-final), region_id, keterangan, authorized_at, authorized_status, authorized_by
                        // update table penawaran  => status (registrasi-final)
                        $dataPermohonan = [
                            'status'            => 'registrasi-final',
                            'region_id'         => $request->region,
                            'keterangan'        => $request->catatan,
                            'authorized_at'     => now(),
                            'authorized_status' => 1,
                            'authorized_by'     => Auth::id(),
                        ];

                        $dataPenawaran = ['status' => 'registrasi-final'];


                        $permohonan = Permohonan::find($id);
                        $penawaran  = PenawaranTender::where('nomor_registrasi', '=', $permohonan->nomor_registrasi)
                                                     ->first();

                        $permohonan->update($dataPermohonan);
                        $penawaran->update($dataPenawaran);
                        //
                        DB::commit();

                        $data['status']                     = 'success';
                        $data['message']['message_success'] = ['Regitrasi Final ' . $permohonan->nomor_registrasi . ' successfully'];
                    } catch (Exception $e) {
                        DB::rollBack();
                        $data['status']                       = 'error';
                        $data['message']['message_try_catch'] = ['Regitrasi Final ' . $permohonan->nomor_registrasi . ' failed.'];
                    }
                }
            } else {
                $data['status']                  = 'error';
                $data['message']['message_ajax'] = ["no ajax request"];
            }

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

        public function rulesEditnya($request, $id)
        {
            $validate_catatan = '';

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

            $messageIt = [
                'region.required'  => 'Silahkan pilih Region',
                'catatan.required' => 'Silahkan isi Catatan',
            ];

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

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

            return $data;
        }

    }
