<?php

namespace App\Http\Controllers\Karyawan;

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

class HistoryController extends Controller
{
    public function index(Request $request)
    {
        $karyawan = Auth::user()->karyawan;

        $dari   = $request->dari   ? Carbon::parse($request->dari)->startOfDay()   : now()->startOfMonth();
        $sampai = $request->sampai ? Carbon::parse($request->sampai)->endOfDay()   : now()->endOfDay();

        $absensis = Absensi::where('karyawan_id', $karyawan->id)
            ->whereBetween('tanggal', [$dari, $sampai])
            ->orderByDesc('tanggal')
            ->get();

        // Hitung summary
        $summary = [
            'hadir'     => $absensis->where('jam_masuk', '!=', null)->where('status_waktu', 'tepat_waktu')->count(),
            'terlambat' => $absensis->where('status_waktu', 'terlambat')->count(),
            'sakit'     => $absensis->where('status', 'sakit')->count(),
            'izin'      => $absensis->where('status', 'izin')->count(),
        ];

        // Hadir = semua yang punya jam_masuk (termasuk terlambat)
        $summary['hadir'] = $absensis->where('jam_masuk', '!=', null)->count();

        return view('karyawan.history', compact('absensis', 'summary'));
    }
}