<?php

namespace App\Http\Controllers;

use App\Models\Router;
use App\Services\Router\MikroTikHotspotService;
use Illuminate\Http\Request;

class HotspotLogController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    protected function resolveRouter(Request $request): ?Router
    {
        $routerId = $request->integer('router_id');
        if ($routerId) {
            return Router::find($routerId);
        }

        return Router::orderBy('name')->first();
    }

    /**
     * System hotspot log (MikroTik /log print topics=hotspot)
     */
    public function index(Request $request)
    {
        $router = $this->resolveRouter($request);
        $limit  = $request->integer('limit', 200);
        $search = trim($request->input('q', ''));

        $logs  = [];
        $error = null;

        if ($router) {
            try {
                $logs = MikroTikHotspotService::logs($router, $limit, $search);
            } catch (\Throwable $e) {
                $error = $e->getMessage();
            }
        }

        return view('hotspot.logs.index', [
            'routers' => Router::orderBy('name')->get(),
            'router'  => $router,
            'logs'    => $logs,
            'limit'   => $limit,
            'search'  => $search,
            'error'   => $error,
        ]);
    }

    /**
     * User log (still based on /log, but filtered by username)
     */
    public function userLog(Request $request)
    {
        $router = $this->resolveRouter($request);
        $limit  = $request->integer('limit', 200);
        $user   = trim($request->input('user', ''));

        $logs  = [];
        $error = null;

        if ($router) {
            try {
                $logs = MikroTikHotspotService::userLogs($router, $limit, $user);
            } catch (\Throwable $e) {
                $error = $e->getMessage();
            }
        }

        return view('hotspot.logs.user', [
            'routers'    => Router::orderBy('name')->get(),
            'router'     => $router,
            'logs'       => $logs,
            'limit'      => $limit,
            'userFilter' => $user,
            'error'      => $error,
        ]);
    }
}
