<?php

namespace App\Http\Controllers;

use App\Jobs\PollRouterJob;
use App\Models\Router;
use Illuminate\Http\Request;

class RouterController extends Controller
{
    public function index()
    {
        $q = Router::query();
        if($s = request('s')) $q->where('name','like',"%$s%")->orWhere('host','like',"%$s%");
        $routers = $q->latest()->paginate(15);
        return view('routers.index', compact('routers'));
    }

    public function create(){ return view('routers.create'); }

    public function store(Request $r)
    {
        $data = $r->validate([
            'name'=>'required','host'=>'required','api_port'=>'nullable|integer',
            'username'=>'required','password'=>'required',
            'use_tls'=>'boolean','site'=>'nullable','tags'=>'nullable'
        ]);
        $data['api_port'] = $data['api_port'] ?? 8728;
        $router = Router::create($data);
        dispatch(new PollRouterJob($router));
        return redirect()->route('routers.index')->with('status','Router added and polling started.');
    }

    public function edit(Router $router){ return view('routers.edit', compact('router')); }

    public function update(Request $r, Router $router)
    {
        $data = $r->validate([
            'name'=>'required','host'=>'required','api_port'=>'nullable|integer',
            'username'=>'required','password'=>'required',
            'use_tls'=>'boolean','site'=>'nullable'
        ]);
        $router->update($data);
        return redirect()->route('routers.index')->with('status','Router updated.');
    }

    public function destroy(Router $router)
    {
        $router->delete();
        return back()->with('status','Router removed.');
    }

    public function show(Router $router)
    {
        return view('routers.show', compact('router'));
    }
}
