<!DOCTYPE html>
<html lang="<%= lang || 'id' %>">
<head>
  <meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
  <title><%= t('admin.nav.router_management', 'Manajemen Router') %> | <%= company %></title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
  <link rel="stylesheet" href="/css/admin.css">
  <style>
    .mtabs { display: flex; gap: 10px; margin-bottom: 14px; border-bottom: 1px solid var(--border); padding-bottom: 10px; }
    .mtab { padding: 8px 14px; border-radius: 8px; cursor: pointer; color: var(--muted); transition: all 0.2s; font-weight: 700; text-decoration: none; }
    .mtab:hover { background: rgba(255,255,255,0.06); color: var(--text); }
    .mtab.active { background: var(--primary); color: white; }
  </style>
</head>
<body>
<%- include('partials/sidebar', { activePage: 'mikrotik', company }) %>
<div class="mw">
  <div class="topbar">
    <div class="tb-title"><button class="hb-menu" onclick="toggleSidebar()"><i class="bi bi-list"></i></button><i class="bi bi-hdd-network"></i> <%= t('admin.nav.router_management', 'Manajemen Router') %></div>
    <div class="tb-right">
      <span class="adm-badge"><i class="bi bi-person-fill"></i> <%= (typeof session !== 'undefined' && session.isCashier) ? t('admin.role.cashier', 'Kasir') : t('admin.role.admin', 'Admin') %></span>
      <a href="/admin/logout" class="btn btn-g btn-sm"><i class="bi bi-box-arrow-left"></i></a>
    </div>
  </div>
  <div class="page">
    <% const mTab = 'routers'; %>

    <% if (msg) { %>
    <div class="alert alert-<%= msg.type === 'success' ? 's' : 'd' %>">
      <i class="bi bi-<%= msg.type === 'success' ? 'check-circle' : 'exclamation-circle' %>"></i> <%= msg.text %>
    </div>
    <% } %>

    <div class="mtabs">
      <a href="/admin/mikrotik" class="mtab <%= mTab==='monitoring' ? 'active' : '' %>"><i class="bi bi-router"></i> Monitoring</a>
      <a href="/admin/vouchers" class="mtab <%= mTab==='vouchers' ? 'active' : '' %>"><i class="bi bi-ticket-perforated"></i> Voucher Hotspot</a>
      <a href="/admin/routers" class="mtab <%= mTab==='routers' ? 'active' : '' %>"><i class="bi bi-hdd-network"></i> Router</a>
    </div>

    <div class="card">
      <div class="card-hd">
        <h6><i class="bi bi-hdd-network"></i> <%= t('admin.routers.list_title', 'Daftar Router MikroTik') %> (<%= routers.length %>)</h6>
        <div style="display:flex;gap:8px;flex-wrap:wrap">
          <button type="button" class="btn btn-outline-light btn-sm" onclick="openIsolirScriptModal()"><i class="bi bi-filetype-txt"></i> <%= t('admin.routers.isolir_script_btn', 'Script halaman isolir') %></button>
          <button class="btn btn-p btn-sm" onclick="openModal('addModal')"><i class="bi bi-plus-lg"></i> <%= t('admin.routers.add', 'Tambah Router') %></button>
        </div>
      </div>
      <div class="tbl-wrap">
        <table class="dtbl">
          <thead>
            <tr>
              <th>#</th>
              <th><%= t('admin.routers.table.name', 'Nama Router') %></th>
              <th><%= t('admin.routers.table.host', 'Host / IP') %></th>
              <th><%= t('admin.routers.table.port', 'Port') %></th>
              <th><%= t('admin.routers.table.username', 'Username') %></th>
              <th><%= t('admin.routers.table.status', 'Status') %></th>
              <th><%= t('common.actions', 'Aksi') %></th>
            </tr>
          </thead>
          <tbody>
          <% if (routers.length === 0) { %>
            <tr><td colspan="7" class="text-center text-muted" style="padding:32px"><%= t('admin.routers.empty', 'Belum ada router yang ditambahkan') %></td></tr>
          <% } %>
          <% routers.forEach((r, i) => { %>
            <tr>
              <td class="text-muted"><%= i+1 %></td>
              <td class="fw6"><%= r.name %></td>
              <td><%= r.host %></td>
              <td><%= r.port %></td>
              <td><%= r.user %></td>
              <td>
                <% if (r.is_active) { %><span class="badge bs"><%= t('common.active', 'Aktif') %></span><% } else { %><span class="badge bm"><%= t('common.inactive', 'Nonaktif') %></span><% } %>
              </td>
              <td>
                <button class="btn btn-g btn-icon btn-sm" title="<%= t('admin.routers.actions.test', 'Test Koneksi') %>" onclick="testConn(<%= r.id %>)"><i class="bi bi-plug"></i></button>
                <button class="btn btn-g btn-icon btn-sm" title="Setup Firewall Isolir" onclick="setupFirewall(<%= r.id %>)"><i class="bi bi-shield-lock"></i></button>
                <button class="btn btn-g btn-icon btn-sm" title="<%= t('common.edit', 'Edit') %>" onclick="editRouter(<%= i %>)"><i class="bi bi-pencil"></i></button>
                <form method="POST" action="/admin/routers/<%= r.id %>/delete" style="display:inline" onsubmit="return confirm('<%= t('admin.routers.confirm.delete', 'Hapus router ini?') %>')">
                  <button class="btn btn-d btn-icon btn-sm" title="<%= t('common.delete', 'Hapus') %>"><i class="bi bi-trash"></i></button>
                </form>
              </td>
            </tr>
          <% }) %>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<!-- Modal Script Isolir Portal -->
