<?php

namespace App\Modules\Network\Models\GeoIp;

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

use App\Modules\Network\Models\Supernets;

class PrefixGeoIp extends Model
{
    use SoftDeletes;

    protected $table = 'prefix_geo_ip';

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'prefix_id',
        'country',
        'region',
        'organisation_id',
        'city',
        'whois_error',
    ];

    protected $dates = [
        'created_at',
        'updated_at',
    ];

    public static function countSetTrueSubnets($_organisation_id) {
        return Supernets::leftJoin('prefix_geo_ip', 'prefix_geo_ip.prefix_id', '=', 'subnet_id')
            ->select('subnet_id')
            ->distinct()
            ->whereNotNull('supernet_id')
            ->where('organisation_id', '=', $_organisation_id)
            ->whereNotNull('country')
            ->get()
            ->count();
    }

    public static function countSetTrueSupernets($_organisation_id) {
        $true_subnets = Supernets::leftJoin('prefix_geo_ip', 'prefix_geo_ip.prefix_id', '=', 'subnet_id')
            ->select('subnet_id')
            ->distinct()
            ->whereNotNull('supernet_id')
            ->where('organisation_id', '=', $_organisation_id)
            ->whereNotNull('country')
            ->pluck('subnet_id');

        return Supernets::leftJoin('prefix_geo_ip', 'prefix_geo_ip.prefix_id', '=', 'subnet_id')->whereNotIn('subnet_id', $true_subnets)->whereNotNull('country')->where('organisation_id', '=', $_organisation_id)->count();
    }
}
