<?php

namespace App\Console\Commands;

use App\Models\Nas;
use App\Models\Pop;
use RouterOS\Query;
use App\Models\Client;
use App\Models\Clientsinfo;
use Illuminate\Console\Command;
use App\Classes\MikrotikService\Mikrotik as ClassesMikrotik;

class DisableSecretIfClientNotExistCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'disablesecret:ifclientnotexist';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Disable secret if client does not exist in the database';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        if(checkSettings('disableSecretIfClientNotExist') == 'disable') {
            return $this->info('Command is disabled in the global settings');
        }

        $nas = Nas::all();

        foreach ($nas as $item) {
            $mk = new ClassesMikrotik($item->nasname, $item->mikrotick_user, $item->mikrotick_user_password, $item->mikrotick_port ? (int)$item->mikrotick_port : 8728);
            $secrets = $mk->getSecret();

            // Get pops
            $pops = Pop::where('nas_id', $item->id)->get();

            // Get clients under the pop
            $clients = Client::withTrashed()->whereIn('pop_id', $pops->pluck('id'))->get();

            // Array to store extra secrets not matching any client
            $extraSecrets = [];


            // Loop through each secret from mikrotik
            foreach ($secrets as $secret) {
                $secretName = $secret['name'];
                $secretComment = $secret['comment'] ?? '';

                if(!in_array($secretName, $clients->pluck('userid')->toArray())) {
                    $extraSecrets[] = [
                        'name' => $secretName,
                        'comment' => $secretComment
                    ];
                }
            }

            foreach($extraSecrets as $secret) {
                try{
                    $mk->setComment($secret['name'], $secret['comment'] . ' - Client not found in the database. Disable by System');
                    $mk->disableSecret($secret['name']);
                    $mk->disconnectSecret($secret['name']);
                }catch (\Exception $e) {
                    $this->error("Error processing secret {$secret['name']} on NAS {$item->nasname}: " . $e->getMessage());
                    continue;
                }
            }



        }
    }
}
