<?php

namespace App\Services;

use App\Models\Project;
use App\Models\Task;

class ProjectProgressService
{
    public function calculateProgress($projectId)
    {
        $project = Project::findOrFail($projectId);
        $totalTasks = Task::where('project_id', $projectId)->count();

        if ($totalTasks === 0) {
            $project->update(['progress' => 0]);

            return 0;
        }

        $completedTasks = Task::where('project_id', $projectId)->where('status', 'done')->count();
        $progress = round(($completedTasks / $totalTasks) * 100, 2);

        $project->update(['progress' => $progress]);

        return $progress;
    }
}
