<?php
 
namespace App\Rules;

use App\Models\Goliath\GoliathAttackPrefix;
use App\Repositories\ReportRepository;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Auth;

class AllowedReportIdentity implements Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        
        /**
         * Determine whether the provided identifier correlates with an attack that the user would be allowed to see.
         */

        $organisation_id = Auth::user()->organisation_id;

        $valid_owned = GoliathAttackPrefix::leftJoin('prefixes', 'prefix_id', '=', 'prefixes.id')->where([ 
            ['organisation_id', '=', $organisation_id], 
            ['attack_id', '=', $value]
        ])->exists();

        $valid_leased = GoliathAttackPrefix::leftJoin('goliath_attacks', 'attack_id', '=', 'goliath_attacks.id')
            ->leftJoin('prefixes', 'goliath_attack_prefixes.prefix_id', '=', 'prefixes.id')
            ->leftJoin('prefix_subtenants', 'prefix_subtenants.prefix_id', '=', 'prefixes.id')
            ->whereRaw('goliath_attacks.started_at >= prefix_subtenants.created_at AND (goliath_attacks.last_at <= prefix_subtenants.deleted_at OR (prefix_subtenants.deleted_at IS NULL))')
            ->where([
                ['subtenant_id', '=', $organisation_id],
                ['attack_id', '=', $value]
            ])->exists();

        if($valid_owned || $valid_leased) {
            return true;
        }

        return false;
    }
 
    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute must be a valid reporting identifier.';
    }
}