<?php

namespace Modules\Lpj\Services;

use Modules\Lpj\Models\Permohonan;
use Modules\Lpj\Models\Penilaian;
use Illuminate\Http\Request;
use Carbon\Carbon;

class LaporanSLAPenilaiService
{
    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()
                ]);
            }


            if (isset($search->penilai_id) && !empty($search->penilai_id)) {
                $query->whereHas('penilaian._user_penilai.userPenilaiTeam', function ($q) use ($search) {
                    $q->where('user_id', $search->penilai_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(['documents','debiture.branch'])->get();

        $data = $data->map(function ($permohonan) {

            $tgl_kunjungan = $permohonan->penilaian?->tanggal_kunjungan;
            $tgl_otorisator = $permohonan->approval_dd_at ?? $permohonan->approval_eo_at ?? $permohonan->approval_so_at;
            $jangkaWaktu = $this->hitungTotalJangkaWaktuSla($tgl_kunjungan, $tgl_otorisator);



            return [
                'id'                => $permohonan->id,
                'nomor_registrasi'  => $permohonan->nomor_registrasi,
                'tanggal_permohonan' => $permohonan->tanggal_permohonan,
                'branch'            => $permohonan->debiture?->branch?->name,
                'name'              => $permohonan->debiture?->name,
                'pemohon'           => $permohonan->creator?->name,
                'tujuan_penilaian'  => $permohonan->tujuanPenilaian?->name,
                'tanggal_laporan'   => $permohonan->approval_dd_at ?? $permohonan->approval_eo_at ?? '',
                'tanggal_approval'    => $permohonan->approval_dd_at ?? $permohonan->approval_eo_at ?? '',
                'tanggal_kunjungan'    => $permohonan->penilaian?->tanggal_kunjungan ?? '',
                'nama_penilai'      => $permohonan->penilaian?->_user_penilai?->userPenilaiTeam?->name,
                'jangka_waktu' => $jangkaWaktu,
                'keterangan' => $permohonan->keterangan
            ];
        });

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

    private function hitungTotalJangkaWaktuSla($tgl_kunjungan,$tgl_otorisator){
            $countHariKerja = hitungHariKerja($tgl_kunjungan, $tgl_otorisator);
            return $countHariKerja;
    }
}
