<?php

namespace App\Console\Commands\Utility;

use App\Models\GeoIp\PrefixGeoIp;
use App\Models\Prefixes;
use App\Models\PrefixSubtenants;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Creates CSV Showing a list of all subnets assigned to a hardcoded org.';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $prefixes_relevant = Prefixes::getOrganisationPrefixes(8)->pluck('id');

        $csv_rows = [ ['prefix', 'country', 'region', 'city'] ];
        PrefixGeoIp::leftJoin('prefixes', 'prefixes.id', '=', 'prefix_id')->select('address', 'mask', 'country', 'region', 'city')
            ->whereIn('prefixes.id', $prefixes_relevant)
            ->whereNull('prefixes.deleted_at')
            ->orderBy('address')
            ->orderBy('mask')
            ->chunk(config('creatia.constant.chunk_large'), function($x) use(&$csv_rows) {
                foreach($x as $y) {
                    $csv_rows[] = ["$y->address/$y->mask", $y->country ?? '', $y->region ?? '', trim($y->city) ?? ''];
                }
            });

        $output_fh = fopen('php://output', 'w+');

        ob_start();

        foreach($csv_rows as $row) {
            $row[] = '';

            fputs($output_fh, implode(',', $row)."\n");
        }

        $final_content = ob_get_clean();

        fclose($output_fh);

        file_put_contents(storage_path('geo-ip-dump.csv'), $final_content);
        
        return 0;
    }
}