<div class="mo" id="isolirScriptModal">
  <div class="mb" style="max-width:720px">
    <div class="mh"><span class="mt"><i class="bi bi-shield-lock"></i> <%= t('admin.routers.isolir_script_title', 'Script RouterOS — halaman isolir') %></span><button class="mc" onclick="closeModal('isolirScriptModal')">&times;</button></div>
    <div class="mbody">
      <p class="small text-muted mb-2"><%= t('admin.routers.isolir_script_help', 'Dari Pengaturan → URL aplikasi (app_url). Salin ke Winbox Terminal atau import .rsc. Sesuaikan jika bentrok dengan rule yang ada.') %></p>
      <div id="isolir-script-meta" class="small text-muted mb-2"></div>
      <textarea id="isolir-script-body" class="fc" readonly rows="18" style="width:100%;font-family:ui-monospace,monospace;font-size:12px"></textarea>
    </div>
    <div class="mf">
      <button type="button" class="btn btn-g" onclick="closeModal('isolirScriptModal')"><%= t('common.close', 'Tutup') %></button>
      <button type="button" class="btn btn-p" onclick="copyIsolirScript()"><i class="bi bi-clipboard"></i> <%= t('admin.routers.isolir_script_copy', 'Salin script') %></button>
    </div>
  </div>
</div>

<!-- Modal Tambah -->
<div class="mo" id="addModal">
  <div class="mb">
    <div class="mh"><span class="mt"><i class="bi bi-hdd-network"></i> <%= t('admin.routers.add', 'Tambah Router') %></span><button class="mc" onclick="closeModal('addModal')">&times;</button></div>
    <form method="POST" action="/admin/routers">
      <div class="mbody">
        <div class="form-row">
          <div class="fg"><label class="fl"><%= t('admin.routers.form.name', 'Nama Router') %> *</label><input class="fc" name="name" required placeholder="<%= t('admin.routers.form.name_placeholder', 'Contoh: Router Pusat') %>"></div>
          <div class="fg"><label class="fl"><%= t('admin.routers.form.host', 'Host / IP') %> *</label><input class="fc" name="host" required placeholder="192.168.1.1"></div>
        </div>
        <div class="form-row">
          <div class="fg"><label class="fl"><%= t('admin.routers.form.api_port', 'Port API') %> *</label><input class="fc" name="port" type="number" value="8728" required></div>
          <div class="fg"><label class="fl"><%= t('admin.routers.form.username', 'Username MikroTik') %> *</label><input class="fc" name="user" required></div>
        </div>
        <div class="form-row">
          <div class="fg"><label class="fl"><%= t('admin.routers.form.password', 'Password') %> *</label><input class="fc" name="password" type="password" required></div>
          <div class="fg">
            <label class="fl"><%= t('admin.routers.form.status', 'Status') %></label>
            <select class="fs" name="is_active">
              <option value="1"><%= t('common.active', 'Aktif') %></option>
              <option value="0"><%= t('common.inactive', 'Nonaktif') %></option>
            </select>
          </div>
        </div>
        <div class="fg"><label class="fl"><%= t('admin.routers.form.description', 'Deskripsi / Lokasi') %></label><textarea class="fc" name="description" placeholder="<%= t('admin.routers.form.optional', 'Opsional...') %>"></textarea></div>
      </div>
      <div class="mf">
        <button type="button" class="btn btn-g" onclick="closeModal('addModal')"><%= t('common.cancel', 'Batal') %></button>
        <button type="submit" class="btn btn-p"><i class="bi bi-check-lg"></i> <%= t('admin.routers.actions.save', 'Simpan Router') %></button>
      </div>
    </form>
  </div>
</div>

