<?php
session_start();
require_once 'includes/config.php';
require_once 'includes/auth.php';

if (!isLoggedIn()) {
    header('Location: login.php');
    exit;
}

$user = getCurrentUser();
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ship Network Admin — <?= htmlspecialchars(SHIP_NAME) ?></title>
<link rel="stylesheet" href="assets/css/tabler-icons.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@tabler/icons-webfont@3/dist/tabler-icons.min.css">
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>

<!-- TOP BAR -->
<div class="topbar">
  <div class="topbar-brand">
    <div class="brand-icon"><i class="ti ti-ship"></i></div>
    <span>Ship Network Admin</span>
  </div>
  <span class="ship-badge"><i class="ti ti-anchor"></i> <?= htmlspecialchars(SHIP_NAME) ?></span>
  <div class="topbar-right">
    <span id="clock" class="clock-text">--:--:--</span>
    <span class="user-badge"><i class="ti ti-user"></i> <?= htmlspecialchars($user['name']) ?></span>
    <button class="btn btn-icon" onclick="switchTab('alerts')" title="Alerts">
      <i class="ti ti-bell"></i>
      <span class="alert-dot" id="alert-dot"></span>
    </button>
    <button class="btn btn-sm btn-primary" onclick="refreshAll()">
      <i class="ti ti-refresh"></i> Refresh
    </button>
    <a href="logout.php" class="btn btn-sm btn-danger">
      <i class="ti ti-logout"></i> Logout
    </a>
  </div>
</div>

<!-- NAV TABS -->
<nav class="navtabs">
  <button class="navtab active" onclick="switchTab('overview')" data-tab="overview">
    <span class="tab-dot dot-green"></span>Overview
  </button>
  <button class="navtab" onclick="switchTab('fortinet')" data-tab="fortinet">
    <span class="tab-dot dot-red"></span>Fortinet
  </button>
  <button class="navtab" onclick="switchTab('aruba')" data-tab="aruba">
    <span class="tab-dot dot-amber"></span>Aruba Instant On
  </button>
  <button class="navtab" onclick="switchTab('starlink')" data-tab="starlink">
    <span class="tab-dot dot-blue"></span>Starlink
  </button>
  <button class="navtab" onclick="switchTab('alerts')" data-tab="alerts">
    <span class="tab-dot dot-red"></span>Alerts
    <span class="badge-count" id="alert-count-badge">0</span>
  </button>
  <button class="navtab" onclick="switchTab('ai')" data-tab="ai">
    <span class="tab-dot dot-purple"></span>AI Asisten
  </button>
  <button class="navtab" onclick="switchTab('settings')" data-tab="settings">
    <span class="tab-dot dot-gray"></span>Pengaturan
  </button>
</nav>

<div class="content">

<!-- ============================
     TAB: OVERVIEW
     ============================ -->
