<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use App\Models\Project;
use Carbon\Carbon;

class AllMosaicsPresentRule implements Rule
{
    protected $projectId;
    protected $errorMessage = '';

    public function __construct($projectId)
    {
        $this->projectId = $projectId;
    }

    public function passes($attribute, $value)
    {
        try {
            /** @var Project $project */
            $project = Project::find($this->projectId);

            if (!$project) {
                $this->errorMessage = 'Project not found.';
                return false;
            }

            return $project->allMosaicsPresent(new Carbon($value['end_date']));
        } catch (\Exception $e) {
            $this->errorMessage = $e->getMessage();
            return false;
        }
    }

    public function message()
    {
        return $this->errorMessage;
    }
}
