@extends('layouts.app')
@section('title','Edit Router — BlueBando v3')

@section('content')
  <h1 style="margin:0 0 12px">Edit Router</h1>

  <div class="card full">
    <form method="POST" action="{{ route('routers.update',$router) }}">
      @csrf
      @method('PUT')

      <div style="display:grid;grid-template-columns:repeat(2,1fr);gap:14px">

        <div>
          <label class="label">Prefer VPN when available</label>
          <select class="input" name="prefer_vpn">
            <option value="1" @selected($router->prefer_vpn)>Yes</option>
            <option value="0" @selected(!$router->prefer_vpn)>No</option>
          </select>
          <div class="muted" style="font-size:12px;margin-top:4px">
            When enabled and a VPN IP exists, the system will connect via VPN.
          </div>
        </div>

        <div>
          <label class="label">Name</label>
          <input class="input" name="name" value="{{ $router->name }}" required>
        </div>

        <div>
          <label class="label">Site</label>
          <input class="input" name="site" value="{{ $router->site }}">
        </div>

        <div>
          <label class="label">Host (IP or DDNS)</label>
          <input class="input" name="host" value="{{ $router->host }}" required>
          <div class="muted" style="font-size:12px;margin-top:4px">
            Example: <code>41.xx.xx.xx</code> or <code>server3.remotemikrotik.com</code>
          </div>
        </div>

        <div>
          <label class="label">API Port</label>
          <input class="input" type="number" name="api_port" value="{{ $router->api_port ?? 8728 }}">
          <div class="muted" style="font-size:12px;margin-top:4px">
            Default: 8728 (or 8729 if using API-SSL).
          </div>
        </div>

        <div>
          <label class="label">Username</label>
          <input class="input" name="username" value="{{ $router->username }}" required>
        </div>

        <div>
          <label class="label">Password</label>
          <input class="input" type="password" name="password" value="{{ $router->password }}" required>
        </div>

        <div>
          <label class="label">TLS (API-SSL)</label>
          <select class="input" name="use_tls">
            <option value="0" @selected(!$router->use_tls)>No</option>
            <option value="1" @selected($router->use_tls)>Yes</option>
          </select>
        </div>
      </div>

      {{-- Test connection row --}}
      <div style="margin-top:16px;display:flex;align-items:center;gap:10px">
        <button type="button" id="btn-test-router" class="btn-ghost">
          Test Connection
        </button>
        <div id="router-test-result" class="muted" style="font-size:13px"></div>
      </div>

      <div style="margin-top:14px;display:flex;gap:8px;justify-content:flex-end">
        <a href="{{ route('routers.index') }}" class="btn-ghost" style="text-decoration:none">Cancel</a>
        <button class="btn">Update</button>
      </div>
    </form>
  </div>

  <script>
    (function(){
      const btn = document.getElementById('btn-test-router');
      const out = document.getElementById('router-test-result');
      if (!btn) return;

      function val(name){
        const el = document.querySelector('[name="'+name+'"]');
        return el ? el.value.trim() : '';
      }
      function tlsVal(){
        const el = document.querySelector('[name="use_tls"]');
        if (!el) return 0;
        const v = (el.value || '').toString().toLowerCase();
        return (v === '1' || v === 'yes') ? 1 : 0;
      }

      async function testConn(){
        out.textContent = 'Testing…';
        btn.disabled = true;

        const payload = {
          host:     val('host'),
          api_port: val('api_port') || 8728,
          username: val('username'),
          password: val('password'),
          use_tls:  tlsVal(),
          _token:   '{{ csrf_token() }}'
        };

        try {
          const res = await fetch('{{ route('routers.test') }}', {
            method: 'POST',
            headers: {
              'X-Requested-With': 'XMLHttpRequest',
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(payload)
          });

          const j = await res.json();

          if (j.ok) {
            out.innerHTML =
              `<span style="color:#10b981;font-weight:700">Connected</span> ` +
              `(${j.ms} ms) — Identity: <b>${j.identity ?? '—'}</b>, ` +
              `Model: <b>${j.model ?? '—'}</b>, CPU: <b>${j.cpu_load ?? '—'}%</b>, ` +
              `Uptime: <b>${j.uptime ?? '—'}</b>`;
          } else {
            out.innerHTML =
              `<span style="color:#ef4444;font-weight:700">Failed:</span> ${j.error || 'Unknown error'}`;
          }
        } catch (e) {
          out.innerHTML =
            `<span style="color:#ef4444;font-weight:700">Failed:</span> ${e.message}`;
        } finally {
          btn.disabled = false;
        }
      }

      btn.addEventListener('click', testConn);
    })();
  </script>
@endsection