<div id="tab-overview" class="tab-pane active">
  <div class="metric-grid">
    <div class="mcard">
      <div class="mcard-label">Fortinet</div>
      <div class="mcard-val green"><i class="ti ti-shield-check"></i> <span id="ov-ft-status">--</span></div>
      <div class="mcard-sub" id="ov-ft-sub">Memuat...</div>
    </div>
    <div class="mcard">
      <div class="mcard-label">AP Online</div>
      <div class="mcard-val blue"><span id="ov-ap-count">--</span></div>
      <div class="mcard-sub" id="ov-ap-sub">Memuat...</div>
    </div>
    <div class="mcard">
      <div class="mcard-label">Starlink</div>
      <div class="mcard-val green"><span id="ov-sl-status">--</span></div>
      <div class="mcard-sub" id="ov-sl-sub">Memuat...</div>
    </div>
    <div class="mcard">
      <div class="mcard-label">Alert Aktif</div>
      <div class="mcard-val red"><span id="ov-alert-count">--</span></div>
      <div class="mcard-sub" id="ov-alert-sub">Memuat...</div>
    </div>
  </div>

  <div class="grid-2col">
    <div class="card">
      <div class="card-title"><i class="ti ti-activity"></i> Status perangkat</div>
      <div id="ov-device-list">
        <div class="loading-row">Memuat data perangkat...</div>
      </div>
    </div>
    <div class="card">
      <div class="card-title"><i class="ti ti-chart-bar"></i> Bandwidth realtime</div>
      <div id="ov-bandwidth">
        <div class="bw-row">
          <span class="bw-label">Download</span>
          <div class="bw-bar-wrap"><div class="bw-bar bw-blue" id="bar-dl" style="width:0%"></div></div>
          <span class="bw-val" id="val-dl">-- Mbps</span>
        </div>
        <div class="bw-row">
          <span class="bw-label">Upload</span>
          <div class="bw-bar-wrap"><div class="bw-bar bw-teal" id="bar-ul" style="width:0%"></div></div>
          <span class="bw-val" id="val-ul">-- Mbps</span>
        </div>
        <div class="bw-row">
          <span class="bw-label">CPU FortiGate</span>
          <div class="bw-bar-wrap"><div class="bw-bar bw-amber" id="bar-cpu" style="width:0%"></div></div>
          <span class="bw-val" id="val-cpu">--%</span>
        </div>
        <div class="bw-row">
          <span class="bw-label">Memory FortiGate</span>
          <div class="bw-bar-wrap"><div class="bw-bar bw-amber" id="bar-mem" style="width:0%"></div></div>
          <span class="bw-val" id="val-mem">--%</span>
        </div>
      </div>
    </div>
  </div>

  <div class="card">
    <div class="card-title"><i class="ti ti-clock"></i> Log aktivitas terkini</div>
    <div class="mini-log" id="ov-log">
      <div class="log-info">Sistem dimulai — menghubungkan ke perangkat...</div>
    </div>
  </div>
</div>

<!-- ============================
     TAB: FORTINET
     ============================ -->
<div id="tab-fortinet" class="tab-pane">
  <div class="sub-tabs">
    <button class="sub-tab active" onclick="switchSubTab('fortinet','status')">Status</button>
    <button class="sub-tab" onclick="switchSubTab('fortinet','policy')">Firewall Policy</button>
    <button class="sub-tab" onclick="switchSubTab('fortinet','vpn')">VPN</button>
    <button class="sub-tab" onclick="switchSubTab('fortinet','cli')">CLI Terminal</button>
  </div>

  <div id="ft-status" class="sub-pane active">
    <div class="metric-grid">
      <div class="mcard"><div class="mcard-label">Model</div><div class="mcard-val sm" id="ft-model">--</div><div class="mcard-sub" id="ft-os">--</div></div>
      <div class="mcard"><div class="mcard-label">Uptime</div><div class="mcard-val sm" id="ft-uptime">--</div><div class="mcard-sub" id="ft-boot">--</div></div>
      <div class="mcard"><div class="mcard-label">Sesi aktif</div><div class="mcard-val" id="ft-sess">--</div><div class="mcard-sub">max 500k</div></div>
      <div class="mcard"><div class="mcard-label">Threat blocked</div><div class="mcard-val red" id="ft-threat">--</div><div class="mcard-sub">hari ini</div></div>
    </div>
    <div class="grid-2col">
      <div class="card">
        <div class="card-title"><i class="ti ti-network"></i> Interface</div>
        <div id="ft-interfaces"><div class="loading-row">Memuat...</div></div>
      </div>
      <div class="card">
        <div class="card-title"><i class="ti ti-shield"></i> Status keamanan</div>
        <div id="ft-security"><div class="loading-row">Memuat...</div></div>
      </div>
    </div>
  </div>

  <div id="ft-policy" class="sub-pane">
    <div class="card">
      <div class="card-title">
        <i class="ti ti-list"></i> Firewall policy
        <button class="btn btn-sm btn-primary ml-auto" onclick="showPolicyModal()">
          <i class="ti ti-plus"></i> Tambah Policy
        </button>
      </div>
      <div class="table-wrap">
        <table class="data-table" id="policy-table">
          <thead>
            <tr><th>#</th><th>Nama</th><th>Sumber</th><th>Tujuan</th><th>Aksi</th><th>Status</th><th>Kelola</th></tr>
          </thead>
          <tbody id="policy-tbody">
            <tr><td colspan="7" class="loading-row">Memuat policy...</td></tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <div id="ft-vpn" class="sub-pane">
    <div class="card">
      <div class="card-title"><i class="ti ti-lock"></i> VPN Tunnel</div>
      <div id="vpn-list"><div class="loading-row">Memuat VPN...</div></div>
    </div>
  </div>

  <div id="ft-cli" class="sub-pane">
    <div class="card">
      <div class="card-title"><i class="ti ti-terminal"></i> FortiGate CLI</div>
      <div class="cli-output" id="ft-cli-out">FortiGate # <span class="cli-cursor">_</span></div>
      <div class="cli-row">
        <span class="cli-prefix">FortiGate #</span>
        <input type="text" class="cli-input" id="ft-cli-inp" placeholder="get system status, diag debug, get router info..." onkeydown="if(event.key==='Enter')runFtCLI()">
        <button class="btn btn-sm btn-primary" onclick="runFtCLI()"><i class="ti ti-player-play"></i> Run</button>
      </div>
      <div class="quick-cmds">
        <button class="btn btn-xs" onclick="setCLI('get sys perf stat')">perf stat</button>
        <button class="btn btn-xs" onclick="setCLI('get router info routing-table all')">routing table</button>
        <button class="btn btn-xs" onclick="setCLI('diag sys session stat')">session stat</button>
        <button class="btn btn-xs" onclick="setCLI('get vpn ipsec tunnel summary')">vpn summary</button>
        <button class="btn btn-xs" onclick="setCLI('get system interface physical')">interfaces</button>
      </div>
    </div>
  </div>
