<?php

namespace App\Services;

use App\Models\BioTimeAttendanceLog;
use App\Models\DailyAttendance;
use App\Models\Employee;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

class AttendanceService
{
    public function processEmployeeLogsToDailyAttendance(Employee $employee, string $date): bool
    {
        $existing = DailyAttendance::where('employee_id', $employee->id)
            ->whereDate('date', $date)
            ->first();

        if ($existing && strtolower((string) $existing->source) === 'manual') {
            return false;
        }

        $logs = BioTimeAttendanceLog::where('employee_id', $employee->id)
            ->whereDate('punch_time', $date)
            ->orderBy('punch_time', 'asc')
            ->get();

        if ($logs->isEmpty()) {
            return false;
        }

        $checkIn = $logs->first()->punch_time;
        $checkOut = $logs->count() > 1 ? $logs->last()->punch_time : null;

        $minutesWorked = 0;
        if ($checkIn && $checkOut) {
            $minutesWorked = $checkIn->diffInMinutes($checkOut);
        }

        $department = $employee->department;
        $shiftStartStr = $department ? $department->shift_start : '09:00:00';
        $gracePeriod = $department ? $department->grace_period : 15;

        $shiftStart = Carbon::parse($date . ' ' . $shiftStartStr);
        $lateMinutes = 0;

        if ($checkIn->greaterThan($shiftStart->copy()->addMinutes($gracePeriod))) {
            $lateMinutes = $checkIn->diffInMinutes($shiftStart);
        }

        $status = 'present';
        if ($lateMinutes > 0) {
            $status = 'late';
        }

        DailyAttendance::updateOrCreate(
            [
                'employee_id' => $employee->id,
                'date' => $date,
            ],
            [
                'check_in' => $checkIn,
                'check_out' => $checkOut,
                'minutes_worked' => $minutesWorked,
                'overtime_minutes' => 0,
                'is_business_out' => false,
                'late_minutes' => $lateMinutes,
                'status' => $status,
                'source' => 'BioTime',
            ]
        );

        return true;
    }

    public function processLogsToDailyAttendance($date = null)
    {
        $date = $date ? Carbon::parse($date)->toDateString() : now()->toDateString();
        $employees = Employee::with('department')->where('status', 'active')->get();
        $processedCount = 0;

        foreach ($employees as $employee) {
            if ($this->processEmployeeLogsToDailyAttendance($employee, $date)) {
                $processedCount++;
            }
        }

        return $processedCount;
    }
}
