<?php

namespace App\Services;

use App\Classes\MikrotikService\Mikrotik;
use App\Models\ApiBandwidthUsage;
use App\Models\Nas;
use Carbon\Carbon;

class ApiBandwidthUsageService
{
    private $mikrotiks;
    public function __construct()
    {
        $this->mikrotiks = Nas::all();
    }


    private function getOnlineClientByName($name, $activeConnections)
    {

        foreach ($activeConnections as $activeConnection) {
            if ($activeConnection["name"] == $name) {
                return $activeConnection;
            }
        }
        return null;
    }

    private function parseTime($time)
    {
        return Carbon::createFromFormat('M/d/Y H:i:s', $time);
    }
    private function bytesToMegabytes($bytes)
    {
        return $bytes / 1048576;
    }

    public function processClientUsage($secret, $activeConnections, $mk)
    {
        $online = $this->getOnlineClientByName($secret["name"], $activeConnections);
        $existingSession = ApiBandwidthUsage::where("username", $secret["name"])->whereNull("session_end_time")->first();

        if (!$online) {
            if (!$existingSession) {
                return;
            }

            $existingSession->session_end_time = $this->parseTime($secret["last-logged-out"]);
            $existingSession->last_disconnect_reason = $secret["last-disconnect-reason"];
            $existingSession->save();
            return;
        }

        $bandwidthUsage = $mk->getBandwidthUsage($secret["name"]);

        if ($existingSession) {
            if ($existingSession->session_id == $online['session-id']) {
                $existingSession->downloaded = $this->bytesToMegabytes($bandwidthUsage["tx-byte"]);
                $existingSession->uploaded =  $this->bytesToMegabytes($bandwidthUsage["rx-byte"]);
                $existingSession->save();
                return;
            }

            $existingSession->session_end_time = $this->parseTime($secret["last-logged-out"]);
            $existingSession->last_disconnect_reason = $secret["last-disconnect-reason"];
            $existingSession->save();
        }

        // create new sessions
        ApiBandwidthUsage::create([
            "session_id" => $online['session-id'],
            "username" => $secret["name"],
            "ip_address" => $online["address"],
            "mac_address" => $online["caller-id"],
            "downloaded" => $this->bytesToMegabytes($bandwidthUsage["tx-byte"]),
            "uploaded" => $this->bytesToMegabytes($bandwidthUsage["rx-byte"]),
            "session_start_time" => $this->parseTime($bandwidthUsage["last-link-up-time"]),
        ]);
    }

    public function UpdateOnlineClientBandwidthUsage()
    {



        foreach ($this->mikrotiks as $mikrotik) {
            $mkIp = $mikrotik->nasname;
            $mkUser = $mikrotik->mikrotick_user;
            $mkPass = $mikrotik->mikrotick_user_password;
            $mkPort = $mikrotik->mikrotick_port;
            try {
                $mk = new Mikrotik($mkIp, $mkUser, $mkPass, $mkPort ? (int)$mkPort : 8728);

                $secrets = $mk->getSecret();
                $activeConnections = $mk->getActiveConnection();
                foreach ($secrets as $secret) {
                    $this->processClientUsage($secret, $activeConnections, $mk);
                }
            } catch (\Exception $e) {
                dd($e);
                continue;
            }
        }
        return "commando echo.";
    }
}