</div>

<!-- ============================
     TAB: ARUBA
     ============================ -->
<div id="tab-aruba" class="tab-pane">
  <div class="metric-grid">
    <div class="mcard"><div class="mcard-label">Total AP</div><div class="mcard-val blue" id="ar-total-ap">--</div><div class="mcard-sub" id="ar-ap-sub">--</div></div>
    <div class="mcard"><div class="mcard-label">Total klien</div><div class="mcard-val" id="ar-clients">--</div><div class="mcard-sub">Wi-Fi aktif</div></div>
    <div class="mcard"><div class="mcard-label">SSID aktif</div><div class="mcard-val" id="ar-ssid">--</div><div class="mcard-sub" id="ar-ssid-names">--</div></div>
    <div class="mcard"><div class="mcard-label">Avg utilization</div><div class="mcard-val amber" id="ar-util">--%</div><div class="mcard-sub">2.4GHz avg</div></div>
  </div>

  <div class="card">
    <div class="card-title"><i class="ti ti-router"></i> Daftar Access Point</div>
    <div class="table-wrap">
      <table class="data-table" id="ap-table">
        <thead>
          <tr><th>Nama AP</th><th>Model</th><th>IP</th><th>Klien</th><th>Band</th><th>Utilization</th><th>Status</th><th>Aksi</th></tr>
        </thead>
        <tbody id="ap-tbody">
          <tr><td colspan="8" class="loading-row">Memuat AP...</td></tr>
        </tbody>
      </table>
    </div>
  </div>

  <div class="card">
    <div class="card-title"><i class="ti ti-wifi"></i> SSID / Network</div>
    <div id="ssid-list"><div class="loading-row">Memuat SSID...</div></div>
  </div>
</div>

<!-- ============================
     TAB: STARLINK
     ============================ -->
