<?php
 
namespace App\Rules;

use App\Models\Prefixes;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class SubtenantedAddressV4 implements Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {

        try {
            $all_prefixes = Prefixes::getSubtenancyPrefixes(Auth::user()->organisation_id)->pluck('id');

            return Auth::user()->organisation_id == 1 || boolval(Prefixes::whereRaw('family(address) = 4')->where('organisation_id', '=', 1)->whereIn('id', $all_prefixes)->where(DB::raw("CONCAT(address, '/', mask)::cidr"), '>>=', ($value . '/32'))->count());
        }
        catch(\Exception $ex) {
            return false;
        }

    }
 
    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute must be a valid address that belongs in a prefix allocated to the user.';
    }
}