<?php

namespace App\Http\Controllers\Clients;

use App\Classes\Accounting\Accounting;
use App\Models\Pop;
use App\Models\Client;
use App\Models\Reseller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Models\CompanyInformation;
use Brian2694\Toastr\Facades\Toastr;

use App\Classes\MikrotikService\Mikrotik;
use App\Models\AccountingServer;
use App\Models\Nas;
use Exception;

class OnlineCustomerController extends Controller
{

    public function customer_list()
    {
        $pop_ids = Pop::poplist()->pluck('id')->toArray();

        $list = Client::whereIn('pop_id', $pop_ids)
            ->pluck('userid')
            ->toArray();

        return $list;
    }

    public function online_customer_list()
    {



        $online = 0; // Initialize an empty collection to store the results

        $usernames = $this->customer_list();

        $accounting = new Accounting();

        $all_online_user = $accounting->totalOnlineUser();

        $common_user = array_intersect($usernames, $all_online_user);
        $online = count($common_user);

        return $online;
    }



    public function onlineCustomer()
    {

        if (checkAPI()) {
        }

        $online = "";
        // dd($online);

        $resellers = Reseller::resellerList()->get();
        return view('clients.onlineofline.online', [
            'page_title' => 'Online Customer List',
            'list' => $online,
            'reseller'   =>  $resellers,
        ]);
    }


