<?php

namespace App\Services;

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

class ClientDeleteService
{
    public function delete(Client $client, $authUserId): void
    {
        DB::transaction(function () use ($client, $authUserId) {
            // Update client status
            DB::statement("delete from radcheck where username='$client->userid'");
            DB::statement("delete from radusergroup where username='$client->userid'");
            DB::statement("delete from radacct where username='$client->userid'");
            DB::statement("delete from customer_accounts where client_id=$client->id");
            DB::statement("delete from bill_generates where client_id=$client->id");
            DB::statement("delete from clientsinfo where client_id=$client->id");
            DB::statement("delete from clients where id=$client->id");


            $deleted = new CustomerDelInfo();
            $deleted->customer_id = $client->id;
            $deleted->username = $client->userid;
            $deleted->deleted_by = $authUserId;
            $deleted->save();

            if (checkAPI()){
                $mikrotik = new SyncWithMk();
                try {
                    $pop = Pop::with("nas")->find($client->pop_id);
                    $mkIp = $pop->nas->nasname;
                    $mkUser = $pop->nas->mikrotick_user;
                    $mkPass = $pop->nas->mikrotick_user_password;
                    $mkPort = $pop->nas->mikrotick_port;
                    $mk = new Mikrotik($mkIp, $mkUser, $mkPass, $mkPort ? (int)$mkPort : 8728);
                    try {
                        $mk->deleteSecret($client->userid);
                    } catch (Exception $e) {
                    }
                } catch (Exception $e) {
                    Log::error('Mikrotik Sync Error: ' . $e->getMessage());
                }
            }
        }, 1);
    }

}
