<?php

namespace App\Services;

use App\Classes\MikrotikService\Mikrotik;
use App\Classes\MikrotikService\MikrotikStaticIP;
use App\Classes\MikrotikService\SyncWithMk;
use App\Http\Controllers\Clients\IdDisconnectController;
use App\Jobs\ClientSyncJobForSingle;
use App\Models\Client;
use App\Models\Clientsinfo;
use App\Models\User_log;
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ClientCloseService
{
    public function close(Client $client, $details, $authUserId)
    {
        DB::beginTransaction();
        try {
            if (checkAPI()) {
                if (!globalPermission("close-or-deactive-without-mikrotik")) {
                    $mkIp = $client->pop->nas->nasname;
                    $mkUser = $client->pop->nas->mikrotick_user;
                    $mkPass = $client->pop->nas->mikrotick_user_password;
                    $mkPort = $client->pop->nas->mikrotick_port;
                    if ($client->isStatic) {
                        $mk = new MikrotikStaticIP($mkIp, $mkUser, $mkPass, $mkPort ? (int)$mkPort : 8728);
                        $mk->disableStaticIP($client->ip_address);
                    } else {
                        $mk = new Mikrotik($mkIp, $mkUser, $mkPass, $mkPort ? (int)$mkPort : 8728);
                        try {
                            $mk->disconnectSecret($client->userid);
                        } catch (Exception $err) {
                        }
                        $info = $mk->getSecret();
                        foreach ($info as $value) {
                            if ($value['name'] == $client->userid) {
                                $client_info = Clientsinfo::where('client_id', $client->id)->first();
                                $client_info->remarks = $client_info->remarks . ". [Last Log Out Time = " . $value['last-logged-out'] . "]" ?? '';
                                $client_info->save();
                            }
                        }
                        $mk->deleteSecret($client->userid);
                    }
                }
                $client->closed_at = Carbon::now();
                $client->save();
            } else {
                DB::table('radcheck')
                    ->whereUsername($client->userid)
                    ->delete();
                ClientSyncJobForSingle::dispatch($client->id);
            }
            $user_log = new User_log();
            $user_log->log_type = "id_close";
            $user_log->user_id = $authUserId;
            $user_log->details = $details;
            $user_log->client_id = $client->id;
            $user_log->save();
        } catch (Exception $err) {
            DB::rollBack();
        }
        $client->delete();
        DB::commit();
    }
}
