<?php
 
namespace App\Rules;

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

class AdminAnyAsSetIdentity implements Rule
{

    private $approved_only = false;

    public function __construct(bool $_approved_only = false)
    {
        $this->approved_only = $_approved_only;
    }

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


    public function passes($attribute, $value)
    {

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

        try {

            if($this->approved_only) {
                return AsSets::where([['id', '=', $value], ['approved', '=', 1]])->count() === 1;
            }

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

    }

    public function message()
    {
        return 'The :attribute must correlate to a valid, not deleted AS-SET.';
    }
}