<div id="tab-starlink" class="tab-pane">
  <div class="metric-grid">
    <div class="mcard">
      <div class="mcard-label">Status terminal</div>
      <div class="mcard-val green" id="sl-status"><i class="ti ti-satellite"></i> --</div>
      <div class="mcard-sub" id="sl-hw">--</div>
    </div>
    <div class="mcard"><div class="mcard-label">Latency</div><div class="mcard-val" id="sl-lat">-- ms</div><div class="mcard-sub" id="sl-lat-avg">--</div></div>
    <div class="mcard"><div class="mcard-label">Download</div><div class="mcard-val blue" id="sl-dl">-- Mbps</div><div class="mcard-sub">realtime</div></div>
    <div class="mcard"><div class="mcard-label">Upload</div><div class="mcard-val teal" id="sl-ul">-- Mbps</div><div class="mcard-sub">realtime</div></div>
  </div>

  <div class="grid-2col">
    <div class="card">
      <div class="card-title"><i class="ti ti-antenna"></i> Kualitas sinyal</div>
      <div id="sl-signal"><div class="loading-row">Memuat...</div></div>
    </div>
    <div class="card">
      <div class="card-title"><i class="ti ti-satellite"></i> Info terminal</div>
      <div id="sl-info"><div class="loading-row">Memuat...</div></div>
    </div>
  </div>

  <div class="card">
    <div class="card-title"><i class="ti ti-chart-line"></i> Histori throughput (24 jam)</div>
    <canvas id="sl-chart" height="80"></canvas>
  </div>
</div>

<!-- ============================
     TAB: ALERTS
     ============================ -->
<div id="tab-alerts" class="tab-pane">
  <div class="alerts-header">
    <span id="alert-summary-text" class="text-muted">Memuat alerts...</span>
    <button class="btn btn-sm" onclick="clearAllAlerts()"><i class="ti ti-check"></i> Tandai semua dibaca</button>
  </div>
  <div id="alerts-container">
    <div class="loading-row">Memuat alerts...</div>
  </div>
</div>

<!-- ============================
     TAB: AI ASISTEN
     ============================ -->
<div id="tab-ai" class="tab-pane">
  <div class="card">
    <div class="card-title"><i class="ti ti-robot"></i> AI Network Asisten</div>
    <div class="ai-quick-btns">
      <button class="btn btn-xs" onclick="quickAI('Ringkasan status jaringan kapal saat ini dan apa yang perlu diperhatikan?')">Ringkasan status</button>
      <button class="btn btn-xs" onclick="quickAI('Best practice segmentasi VLAN untuk jaringan kapal dengan Fortinet dan Aruba?')">Best practice VLAN</button>
      <button class="btn btn-xs" onclick="quickAI('Cara setup failover otomatis Starlink ke 4G backup di FortiGate?')">Setup failover</button>
      <button class="btn btn-xs" onclick="quickAI('Cara hardening keamanan FortiGate untuk lingkungan maritim?')">Hardening maritim</button>
      <button class="btn btn-xs" onclick="quickAI('Bagaimana cara optimasi QoS di FortiGate untuk prioritas VSAT/Starlink di kapal?')">Optimasi QoS</button>
    </div>
    <textarea id="ai-question" class="ai-textarea" placeholder="Tanya tentang Fortinet, Aruba Instant On, Starlink, troubleshooting, konfigurasi, best practice jaringan kapal..."></textarea>
    <div class="ai-actions">
      <button class="btn btn-primary" id="ai-send-btn" onclick="sendAIQuestion()">
        <i class="ti ti-send"></i> Tanya AI
      </button>
      <button class="btn" onclick="document.getElementById('ai-question').value=''">Bersihkan</button>
    </div>
  </div>
  <div id="ai-loading" class="ai-loading" style="display:none">
    <div class="spinner"></div> AI sedang menganalisis...
  </div>
  <div id="ai-response-card" class="card" style="display:none">
    <div class="card-title"><i class="ti ti-message-circle"></i> Jawaban AI</div>
    <div id="ai-response-text" class="ai-response"></div>
  </div>
  <div id="ai-history-wrap" style="display:none;margin-top:12px">
    <div class="card-title"><i class="ti ti-history"></i> Riwayat sesi</div>
    <div id="ai-history-list"></div>
  </div>
</div>

<!-- ============================
     TAB: SETTINGS
     ============================ -->
