<?php

namespace App\Http\Controllers;

use App\Models\OltInfo;
use Illuminate\Http\Request;
use App\Services\SnmpManager;
use App\Services\VsolManager;
use App\Services\VsolManager2;
use App\Models\OltOnuInformation;
use Brian2694\Toastr\Facades\Toastr;

class OltController extends Controller
{
    public function oltOnuInformationTruncate()
    {
        OltOnuInformation::truncate();

        return redirect()->back()->with('success', 'OLT ONU Information Truncated Successfully');
    }

    public function run($id)
    {
        try {
            $oltinfo = OltInfo::find($id);

            $activeClients = mikrotikOnlineAndOfflineUsers();
            $usersByMac = collect($activeClients['allOnlineUsersWithoutMap'])->keyBy("caller-id");

            $oids = [
                'oltName' => $oltinfo->olt_name,
                'vlanMac' => $oltinfo->vlan_mac,
                'onuId' => $oltinfo->onu_id,
                'onuInterfaceName' => $oltinfo->onu_interface_name,
                'onuLaser' => $oltinfo->onu_laser,
            ];

            if ($oltinfo->olt_company == 'Vsol') {
                if ($oltinfo->olt_type == 'Epon') {
                    $snmpManager = new VsolManager(
                        $oltinfo->olt_address,
                        $oltinfo->community,
                        $oids,
                        $oltinfo->port
                    );
                } else {
                    $snmpManager = new VsolManager2(
                        $oltinfo->olt_address,
                        $oltinfo->community,
                        $oids,
                        $oltinfo->port
                    );
                }
            } else {
                $snmpManager = new SnmpManager(
                    $oltinfo->olt_address,
                    $oltinfo->community,
                    $oids,
                    $oltinfo->port
                );
            }

            $oltName = $snmpManager->getOltName();
            $onuData = $snmpManager->getAllOnuInformation();

            foreach ($onuData as $onu) {
                if ($onu->laserID != null){
                    $this->updateDatabase($oltinfo->olt_address, $oltName, $onu, $usersByMac);
                }
            }

            Toastr::success('Successfully processed SNMP Manager: ' . $oltinfo->olt_address);
            return redirect()->back();
        } catch (\Exception $e) {
            Toastr::error($e->getMessage());
            return redirect()->back();
        }
    }

    private function updateDatabase($oltAddress, $oltName, $onu, $usersByMac)
    {
        try {
            $onuInfo = OltOnuInformation::firstOrNew(
                [
                    'mac' => $onu['macAddress'],
                ]
            );

            $userExist = $usersByMac[strtoupper(implode(':', str_split($onu['macAddress'], 2)))] ?? null;

            if(!$userExist){
                $userExist = $usersByMac[$onu['macAddress']] ?? null;
            }

            if ($userExist) {
                $onuInfo->username = $userExist["name"];
            }

            $onuInfo->fill([
                'oltaddress' => $oltAddress,
                'onuid' => $onu['onuId'],
                'Vlan' => $onu['vLan'],
                'interface' => $onu['interfaceName'],
                'laser' => $onu['onuLaser'],
                'oltName' => $oltName,
                'username' => $userExist ? $userExist["name"] : null
            ]);

            $onuInfo->save();
        } catch (\Exception $e) {
            Toastr::error("Error updating database for ONU ID: {$onu['onuId']}, Error: {$e->getMessage()}");
        }
    }
}
