<?php

namespace App\Jobs;

use App\Classes\MikrotikService\SyncWithMk;
use App\Http\Controllers\Clients\IdDisconnectController;
use App\Http\Controllers\Clients\IdEnableDisableController;
use App\Models\Client;
use App\Models\Pop;
use App\Models\User_log;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;

class PopDeactiveJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    private $pop_id;
    public function __construct($pop_id)
    {
        $this->pop_id = $pop_id;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {

        $client = Client::where('pop_id', $this->pop_id)->get();
        foreach ($client as $value) {

            DB::beginTransaction();
            try {


                // $this->disableInRadius($user);


                Client::where('id', $value->id)
                    ->update([
                        'clients_status' => 'deactive'
                    ]);

                User_log::create([
                    'log_type' => 'id_deactive',
                    'user_id' => auth()->id(),
                    'details' => "deactive all customer from pop",
                    'client_id' => $value->id
                ]);
                if (checkAPI()) {
                    if (checkSettings("close-or-deactive-without-mikrotik") != "enable") {
                        $mikrotik = new SyncWithMk();
                        $mikrotik->syncSingleClient($value->id);
                    }
                } else {
                    DB::table('radcheck')
                        ->whereUsername($value->userid)
                        ->delete();

                    IdDisconnectController::disconnect($value);
                }


                DB::commit();
            } catch (\Throwable $th) {
            }
        }
    }
}