<div id="tab-settings" class="tab-pane">
  <form method="POST" action="api/save_settings.php" id="settings-form">
    <div class="grid-2col">
      <div class="card">
        <div class="card-title"><i class="ti ti-shield"></i> Koneksi Fortinet</div>
        <div class="form-group">
          <label>Host / IP FortiGate</label>
          <input type="text" name="ft_host" value="<?= htmlspecialchars($config['ft_host'] ?? '192.168.1.1') ?>" placeholder="192.168.1.1">
        </div>
        <div class="form-group">
          <label>Port HTTPS</label>
          <input type="number" name="ft_port" value="<?= htmlspecialchars($config['ft_port'] ?? '443') ?>" placeholder="443">
        </div>
        <div class="form-group">
          <label>Username</label>
          <input type="text" name="ft_user" value="<?= htmlspecialchars($config['ft_user'] ?? '') ?>" placeholder="admin">
        </div>
        <div class="form-group">
          <label>Password</label>
          <input type="password" name="ft_pass" placeholder="(tidak berubah jika kosong)">
        </div>
        <div class="form-group">
          <label>API Key (REST API)</label>
          <input type="text" name="ft_api_key" value="<?= htmlspecialchars($config['ft_api_key'] ?? '') ?>" placeholder="FortiGate API key">
        </div>
        <button type="button" class="btn btn-primary btn-sm" onclick="testDevice('fortinet')">
          <i class="ti ti-plug"></i> Test Koneksi
        </button>
        <span id="ft-test-msg" class="test-msg"></span>
      </div>

      <div class="card">
        <div class="card-title"><i class="ti ti-wifi"></i> Koneksi Aruba Instant On</div>
        <div class="form-group">
          <label>Client ID (OAuth)</label>
          <input type="text" name="ar_client_id" value="<?= htmlspecialchars($config['ar_client_id'] ?? '') ?>" placeholder="OAuth Client ID">
        </div>
        <div class="form-group">
          <label>Client Secret</label>
          <input type="password" name="ar_client_secret" placeholder="(tidak berubah jika kosong)">
        </div>
        <div class="form-group">
          <label>Site ID</label>
          <input type="text" name="ar_site_id" value="<?= htmlspecialchars($config['ar_site_id'] ?? '') ?>" placeholder="Site ID dari Aruba portal">
        </div>
        <div class="form-group">
          <label>Region</label>
          <select name="ar_region">
            <option value="ap" <?= ($config['ar_region']??'')=='ap'?'selected':'' ?>>Asia Pacific</option>
            <option value="us" <?= ($config['ar_region']??'')=='us'?'selected':'' ?>>United States</option>
            <option value="eu" <?= ($config['ar_region']??'')=='eu'?'selected':'' ?>>Europe</option>
          </select>
        </div>
        <button type="button" class="btn btn-primary btn-sm" onclick="testDevice('aruba')">
          <i class="ti ti-plug"></i> Test Koneksi
        </button>
        <span id="ar-test-msg" class="test-msg"></span>
      </div>

      <div class="card">
        <div class="card-title"><i class="ti ti-satellite"></i> Koneksi Starlink</div>
        <div class="form-group">
          <label>Router IP (lokal LAN)</label>
          <input type="text" name="sl_host" value="<?= htmlspecialchars($config['sl_host'] ?? '192.168.100.1') ?>" placeholder="192.168.100.1">
        </div>
        <div class="form-group">
          <label>gRPC Port</label>
          <input type="number" name="sl_grpc_port" value="<?= htmlspecialchars($config['sl_grpc_port'] ?? '9200') ?>" placeholder="9200">
        </div>
        <div class="form-group">
          <label>Starlink API Token (Business)</label>
          <input type="password" name="sl_token" placeholder="(tidak berubah jika kosong)">
        </div>
        <button type="button" class="btn btn-primary btn-sm" onclick="testDevice('starlink')">
          <i class="ti ti-plug"></i> Test Koneksi
        </button>
        <span id="sl-test-msg" class="test-msg"></span>
      </div>

      <div class="card">
        <div class="card-title"><i class="ti ti-bell"></i> Threshold Alert</div>
        <div class="form-group">
          <label>Email notifikasi</label>
          <input type="email" name="alert_email" value="<?= htmlspecialchars($config['alert_email'] ?? '') ?>" placeholder="admin@kapal.com">
        </div>
        <div class="form-group">
          <label>CPU Fortinet threshold (%)</label>
          <input type="number" name="thresh_cpu" value="<?= htmlspecialchars($config['thresh_cpu'] ?? '80') ?>" min="1" max="100">
        </div>
        <div class="form-group">
          <label>AP utilization threshold (%)</label>
          <input type="number" name="thresh_ap" value="<?= htmlspecialchars($config['thresh_ap'] ?? '80') ?>" min="1" max="100">
        </div>
        <div class="form-group">
          <label>Starlink latency alert (ms)</label>
          <input type="number" name="thresh_latency" value="<?= htmlspecialchars($config['thresh_latency'] ?? '150') ?>" min="1">
        </div>
        <div class="form-group">
          <label>Nama kapal</label>
          <input type="text" name="ship_name" value="<?= htmlspecialchars(SHIP_NAME) ?>" placeholder="KM Nama Kapal">
        </div>
      </div>
    </div>

    <div class="card" style="margin-top:0">
      <div class="card-title"><i class="ti ti-key"></i> Anthropic API (AI Asisten)</div>
      <div class="form-group" style="max-width:400px">
        <label>Anthropic API Key</label>
        <input type="password" name="anthropic_key" placeholder="sk-ant-... (tidak berubah jika kosong)">
        <small class="form-hint">Diperlukan untuk fitur AI Asisten. Dapatkan di console.anthropic.com</small>
      </div>
    </div>

    <div style="display:flex;gap:8px;margin-top:12px">
      <button type="submit" class="btn btn-primary"><i class="ti ti-device-floppy"></i> Simpan semua pengaturan</button>
      <button type="button" class="btn" onclick="exportConfig()"><i class="ti ti-download"></i> Export config</button>
    </div>
    <div id="save-msg" class="save-msg" style="display:none"></div>
  </form>
