<?php

namespace App\Http\Controllers\Instansi;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Absensi;
use App\Models\Karyawan;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;

class RekapController extends Controller
{
    public function index(Request $request)
{
    $instansiId = Auth::user()->instansi_id;

    $bulan = (int) $request->input('bulan', now()->month);
    $tahun = (int) $request->input('tahun', now()->year);
    $bln   = $bulan; // alias agar compact tetap konsisten

    $karyawanList = Karyawan::with(['user', 'jabatan'])
        ->where('instansi_id', $instansiId)
        ->get();

    $hariKerja  = 0;
    $start      = Carbon::createFromDate($tahun, $bln, 1);
    $end        = $start->copy()->endOfMonth();
    $batasAkhir = (now()->year === $tahun && now()->month === $bln) ? now() : $end;

    for ($d = $start->copy(); $d->lte($batasAkhir); $d->addDay()) {
        if ($d->isWeekday()) $hariKerja++;
    }

    $absensiData = Absensi::whereHas('karyawan', fn($q) => $q->where('instansi_id', $instansiId))
        ->whereYear('tanggal', $tahun)
        ->whereMonth('tanggal', $bln)
        ->get()
        ->groupBy('karyawan_id');

    $rekap = $karyawanList->map(function ($kar) use ($absensiData, $hariKerja) {
        $data       = $absensiData->get($kar->id, collect());
        $hadir      = $data->whereNotNull('jam_masuk')->count();
        $terlambat  = $data->where('status_waktu', 'terlambat')->count();
        $tepat      = $data->where('status_waktu', 'tepat_waktu')->count();
        $pulangAwal = $data->whereNotNull('jam_pulang')->where('status_pulang', 'lebih_awal')->count();
        $sakit      = $data->where('status', 'sakit')->count();
        $alpha      = max(0, $hariKerja - $hadir - $sakit);
        $pctHadir   = $hariKerja > 0 ? round(($hadir / $hariKerja) * 100) : 0;

        return [
            'id'          => $kar->id,
            'nama'        => $kar->user->name ?? $kar->nama ?? '-',
            'nip'         => $kar->nip ?? '-',
            'jabatan'     => $kar->jabatan->nama_jabatan ?? $kar->jabatan->nama ?? '-',
            'hadir'       => $hadir,
            'terlambat'   => $terlambat,
            'tepat'       => $tepat,
            'sakit'       => $sakit,
            'alpha'       => $alpha,
            'pulang_awal' => $pulangAwal,
            'pct'         => $pctHadir,
        ];
    });

    $instansi     = Auth::user()->instansi;
    $periodeLabel = Carbon::createFromDate($tahun, $bulan, 1)->isoFormat('MMMM YYYY');

    return view('instansi.rekap.index', compact(
        'rekap', 'bulan', 'tahun', 'periodeLabel', 'hariKerja',
        'karyawanList', 'instansi', 'bln'
    ));
}
}