<?php

namespace App\Services;

use App\Classes\MikrotikService\SyncWithMk;
use App\Http\Controllers\Clients\IdDisconnectController;
use App\Models\Client;
use App\Models\User_log;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ClientDisableService
{
    public function disable(Client $user, $details, $authUserId): void
    {
        DB::transaction(function () use ($user, $details, $authUserId) {
            // Update client status
            $user->update([
                'clients_status' => 'disable'
            ]);

            // Update radcheck
            DB::table('radcheck')
                ->where('username', $user->userid)
                ->update([
                    'op' => '!='
                ]);

            // Disconnect the user
            IdDisconnectController::disconnect($user);

            // Log the action
            User_log::create([
                'log_type' => 'id_disable',
                'user_id' => $authUserId,
                'details' => $details,
                'client_id' => $user->id
            ]);

            if (checkAPI()){
                $mikrotik = new SyncWithMk();
                try {
                    $mikrotik->syncSingleClient($user->id);
                } catch (Exception $e) {
                    Log::error('Mikrotik Sync Error: ' . $e->getMessage());
                }
            }

        }, 1);
    }

}
