<?php

namespace App\Services;

use App\Models\Attendance;
use App\Models\SystemSetting;
use Carbon\Carbon;

class AttendanceService
{
    /**
     * Determine if a check-in is late and by how many minutes.
     */
    public function calculateLateStatus(Carbon $checkInTime)
    {
        $officeStartTime = SystemSetting::getValue('office_start_time', '09:00');
        $thresholdMinutes = (int) SystemSetting::getValue('late_threshold_minutes', '15');
        
        $officialStart = Carbon::parse($checkInTime->format('Y-m-d') . ' ' . $officeStartTime);
        $gracePeriod = $officialStart->copy()->addMinutes($thresholdMinutes);

        $isLate = $checkInTime->greaterThan($gracePeriod);
        $lateMinutes = $isLate ? $officialStart->diffInMinutes($checkInTime) : 0;

        return [
            'is_late' => $isLate,
            'late_minutes' => $lateMinutes
        ];
    }

    /**
     * Check if a day should be considered a half-day based on total work hours.
     */
    public function isHalfDay(Attendance $attendance)
    {
        $halfDayThreshold = (int) SystemSetting::getValue('half_day_threshold_hours', '4');
        $workHours = $attendance->total_work_minutes / 60;

        return $workHours < $halfDayThreshold && $workHours > 0;
    }
}