<!-- Modal Edit -->
<div class="mo" id="editModal">
  <div class="mb">
    <div class="mh"><span class="mt"><i class="bi bi-pencil"></i> <%= t('admin.routers.actions.edit_title', 'Edit Router') %></span><button class="mc" onclick="closeModal('editModal')">&times;</button></div>
    <form method="POST" id="editForm">
      <div class="mbody">
        <div class="form-row">
          <div class="fg"><label class="fl"><%= t('admin.routers.form.name', 'Nama Router') %> *</label><input class="fc" name="name" id="e_name" required></div>
          <div class="fg"><label class="fl"><%= t('admin.routers.form.host', 'Host / IP') %> *</label><input class="fc" name="host" id="e_host" required></div>
        </div>
        <div class="form-row">
          <div class="fg"><label class="fl"><%= t('admin.routers.form.api_port', 'Port API') %> *</label><input class="fc" name="port" id="e_port" type="number" required></div>
          <div class="fg"><label class="fl"><%= t('admin.routers.form.username', 'Username MikroTik') %> *</label><input class="fc" name="user" id="e_user" required></div>
        </div>
        <div class="form-row">
          <div class="fg"><label class="fl"><%= t('admin.routers.form.password_keep', 'Password (Kosongkan jika tetap)') %></label><input class="fc" name="password" type="password"></div>
          <div class="fg">
            <label class="fl"><%= t('admin.routers.form.status', 'Status') %></label>
            <select class="fs" name="is_active" id="e_active">
              <option value="1"><%= t('common.active', 'Aktif') %></option>
              <option value="0"><%= t('common.inactive', 'Nonaktif') %></option>
            </select>
          </div>
        </div>
        <div class="fg"><label class="fl"><%= t('admin.routers.form.description', 'Deskripsi / Lokasi') %></label><textarea class="fc" name="description" id="e_desc"></textarea></div>
      </div>
      <div class="mf">
        <button type="button" class="btn btn-g" onclick="closeModal('editModal')"><%= t('common.cancel', 'Batal') %></button>
        <button type="submit" class="btn btn-p"><i class="bi bi-check-lg"></i> <%= t('admin.routers.actions.update', 'Update Router') %></button>
      </div>
    </form>
  </div>
</div>

<script id="routers-data" type="application/json"><%- JSON.stringify(routers) %></script>
<script>
const routersData = JSON.parse(document.getElementById('routers-data').textContent);
const I18N = {
  testConfirm: "<%= t('admin.routers.confirm.test', 'Test koneksi ke router ini?') %>",
  systemError: "<%= t('admin.routers.js.system_error', 'Terjadi kesalahan sistem.') %>"
};
function openModal(id){document.getElementById(id).classList.add('show')}
function closeModal(id){document.getElementById(id).classList.remove('show')}

function editRouter(idx) {
  const r = routersData[idx];
  document.getElementById('editForm').action = '/admin/routers/' + r.id + '/update';
  document.getElementById('e_name').value = r.name;
  document.getElementById('e_host').value = r.host;
  document.getElementById('e_port').value = r.port;
  document.getElementById('e_user').value = r.user;
  document.getElementById('e_active').value = r.is_active;
  document.getElementById('e_desc').value = r.description || '';
  openModal('editModal');
}

async function testConn(id) {
  if(!confirm(I18N.testConfirm)) return;
  try {
    const res = await fetch('/admin/api/routers/' + id + '/test');
    const data = await res.json();
    alert(data.success ? '✅ ' + data.message : '❌ ' + data.error);
  } catch (e) { alert(I18N.systemError); }
}

async function setupFirewall(id) {
  if(!confirm('Setup otomatis Firewall Isolir di MikroTik? Ini akan menambahkan Address List dan Rule NAT/Filter.')) return;
  try {
    const res = await fetch('/admin/api/routers/' + id + '/setup-firewall', { method: 'POST' });
    const data = await res.json();
    alert(data.success ? '✅ ' + data.message : '❌ ' + data.error);
  } catch (e) { alert(I18N.systemError); }
}

async function openIsolirScriptModal() {
  const ta = document.getElementById('isolir-script-body');
  const meta = document.getElementById('isolir-script-meta');
  ta.value = '<%= t('common.loading', 'Memuat...') %>';
  meta.textContent = '';
  openModal('isolirScriptModal');
  try {
    const res = await fetch('/admin/api/isolir-portal-script');
    const data = await res.json();
    if (!data.success) throw new Error(data.error || 'Gagal');
    ta.value = data.script || '';
    meta.textContent = (data.appUrl ? ('app_url: ' + data.appUrl + ' | ') : '') + 'IP: ' + (data.billingIp || '-') + ' | NAT → HTTP:' + (data.httpNatPort ?? '-') + ' HTTPS:' + (data.httpsNatPort ?? '-');
  } catch (e) {
    ta.value = '';
    meta.textContent = e.message || 'Error';
  }
}

function copyIsolirScript() {
  const ta = document.getElementById('isolir-script-body');
  if (!ta || !ta.value) return;
  ta.select();
  document.execCommand('copy');
  alert('<%= t('admin.routers.isolir_script_copied', 'Script disalin ke clipboard.') %>');
}
</script>
</body>
</html>
