<?php

namespace App\Services;

use App\Models\Task;
use App\Models\User;
use Carbon\Carbon;

class WorkloadService
{
    public function getWorkload()
    {
        $users = User::all();

        return $users->map(function ($user) {
            $activeTasks = Task::where('assignee_id', $user->id)->where('status', '!=', 'done')->count();
            $delayedTasks = Task::where('assignee_id', $user->id)
                ->where('due_date', '<', Carbon::now())
                ->where('status', '!=', 'done')
                ->count();
            $estimatedHours = Task::where('assignee_id', $user->id)->sum('estimated_time');
            $actualHours = Task::where('assignee_id', $user->id)->sum('actual_time');

            return [
                'user_id' => $user->id,
                'user_name' => $user->name,
                'active_tasks' => $activeTasks,
                'delayed_tasks' => $delayedTasks,
                'estimated_hours' => (float) $estimatedHours,
                'actual_hours' => (float) $actualHours,
                'workload_percentage' => $estimatedHours > 0 ? round(($actualHours / $estimatedHours) * 100, 2) : 0,
            ];
        });
    }
}