    public function onlineCustomerSearch(Request $request)
    {

        if (checkAPI()) {

            if ($request->ajax()) {
                $allMikrotikAndActiveUsers = [];

                $new_client = [];
                $count = 0;
                if ($request->pop != null && $request->pop != 'all') {
                    try {

                        $pop = Pop::with("nas")->find($request->pop);

                        if ($request->clients_status != null) {
                            $clients = Client::list()->where('clients_status', $request->clients_status)->where('pop_id', $request->pop)->get();
                        } else {
                            $clients = Client::list()->where('clients_status', '!=', 'deactive')->where('pop_id', $request->pop)->get();
                        }


                        if (!globalPermission("clientManageThroughNodeJs")) {
                            $mkIp = $pop->nas->nasname;
                            $mkUsername = $pop->nas->mikrotick_user;
                            $mkPassword = $pop->nas->mikrotick_user_password;
                            $mkPort = $pop->nas->mikrotick_port;
                            $mk = new Mikrotik($mkIp, $mkUsername, $mkPassword, $mkPort ? (int)$mkPort : 8728);
                            $allActiveUsers = $mk->getActiveConnection();
                        }

                        $mikrotikAndActiveUsers = [
                            "nasIp" => $pop->nas->nasname,
                            "activeUsers" => []
                        ];

                        if (!globalPermission("clientManageThroughNodeJs")) {
                            $currentActiveUsers = [];
                            foreach ($allActiveUsers as $user) {
                                $currentActiveUsers[$user["name"]] = $user;
                            }
                        }


                        foreach ($clients as $client) {
                            if (globalPermission("clientManageThroughNodeJs")) {
                                $activeUser = activeFromRedis($client->userid);
                                if ($activeUser) {
                                    $clientName = $client->clientsinfo->clients_name ?? '';
                                    $activeUser['client_name'] = $clientName;
                                    array_push($mikrotikAndActiveUsers["activeUsers"], $activeUser);
                                    $count++;
                                    $new_client[$client->userid] = $client->id;
                                }
                            } else
                            if (array_key_exists($client->userid, $currentActiveUsers)) {
                                $clientName = $client->clientsinfo->clients_name ?? '';
                                $activeUser = $currentActiveUsers[$client->userid];
                                $activeUser['client_name'] = $clientName;
                                array_push($mikrotikAndActiveUsers["activeUsers"], $activeUser);
                                $count++;
                                $new_client[$client->userid] = $client->id;
                            }
                        }

                        array_push($allMikrotikAndActiveUsers, $mikrotikAndActiveUsers);
                    } catch (Exception $err) {
                        dd($err);
                    }
                } else if ($request->reseller != null && $request->pop == 'all') {
                    $pops = Pop::with("nas")->where("reseller_id", $request->reseller)->get();

                    foreach ($pops as $pop) {
                        try {
                            if ($request->clients_status != null) {
                                $clients = Client::list()->where('clients_status', $request->clients_status)->where('pop_id', $pop->id)->get();
                            }else{
                                $clients = Client::list()->where('clients_status', '!=', 'deactive')->where('pop_id', $pop->id)->get();
                            }

                            if (!globalPermission("clientManageThroughNodeJs")) {
                                $mkIp = $pop->nas->nasname;
                                $mkUsername = $pop->nas->mikrotick_user;
                                $mkPassword = $pop->nas->mikrotick_user_password;
                                $mkPort = $pop->nas->mikrotick_port;
                                $mk = new Mikrotik($mkIp, $mkUsername, $mkPassword, $mkPort ? (int)$mkPort : 8728);
                                $allActiveUsers = $mk->getActiveConnection();
                            }

                            $mikrotikAndActiveUsers = [
                                "nasIp" => $pop->nas->nasname,
                                "activeUsers" => []
                            ];

                            if (!globalPermission("clientManageThroughNodeJs")) {
                                $currentActiveUsers = [];
                                foreach ($allActiveUsers as $user) {
                                    $currentActiveUsers[$user["name"]] = $user;
                                }
                            }

                            // return $clients;
                            foreach ($clients as $client) {
                                if (globalPermission("clientManageThroughNodeJs")) {
                                    $activeUser = activeFromRedis($client->userid);
                                    if ($activeUser) {
                                        $clientName = $client->clientsinfo->clients_name ?? '';
                                        $activeUser['client_name'] = $clientName;
                                        array_push($mikrotikAndActiveUsers["activeUsers"], $activeUser);
                                        $count++;
                                        $new_client[$client->userid] = $client->id;
                                    }
                                } else
                            if (array_key_exists($client->userid, $currentActiveUsers)) {
                                    $clientName = $client->clientsinfo->clients_name ?? '';
                                    $activeUser = $currentActiveUsers[$client->userid];
                                    $activeUser['client_name'] = $clientName;
                                    array_push($mikrotikAndActiveUsers["activeUsers"], $activeUser);
                                    $count++;
                                    $new_client[$client->userid] = $client->id;
                                }
                            }
                            array_push($allMikrotikAndActiveUsers, $mikrotikAndActiveUsers);
                        } catch (Exception $err) {
                        }
                    }
                } else if ($request->reseller == null) {
                    $allMikrotik = Nas::all();


                    foreach ($allMikrotik as $mikrotik) {
                        try {

                            $mkIp = $mikrotik->nasname;
                            $mkUsername = $mikrotik->mikrotick_user;
                            $mkPassword = $mikrotik->mikrotick_user_password;
                            $mkPort = $mikrotik->mikrotick_port;
                            $mk = new Mikrotik($mkIp, $mkUsername, $mkPassword, $mkPort ? (int)$mkPort : 8728);
                            $allActiveUsers = $mk->getActiveConnection();

                            $mikrotikAndActiveUsers = [
                                "nasIp" => $mkIp,
                                "activeUsers" => []
                            ];

                            $currentActiveUsers = [];
                            foreach ($allActiveUsers as $user) {

                                $currentActiveUsers[$user["name"]] = $user;
                            }
                             if ($request->clients_status != null) {
                                 $clients = Client::list()->where('clients_status', $request->clients_status)->whereIn("userid", array_keys($currentActiveUsers))->get();

                             }else{

                                 $clients = Client::list()->whereIn("userid", array_keys($currentActiveUsers))->get();
                             }

                            foreach ($clients as $client) {
                                if (array_key_exists($client->userid, $currentActiveUsers)) {
                                    $clientName = $client->clientsinfo->clients_name ?? '';
                                    $activeUser = $currentActiveUsers[$client->userid];
                                    $activeUser['client_name'] = $clientName;
                                    array_push($mikrotikAndActiveUsers["activeUsers"], $activeUser);
                                    $count++;
                                    $new_client[$client->userid] = $client->id;
                                }
                            }

                            array_push($allMikrotikAndActiveUsers, $mikrotikAndActiveUsers);
                        } catch (Exception $err) {
                        }
                    }
                }
                $data = [

                    'allMikrotikAndActiveUsers' => $allMikrotikAndActiveUsers,
                    'page_title' => 'Online Customer List',
                    "count" => $count,
                    'clients' => $new_client,
                ];
                // return $data;
                return view('clients.onlineofline.onlinesearch', $data);
            }
        } else {
            if ($request->ajax()) {

                $list = Client::list()->where('clients_status', '!=', 'deactive');

                if ($request->reseller != null && $request->pop == 'all') {

                    $reseller_ids = DB::table('reseller_user')->where('reseller_id', $request->reseller)->pluck('reseller_id')->toArray();
                    $pop_ids = Pop::with('reseller', 'nas')->whereIn('reseller_id', $reseller_ids)->pluck('id')->toArray();
                    $list = $list->whereIn('pop_id', $pop_ids)->pluck('userid')->toArray();
                } elseif ($request->reseller != null && $request->pop != null) {

                    $list = $list->where('pop_id', $request->pop)->pluck('userid')->toArray();
                } elseif ($request->reseller == null) {

                    $list = $this->customer_list();
                }
            }



            $listChunks = array_chunk($list, 1000);
            $online = collect();
            $accounting = new Accounting();

            foreach ($listChunks as $chunk) {

                $result = $accounting->totalOnlineUserWithInformation($chunk);
                $online = $online->merge($result);
            }


            session([
                'onlineUserList' => $online
            ]);

            return view('clients.onlineofline.onlinesearch', [
                'list' => $online,
                'page_title' => 'Online Customer List',
            ]);
        }
    }

    public function disconnectAll()
    {
        $list = session('onlineUserList');
        $accounting = new Accounting();

        foreach ($list as $l) {
            $accounting->singleUserDisconnect($l->username);
            $accounting->setAcctStopTimeNow($l->username);
        }
        return redirect()->back();
    }


    public function onlineUserDisconnect(Request $request)
    {
        $accounting = new Accounting();
        $accounting->singleUserDisconnect($request->id);
        return redirect()->back();
    }
}