</div>

</div><!-- .content -->

<!-- MODAL: Tambah Policy -->
<div id="policy-modal" class="modal-overlay" style="display:none" onclick="if(event.target===this)this.style.display='none'">
  <div class="modal-box">
    <div class="modal-header">
      <h3>Tambah Firewall Policy</h3>
      <button class="btn-close" onclick="document.getElementById('policy-modal').style.display='none'"><i class="ti ti-x"></i></button>
    </div>
    <div class="modal-body">
      <div class="form-group">
        <label>Nama policy</label>
        <input type="text" id="pm-name" placeholder="LAN-to-WAN">
      </div>
      <div class="grid-2col" style="gap:8px">
        <div class="form-group">
          <label>Interface sumber</label>
          <select id="pm-src-intf">
            <option>lan</option><option>dmz</option><option>crew_vlan</option><option>passenger_vlan</option><option>ot_vlan</option>
          </select>
        </div>
        <div class="form-group">
          <label>Interface tujuan</label>
          <select id="pm-dst-intf">
            <option>wan1</option><option>wan2</option><option>lan</option><option>dmz</option>
          </select>
        </div>
      </div>
      <div class="form-group">
        <label>Aksi</label>
        <select id="pm-action">
          <option value="accept">ALLOW</option>
          <option value="deny">DENY</option>
        </select>
      </div>
      <div class="form-group">
        <label>NAT</label>
        <select id="pm-nat">
          <option value="enable">Enable</option>
          <option value="disable">Disable</option>
        </select>
      </div>
      <div class="form-group">
        <label>Log traffic</label>
        <select id="pm-log">
          <option value="all">All</option>
          <option value="utm">UTM only</option>
          <option value="disable">Disable</option>
        </select>
      </div>
    </div>
    <div class="modal-footer">
      <button class="btn" onclick="document.getElementById('policy-modal').style.display='none'">Batal</button>
      <button class="btn btn-primary" onclick="submitPolicy()"><i class="ti ti-check"></i> Tambah Policy</button>
    </div>
  </div>
</div>

<script src="assets/js/chart.umd.min.js" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js'"></script>
<script src="assets/js/app.js"></script>
</body>
</html>
