<?php

namespace App\Http\Controllers;

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

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

    public function index(Request $request)
    {
        $routers = Router::orderBy('name')->get();
        $routerId = $request->query('router_id') ?: $routers->first()?->id;

        $router = $routers->firstWhere('id', $routerId);
        $profiles = [];
        if ($router) {
            try {
                $profiles = MikroTikHotspotService::listProfiles($router);
            } catch (\Throwable $e) {
                $profiles = [];
            }
        }

        return view('hotspot.profiles.index', compact('routers', 'routerId', 'router', 'profiles'));
    }

    public function create(Request $request)
    {
        $routers = Router::orderBy('name')->get();
        $routerId = $request->query('router_id') ?: $routers->first()?->id;

        return view('hotspot.profiles.create', compact('routers','routerId'));
    }

    public function store(Request $r)
    {
        $data = $r->validate([
            'router_id'        => 'required|exists:routers,id',
            'name'             => 'required|string|max:191',
            'rate_limit'       => 'nullable|string|max:191',
            'shared_users'     => 'nullable|string|max:50',
            'idle_timeout'     => 'nullable|string|max:50',
            'keepalive_timeout'=> 'nullable|string|max:50',
            'parent_queue'     => 'nullable|string|max:191',
            'comment'          => 'nullable|string|max:191',
        ]);

        $router = Router::findOrFail($data['router_id']);

        MikroTikHotspotService::createProfile($router, $data);

        return redirect()
            ->route('hotspot.profiles.index', ['router_id' => $router->id])
            ->with('status', 'Profile created on MikroTik.');
    }

    public function edit(Request $request, Router $router, string $profileName)
    {
        $routers = Router::orderBy('name')->get();
        $profiles = MikroTikHotspotService::listProfiles($router);

        $profile = collect($profiles)->firstWhere('name', $profileName);
        if (!$profile) {
            abort(404);
        }

        return view('hotspot.profiles.edit', compact('routers','router','profile'));
    }

    public function update(Request $r, Router $router, string $profileName)
    {
        $data = $r->validate([
            'name'             => 'required|string|max:191',
            'rate_limit'       => 'nullable|string|max:191',
            'shared_users'     => 'nullable|string|max:50',
            'idle_timeout'     => 'nullable|string|max:50',
            'keepalive_timeout'=> 'nullable|string|max:50',
            'parent_queue'     => 'nullable|string|max:191',
            'comment'          => 'nullable|string|max:191',
        ]);

        $profiles = MikroTikHotspotService::listProfiles($router);
        $profile = collect($profiles)->firstWhere('name', $profileName);
        if (!$profile || empty($profile['id'])) {
            return back()->withErrors('Profile not found on router.');
        }

        MikroTikHotspotService::updateProfile($router, $profile['id'], $data);

        return redirect()
            ->route('hotspot.profiles.index', ['router_id' => $router->id])
            ->with('status', 'Profile updated.');
    }

    public function destroy(Router $router, string $profileName)
    {
        $profiles = MikroTikHotspotService::listProfiles($router);
        $profile = collect($profiles)->firstWhere('name', $profileName);
        if ($profile && !empty($profile['id'])) {
            MikroTikHotspotService::deleteProfile($router, $profile['id']);
        }

        return redirect()
            ->route('hotspot.profiles.index', ['router_id' => $router->id])
            ->with('status','Profile deleted from MikroTik.');
    }
}
