<?php

namespace Modules\Lpj\Services;
use Modules\Lpj\Models\TeamsUsers;
use Modules\Lpj\Models\Teams;
use Modules\Lpj\Models\Debiture;
use Modules\Lpj\Models\Permohonan;
use Modules\Lpj\Models\Penilaian;
use Modules\Lpj\Models\StatusPermohonan;
use Carbon\Carbon;
class LaporanMonitoringSoService
{

    public function progresPengerjaanLaporan($user){

        // Inisialisasi regionId dan teamId
        $regionId = $teamId = null;

        if ($user->roles->pluck('name')->contains('senior-officer')) {
            $userTeam = TeamsUsers::with('team')->firstWhere('user_id', $user->id);
            $regionId = $userTeam?->team->regions_id;
            $teamId = $userTeam?->teams_id;
        }


        $teamsActivity = TeamsUsers::with(['user', 'team', 'team.regions', 'user.roles'])
            ->whereHas('team', function ($q) use ($regionId, $teamId) {
                $q->when($regionId, fn ($q) => $q->where('regions_id', $regionId))
                  ->when($teamId, fn ($q) => $q->where('id', $teamId));
            })
            ->where('user_id', '!=', $user->id)
            ->whereHas('user.roles', fn ($q) => $q->whereIn('name', ['surveyor', 'surveyor-penilai']))
            ->get();

        $teamId = is_array($teamId) ? $teamId : [$teamId];

        $teamPenilai = Teams::with(['regions', 'teamsUsers', 'teamsUsers.user'])->whereNotIn(
            'id',
            $teamId
        )->get();

        return [
            'teamsActivity' => $teamsActivity,
            'teamPenilai' => $teamPenilai,
        ];
    }


    public function showDetailsPermohonan($request,$id)
    {
         $query = Penilaian::with([
            'permohonan',
            'permohonan.debiture',
            'permohonan.tujuanPenilaian',
            'permohonan.debiture.documents.jenisJaminan',
            'userPenilai' => function ($query) use ($id) {
                $query->where('user_id', $id);
            },
            'permohonan.penilai',
            'permohonan.approveEo',
            'permohonan.approveDd',
            'permohonan.approveSo',

        ])
        ->whereHas('userPenilai', function ($q) use ($id) {
            $q->where('user_id', $id);
        })
        ->whereHas('permohonan', function ($q) {
            $q->whereIn('status', [
                'assign',
                'survey-completed',
                'proses-laporan',
                'paparan',
                'proses-paparan',
                'revisi-laporan',
                'revisi-paparan',
                'survey',
                'proses-survey',
                'request-reschedule',
                'reschedule',
                'rejected-reschedule',
                'approved-reschedule',
                'revisi-survey',
                'revisi-pembayaran'
            ]);
        });



        // Filter pencarian
        if ($request->has('search') && !empty($request->get('search'))) {
            $search = $request->get('search');
            $query->where(function ($q) use ($search) {
                $q->where('nomor_registrasi', 'LIKE', "%$search%")
                  ->orWhere('status', 'LIKE', "%$search%");
            });
        }

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

        // Hitung total records
        $totalRecords = $query->count();

        // Pagination
        $size = $request->get('size', 10);
        $page = $request->get('page', 1);
        $offset = ($page - 1) * $size;

        // Ambil data dengan pagination
        $data = $query->skip($offset)->take($size)->get();

        $data = $data->map(function ($item) {
            $jeniAsset = null;
            $statusPembayaran = trim(strtolower($item->permohonan->status_bayar ?? ''));
            $tujuanPenilaian = $item->permohonan->tujuanPenilaian->name ?? null;
            $plafond = $item->permohonan->nilaiPlafond->name ?? null;

            $now = Carbon::now();
            $type_report = $item->permohonan->penilai->type ?? "";

            $hari = $hariPaparan = 0;

            if ($type_report == "sederhana") {
                $hari = 2;
                $item->paparan = 'Tidak Ada';
            } else {
                if ($plafond == '< 2M') {
                    $item->paparan = 'Tidak Ada';
                    $hari = 3;
                } elseif ($plafond == '2 M - 5 M') {
                    $hari = 3;
                    $hariPaparan = 2;
                } else {
                    $hari = 5;
                    $hariPaparan = 3;
                }
            }

            if ($tujuanPenilaian == 'RAP') {
                $hari = 2;
                $hariPaparan = 2;
            }


            if ($item->permohonan && $item->permohonan->debiture) {
                $jeniAsset = $item->permohonan->debiture->documents->first() ?? null;
            }

            /*$hariTambahan = 0;

            if ($tujuanPenilaian == 'RAP') {
                $hariTambahan = 2;
            } else {
                if ($statusPembayaran == 'sudah_bayar') {
                    $hariTambahan = 1; // H+1 untuk yang sudah bayar
                } else {
                    $hariTambahan = 2; // H+2 untuk yang belum bayar
                }
            }*/

            $tanggalMulai = $item->waktu_penilaian;

            if ($tanggalMulai) {
                if (!$tanggalMulai instanceof Carbon) {
                    $tanggalMulai = Carbon::parse($tanggalMulai);
                }
                $hariKerjaBerikutnya = hitungHariKerja($tanggalMulai->toDateString(), $tanggalMulai->copy()->addDays(1));
                $hariKerjaBerikutnya = max($hariKerjaBerikutnya, 1);
                $tanggalMulai = $tanggalMulai->copy()->addDays($hariKerjaBerikutnya);

                // Konversi string tanggal ke objek Carbon jika belum
                if (!$tanggalMulai instanceof Carbon) {
                    $tanggalMulai = Carbon::parse($tanggalMulai);
                }

                // Hitung tanggal selesai berdasarkan hari tambahan
                $tanggalSelesai = $tanggalMulai->copy()->addDays($hari);
                $tanggalPaparan = $tanggalMulai->copy()->addDays($hariPaparan);

                // Hitung hari kerja
                $hariKerja = hitungHariKerja($tanggalMulai->toDateString(), $tanggalSelesai->toDateString());
                $hariKerja = max($hariKerja, $hari);

                $hariKerjaPaparan = hitungHariKerja($tanggalMulai->toDateString(), $tanggalPaparan->toDateString());
                $hariKerjaPaparan = max($hariKerjaPaparan, $hariPaparan);

                // Set due date SLA
                $dueDateSla = $tanggalMulai->copy()->addDays($hariKerja);
                $dueDateSlaPaparan = $tanggalMulai->copy()->addDays($hariKerjaPaparan);

                // Cek apakah sudah melewati due date
                /*if ($now->greaterThan($dueDateSla)) {
                    $item->due_date_sla = null;
                } else {
                    $item->due_date_sla = $dueDateSla->toDateString();
                }*/

                $item->due_date_sla = $dueDateSla->toDateString();
                $item->paparan = $dueDateSlaPaparan->toDateString();
            } else {
                $item->due_date_sla = null;
                $item->paparan = null;

            }

            return $item;
        });

        $filteredRecords = $data->count();
        $pageCount = ceil($totalRecords / $size);

        // Return data dalam bentuk JSON
        return response()->json([
            'draw'            => $request->get('draw'),
            'recordsTotal'    => $totalRecords,
            'recordsFiltered' => $filteredRecords,
            'pageCount'       => $pageCount,
            'page'            => $page,
            'totalCount'      => $totalRecords,
            'data'            => $data
        ]);
    }
}
