<?php

namespace App\Http\Controllers\Admin\HR;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\HR\AttendanceRequest;
use App\Models\Attendance;
use App\Services\Admin\HR\AttendanceService;
use App\Settings\HRSettings;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class AttendanceController extends Controller
{
    public function __construct(
        private readonly AttendanceService $service
    ) {}

    public function index(Request $request): Response
    {
        $year = $request->integer('year', now()->year);
        $month = $request->integer('month', now()->month);

        $hrSettings = app(HRSettings::class);

        return Inertia::render('admin/hr/attendance/index', [
            'attendances' => $this->service->getByMonth($year, $month),
            'todayAttendance' => $this->service->getToday(),
            'currentYear' => $year,
            'currentMonth' => $month,
            'monthStats' => $this->service->getMonthStats($year, $month),
            'hrSettings' => [
                'scheduled_check_in_time' => $hrSettings->scheduled_check_in_time,
                'scheduled_check_out_time' => $hrSettings->scheduled_check_out_time,
            ],
        ]);
    }

    public function store(AttendanceRequest $request): RedirectResponse
    {
        return $this->handleAction(
            fn () => $this->service->checkIn($request->validated()),
            'Berhasil check-in.',
            'admin.hr.attendances.index'
        );
    }

    public function update(AttendanceRequest $request, Attendance $attendance): RedirectResponse
    {
        return $this->handleAction(
            fn () => $this->service->checkOut($attendance, $request->validated()),
            'Berhasil check-out.',
            'admin.hr.attendances.index'
        );
    }

    public function byDate(Request $request): ?array
    {
        $date = $request->query('date', now()->toDateString());

        return $this->service->getByDate($date);
    }
}
