<?php
 
namespace App\Rules;

use App\Models\AsSets;
use Illuminate\Contracts\Validation\Rule;
use Exception;
use Illuminate\Support\Facades\Auth;

class OwnedAsSetIdentity 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)
    {

        try {

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

            return AsSets::where('organisation_id', '=', Auth::user()->organisation_id)->where('id', '=', $value)->count() === 1;
        }
        catch(Exception $ex) {
            return false;
        }

    }

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