<?php

namespace App\Http\Controllers;

use App\Models\OltDevice;
use App\Services\OltSshService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class MonitorController extends Controller
{
    public function index()
    {
        $devices = OltDevice::where('active', true)->get();
        return view('monitor.index', compact('devices'));
    }

    public function getSlots(OltDevice $device)
    {
        $cacheKey = "olt_cards_{$device->id}";

        $cached = Cache::get($cacheKey);
        if ($cached !== null) {
            return response()->json(['success' => true, 'slots' => $cached]);
        }

        try {
            $ssh = new OltSshService($device);
            if (!$ssh->connect()) {
                return response()->json(['success' => false, 'message' => 'No se pudo conectar a la OLT.']);
            }

            $cards = $ssh->getOltCards();
            $ssh->disconnect();

            if (empty($cards)) {
                $cards = array_map(fn($s) => ['slot' => $s, 'type' => 'GPON'], range(2, 9));
            }

            Cache::put($cacheKey, $cards, now()->addMinutes(30));

            return response()->json(['success' => true, 'slots' => $cards]);
        } catch (\Throwable $e) {
            return response()->json(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
        }
    }

    public function getTraffic(Request $request, OltDevice $device)
    {
        $request->validate([
            'frame' => 'required|integer|min:1',
            'slot'  => 'required|integer|min:1',
            'port'  => 'required|integer|min:1',
        ]);

        try {
            $ssh = new OltSshService($device);
            if (!$ssh->connect()) {
                return response()->json(['success' => false, 'message' => 'No se pudo conectar a la OLT.']);
            }

            $traffic = $ssh->getPonTraffic($request->frame, $request->slot, $request->port);
            $ssh->disconnect();

            return response()->json(['success' => true, 'traffic' => $traffic]);
        } catch (\Throwable $e) {
            return response()->json(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
        }
    }

    public function getSlotTraffic(Request $request, OltDevice $device)
    {
        $request->validate([
            'frame' => 'required|integer|min:1',
            'slot'  => 'required|integer|min:1',
        ]);

        set_time_limit(300);

        try {
            $ssh = new OltSshService($device);
            if (!$ssh->connectLong()) {
                return response()->json(['success' => false, 'message' => 'No se pudo conectar a la OLT.']);
            }

            $data = $ssh->getSlotTraffic($request->frame, $request->slot);
            $ssh->disconnect();

            return response()->json([
                'success'    => true,
                'ports'      => $data['ports'],
                'sample_raw' => $data['sample_raw'],
            ]);
        } catch (\Throwable $e) {
            return response()->json(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
        }
    }

    public function getResources(OltDevice $device)
    {
        set_time_limit(60);

        try {
            $ssh = new OltSshService($device);
            if (!$ssh->connectLong()) {
                return response()->json(['success' => false, 'message' => 'No se pudo conectar a la OLT.']);
            }

            $resources = $ssh->getSystemResources();
            $ssh->disconnect();

            return response()->json(['success' => true, 'resources' => $resources]);
        } catch (\Throwable $e) {
            return response()->json(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
        }
    }

    public function getOnuSummary(Request $request, OltDevice $device)
    {
        $request->validate([
            'frame' => 'required|integer|min:1',
            'slot'  => 'required|integer|min:1',
        ]);

        set_time_limit(300);

        try {
            $ssh = new OltSshService($device);
            if (!$ssh->connectLong()) {
                return response()->json(['success' => false, 'message' => 'No se pudo conectar a la OLT.']);
            }

            $summary = $ssh->getSlotOnuSummary($request->frame, $request->slot);
            $ssh->disconnect();

            return response()->json(['success' => true, 'summary' => $summary]);
        } catch (\Throwable $e) {
            return response()->json(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
        }
    }
}
