<?php

namespace App\Services;

use App\Models\Attendance;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

class AttendanceService
{
    /**
     * Check and mark attendance for all staff for missing working days
     */
    public function markMissingAttendance()
    {
        $lastAttendanceDate = $this->getLastAttendanceDate();
        $today = Carbon::today();
        
        // If no attendance records exist, start from yesterday
        if (!$lastAttendanceDate) {
            $lastAttendanceDate = $today->copy()->subDay();
        }
        
        $currentDate = Carbon::parse($lastAttendanceDate)->addDay();
        
        // Mark attendance for all missing working days up to today
        while ($currentDate->lte($today)) {
            if (Attendance::isWorkingDay($currentDate)) {
                $this->markAllStaffPresent($currentDate->toDateString());
            }
            $currentDate->addDay();
        }
    }
    
    /**
     * Mark all staff with automatic attendance type as present for a specific date
     */
    public function markAllStaffPresent($date)
    {
        // Only get staff with automatic attendance type
        $staff = User::role('Staff')->where('attendance_type', 'automatic')->get();
        
        foreach ($staff as $user) {
            // Check if attendance already exists for this user and date
            $existingAttendance = Attendance::where('user_id', $user->id)
                                          ->whereDate('date', $date)
                                          ->first();
            
            if (!$existingAttendance) {
                Attendance::create([
                    'user_id' => $user->id,
                    'date' => $date,
                    'status' => 'present',
                    'notes' => 'Auto-marked as present (automatic attendance type)',
                    'attendance_type' => 'admin'  // Changed from 'automatic' to 'admin'
                ]);
                
                Log::info("Auto-marked attendance for user {$user->name} on {$date} (automatic attendance type)");
            }
        }
    }
    
    /**
     * Get the last attendance date from the database
     */
    private function getLastAttendanceDate($user = null)
    {
        if ($user) {
            // Get last attendance for specific user
            $lastAttendance = Attendance::where('user_id', $user->id)->orderBy('date', 'desc')->first();
        } else {
            // Get last attendance globally (for backward compatibility)
            $lastAttendance = Attendance::orderBy('date', 'desc')->first();
        }
        
        return $lastAttendance ? $lastAttendance->date : null;
    }
    
    /**
     * Check if attendance needs to be updated (called on login)
     */
    public function checkAndUpdateAttendance($user = null)
    {
        $lastAttendanceDate = $this->getLastAttendanceDate($user);
        $today = Carbon::today();
        
        // If last attendance is from a previous day, mark missing attendance
        if (!$lastAttendanceDate || Carbon::parse($lastAttendanceDate)->lt($today)) {
            $this->markMissingAttendance();
            return true;
        }
        
        return false;
    }
    
    /**
     * Get attendance summary for a user in a specific month
     */
    public function getMonthlyAttendanceSummary($userId, $year, $month)
    {
        $startDate = Carbon::create($year, $month, 1);
        $endDate = $startDate->copy()->endOfMonth();
        
        $totalWorkingDays = Attendance::getWorkingDaysBetween($startDate, $endDate);
        
        $attendanceRecords = Attendance::where('user_id', $userId)
                                     ->whereBetween('date', [$startDate, $endDate])
                                     ->get();
        
        $presentDays = $attendanceRecords->where('status', 'present')->count();
        $absentDays = $attendanceRecords->where('status', 'absent')->count();
        $lateDays = $attendanceRecords->where('status', 'late')->count();
        $halfDays = $attendanceRecords->where('status', 'half_day')->count();
        
        return [
            'total_working_days' => $totalWorkingDays,
            'present_days' => $presentDays,
            'absent_days' => $absentDays,
            'late_days' => $lateDays,
            'half_days' => $halfDays,
            'attendance_percentage' => $totalWorkingDays > 0 ? round(($presentDays / $totalWorkingDays) * 100, 2) : 0
        ];
    }
}