<?php

namespace App\Modules\Network\Commands;

use Log;
use Illuminate\Support\Facades\DB;

// Creatia Core
use App\Models\Asns;
use App\Helpers\Utility\WhoIs;

// Module Specifics
use App\Modules\Network\Models\Prefixes;
use App\Modules\Network\Models\GeoIp\PrefixGeoIp;

class GeoIpPort extends \App\Console\Commands\BaseCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'geoip:port';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Pulls prefixes from a CSV and associates them with customer ASNs. If the prefix is not already in Creatia it will mark them as unannounced but import them nonetheless.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        if (($handle = fopen(storage_path('geo-import.csv'), 'r')) !== FALSE)
        {
            while (($data = fgetcsv($handle)) !== FALSE)
            {
                $num = count($data);

                // Lookup IP addresses and see if this belongs in anything else
                $belongs_to = null;
    
                $existing_networks_lookup = Prefixes::select('id', DB::raw('concat("address", \'/\', "mask") as prefix'))->get()->keyBy('prefix');

                if(isset($existing_networks_lookup[$data[0]])) {
                    PrefixGeoIp::where('prefix_id', '=', $existing_networks_lookup[$data[0]]->id)->update([
                        'country'           => $data[1],
                        'region'            => $data[2],
                        'city'              => $data[3]
                    ]);
                }
            }

            fclose($handle);
        
            return 0;
        }
    }
}