<?php

namespace App\Modules\Network\Models\Mitigation;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Log;

use App\Modules\Network\Models\Supernets;

class PrefixMitigation extends Model
{
    use SoftDeletes;

    protected $table = 'prefix_mitigation';

    protected $fillable = [
        'prefix_id',
        'ruleset_ids',
        'sensitivity_id',
        'synced_at',
        'origin',
        'organisation_id',
        'last_source',
        'sent',
        'in_sync',
    ];

    protected $dates = [
        'synced_at',
    ];

    public static function parentSenseSet($_prefix_id) {
        // Firstly, get all supernets that this prefix could live in. Then if there's any with a set sensitivity, then return true.
        if($sense = Supernets::leftJoin('prefix_mitigation', 'prefix_mitigation.prefix_id', '=', 'supernet_id')->where('subnet_id', '=', $_prefix_id)->whereNotNull('sensitivity_id')->first())
        {
            return $sense->sensitivity_id;
        }

        return false;
    }

    public static function childSenseSet($_prefix_id) {
        // Firstly, get all subnets that this prefix could contain. Then if there's any with a set sensitivity, return true.
        if($sense = Supernets::leftJoin('prefix_mitigation', 'prefix_mitigation.prefix_id', '=', 'subnet_id')->where('supernet_id', '=', $_prefix_id)->whereNotNull('sensitivity_id')->first())
        {
            return $sense->sensitivity_id;
        }

        return false;
    }

    public static function pullProfile() {

    }

    public static function countSetTrueSubnets($_organisation_id) {
        return Supernets::leftJoin('prefix_mitigation', 'prefix_mitigation.id', '=', 'subnet_id')
            ->select('subnet_id')
            ->distinct()
            ->whereNotNull('supernet_id')
            ->where('organisation_id', '=', $_organisation_id)
            ->whereRaw('(sensitivity_id is not null OR ruleset_ids is not null)')
            ->get()
            ->count();
    }

    public static function countSetTrueSupernets($_organisation_id) {
        $true_subnets = Supernets::leftJoin('prefix_mitigation', 'prefix_mitigation.id', '=', 'subnet_id')
            ->select('subnet_id')
            ->distinct()
            ->whereNotNull('supernet_id')
            ->where('organisation_id', '=', $_organisation_id)
            ->whereRaw('(sensitivity_id is not null OR ruleset_ids is not null)')
            ->pluck('subnet_id');

        return Supernets::leftJoin('prefix_mitigation', 'prefix_mitigation.id', '=', 'subnet_id')->whereNotIn('subnet_id', $true_subnets)->whereRaw('(sensitivity_id is not null OR ruleset_ids is not null)')->where('organisation_id', '=', $_organisation_id)->count();
    }

}
