<?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 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) {
            $existing = DailyAttendance::where('employee_id', $employee->id)
                ->whereDate('date', $date)
                ->first();

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

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

            if ($logs->isEmpty()) continue;

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

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

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

            $shiftStart = Carbon::parse($date . ' ' . $shiftStartStr);
            $lateMinutes = 0;
            
            // Check if checked in after shift start + grace period
            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',
                ]
            );
            $processedCount++;
        }

        return $processedCount;
    }
}
