<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Services\AttendanceService;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class CheckAttendanceMiddleware
{
    protected $attendanceService;
    
    public function __construct(AttendanceService $attendanceService)
    {
        $this->attendanceService = $attendanceService;
    }
    
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Only run attendance check for authenticated users with automatic attendance type
        if (Auth::check()) {
            $user = Auth::user();
            
            // Only auto-mark attendance for users with automatic attendance type
            if ($user->attendance_type === 'automatic') {
                try {
                    // Check and update attendance if needed - pass the user to the service
                    $updated = $this->attendanceService->checkAndUpdateAttendance($user);
                    
                    if ($updated) {
                        Log::info('Attendance auto-updated for user: ' . $user->name . ' (automatic attendance type)');
                    }
                } catch (\Exception $e) {
                    // Log error but don't block the request
                    Log::error('Error in attendance middleware: ' . $e->getMessage());
                }
            }
        }
        
        return $next($request);
    }
}
