<?php

namespace App\Rules;

use App\Models\Organisation;
use Illuminate\Contracts\Validation\Rule;
use Exception;

class OrganisationIdentity implements Rule
{

    private $with_trashed = false;

    public function __construct(bool $_with_trashed = false)
    {
        $this->with_trashed = $_with_trashed;
    }

    public static function make(bool $with_trashed = false)
    {
        return new static($with_trashed);
    }


    public function passes($attribute, $value)
    {

        if (!is_scalar($value)) {
            return false;
        }

        try {

            if($this->with_trashed) {
                return Organisation::withTrashed()->find($value) !== null;
            }

            return Organisation::find($value) !== null;
        }
        catch(Exception $ex) {
            return false;
        }

    }

    public function message()
    {
        return 'The :attribute must correlate to a valid organisation.';
    }
}
