<?php

namespace App\Classes\customer;

use App\Classes\Accounting\Accounting;
use App\Models\Client;
use App\Classes\MikrotikService\Mikrotik;
use App\Models\Nas;
use App\Models\Pop;
use Exception;
use Illuminate\Support\Facades\DB;

class clientLiveSpeed
{

    public static function liveSpeed($user, $userinfo)
    {
        $error = null;
        $bandwidthUsage = null;
        $lastLogoutTime = null;
        if ($userinfo || checkAPI()) {
            $mikrotick_info = checkAPI() ? $user->pop->nas : Nas::where('nasname', $userinfo->nasipaddress)->first();
            if ($mikrotick_info) {
                if ($mikrotick_info->mikrotick_user && $mikrotick_info->mikrotick_user_password) {
                    try {
                        $mk = new Mikrotik($mikrotick_info->nasname, $mikrotick_info->mikrotick_user, $mikrotick_info->mikrotick_user_password, $mikrotick_info->mikrotick_port ? (int)$mikrotick_info->mikrotick_port : 8728);

                        $lastLogoutTime = $mk->getSecret($user->userid)['last-logged-out'];
                        preg_match('/\b(\d{4})\b/', $lastLogoutTime, $matches);
                        $year = (int)$matches[1];
                        $lastLogoutTime = $year > 2013 ? $lastLogoutTime : "User not connected Yet.";
                        $bandwidthUsage = $mk->getBandwidthUsage($user->userid);
                    } catch (Exception $e) {
                        $error = $e->getMessage();
                    }
                } else {
                    $error = "Mikrotik username or password not provided";
                }
            } else {
                $error = "Mikrotik Not Found";
            }
        } else {
            $error = 'User not Online';
        }

        return [
            'error' => $error,
            'bandwidthUsage' => $bandwidthUsage,
            "lastLogoutTime" => $lastLogoutTime,
        ];
    }

    public function clientLiveSpeedShow($id)
    {

        $list = Client::where('id', $id);

        $user = Client::with('pop.nas')->find($id);
        $pppoe_user = str_replace(' ', '_', $user->userid);

        $accounting = new Accounting();

        $userinfo = $accounting->lastOnlineOfSingleUser($pppoe_user);

        $liveSpeed = self::liveSpeed($user, $userinfo);


        return [
            'error' => $liveSpeed['error'],
            'bandwidthUsage' =>  $liveSpeed['bandwidthUsage'],
            "lastLogoutTime" => $liveSpeed['lastLogoutTime'],
            'data' => $list->get(),
            'page_title' => 'Customer Details Information',
            'pop' => Pop::all(),
            'user_id' => 1
        ];
    }
}
