<?php
// ============================================================
// FortiGate Daily Report Dashboard
// Upload PDF → Extract → AI Analysis → Dashboard
// ============================================================

define('CLAUDE_API_KEY', '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');   // Ganti dengan API key Claude
define('GROQ_API_KEY',   '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');       // Ganti dengan API key Groq
define('HISTORY_FILE',   __DIR__ . '/data/history.json');
define('UPLOAD_DIR',     __DIR__ . '/uploads/');
define('MAX_FILE_SIZE',  10 * 1024 * 1024); // 10 MB

// ── Bootstrap ──────────────────────────────────────────────
foreach ([__DIR__ . '/data', UPLOAD_DIR] as $dir) {
    if (!is_dir($dir)) mkdir($dir, 0755, true);
}

$action  = $_POST['action']  ?? $_GET['action']  ?? '';
$message = '';
$report  = null;

// ── Composer autoload (pdfparser) ──────────────────────────
$autoload = __DIR__ . '/vendor/autoload.php';
if (!file_exists($autoload)) {
    // Tampilkan instruksi install jika belum ada
    $needsComposer = true;
} else {
    require_once $autoload;
    $needsComposer = false;
}

// ── Handle: Upload & Analyze ───────────────────────────────
if ($action === 'upload' && !empty($_FILES['pdf'])) {
    $result = handleUpload($_FILES['pdf']);
    if ($result['success']) {
        $report  = $result['report'];
        $message = ['type' => 'success', 'text' => 'Laporan berhasil dianalisis!'];
    } else {
        $message = ['type' => 'error', 'text' => $result['error']];
    }
}

// ── Handle: Delete history entry ───────────────────────────
if ($action === 'delete' && !empty($_GET['id'])) {
    deleteHistory($_GET['id']);
    header('Location: index.php?deleted=1');
    exit;
}

// ── Handle: View historical report ─────────────────────────
if ($action === 'view' && !empty($_GET['id'])) {
    $report = getHistoryItem($_GET['id']);
}

// ── Load history ───────────────────────────────────────────
$history = loadHistory();

// ============================================================
// FUNCTIONS
// ============================================================

function handleUpload($file) {
    if ($file['error'] !== UPLOAD_ERR_OK)
        return ['success' => false, 'error' => 'Upload gagal. Coba lagi.'];
    if ($file['size'] > MAX_FILE_SIZE)
        return ['success' => false, 'error' => 'File terlalu besar (max 10MB).'];
    if (mime_content_type($file['tmp_name']) !== 'application/pdf')
        return ['success' => false, 'error' => 'File harus berformat PDF.'];

    // Extract text
    $text = extractPdfText($file['tmp_name']);
    if (!$text)
        return ['success' => false, 'error' => 'Gagal membaca isi PDF. Pastikan PDF berisi teks (bukan scan gambar).'];

    // AI Analysis
    $analysis = analyzeWithAI($text);
    if (!$analysis)
        return ['success' => false, 'error' => 'Gagal menghubungi AI. Periksa API key.'];

    // Save
    $report = [
        'id'        => uniqid(),
        'filename'  => htmlspecialchars($file['name']),
        'uploaded'  => date('Y-m-d H:i:s'),
        'analysis'  => $analysis,
        'raw_text'  => substr($text, 0, 3000), // simpan preview
    ];
    saveHistory($report);
    return ['success' => true, 'report' => $report];
}

function extractPdfText($filepath) {
    global $needsComposer;
    if ($needsComposer) return null;
    try {
        $parser   = new \Smalot\PdfParser\Parser();
        $pdf      = $parser->parseFile($filepath);
        $text     = $pdf->getText();
        return strlen(trim($text)) > 100 ? $text : null;
    } catch (Exception $e) {
        return null;
    }
}

function analyzeWithAI($text) {
    $prompt = buildPrompt($text);

    // Try Claude first
    $result = callClaude($prompt);
    if ($result) return $result;

    // Fallback to Groq
    $result = callGroq($prompt);
    return $result;
}

function buildPrompt($text) {
    return "You are a network security analyst. Analyze the following FortiGate report and return ONLY a valid JSON object (no markdown, no extra text) with this exact structure:

{
  \"device\": \"device name\",
  \"period\": \"report period\",
  \"total_traffic_gb\": 0,
  \"total_sessions\": 0,
  \"total_threats\": 0,
  \"attacks\": 0,
  \"threat_items\": [
    {\"name\": \"threat name\", \"level\": \"High/Medium/Low\", \"score\": 0, \"percent\": \"0%\"}
  ],
  \"top_apps\": [
    {\"name\": \"app name\", \"traffic_gb\": 0, \"percent\": \"0%\"}
  ],
  \"web_categories\": [
    {\"name\": \"category\", \"percent\": \"0%\"}
  ],
  \"vpn_threats\": [\"app1\", \"app2\"],
  \"suspicious_domains\": [\"domain1\"],
  \"top_users\": [
    {\"name\": \"username\", \"visits\": 0}
  ],
  \"vpn_tunnels\": [
    {\"name\": \"tunnel\", \"sent_gb\": 0, \"recv_gb\": 0}
  ],
  \"traffic_by_country\": [
    {\"country\": \"country name\", \"traffic_gb\": 0, \"percent\": \"0%\"}
  ],
  \"admin_sessions\": [
    {\"user\": \"admin\", \"interface\": \"https\", \"sessions\": 0, \"changes\": 0}
  ],
  \"failed_admin_logins\": 0,
  \"virus_detected\": false,
  \"recommendations\": [
    {
      \"level\": \"high/medium/low\",
      \"title_id\": \"judul dalam Bahasa Indonesia\",
      \"title_en\": \"title in English\",
      \"desc_id\": \"penjelasan singkat dan jelas dalam Bahasa Indonesia\",
      \"desc_en\": \"concise explanation in English\"
    }
  ],
  \"summary_id\": \"Ringkasan 2-3 kalimat kondisi keamanan jaringan hari ini dalam Bahasa Indonesia.\",
  \"summary_en\": \"2-3 sentence summary of today's network security status in English.\"
}

IMPORTANT: The recommendations array MUST include both Indonesian (title_id, desc_id) and English (title_en, desc_en) fields for every item. Do not use the old 'title' or 'desc' fields.

REPORT DATA:
" . substr($text, 0, 8000);
}

function callClaude($prompt) {
    $payload = json_encode([
        'model'      => 'claude-haiku-4-5',
        'max_tokens' => 2000,
        'messages'   => [['role' => 'user', 'content' => $prompt]],
    ]);
    $response = httpPost('https://api.anthropic.com/v1/messages', $payload, [
        'x-api-key: '    . CLAUDE_API_KEY,
        'anthropic-version: 2023-06-01',
        'content-type: application/json',
    ]);
    if (!$response) return null;
    $data = json_decode($response, true);
    $text = $data['content'][0]['text'] ?? null;
    return $text ? parseJsonResponse($text) : null;
}

function callGroq($prompt) {
    $payload = json_encode([
        'model'    => 'llama-3.3-70b-versatile',
        'messages' => [
            ['role' => 'system', 'content' => 'Kamu analis keamanan jaringan. Selalu balas HANYA dengan JSON valid.'],
            ['role' => 'user',   'content' => $prompt],
        ],
        'max_tokens'  => 2000,
        'temperature' => 0.1,
    ]);
    $response = httpPost('https://api.groq.com/openai/v1/chat/completions', $payload, [
        'Authorization: Bearer ' . GROQ_API_KEY,
        'Content-Type: application/json',
    ]);
    if (!$response) return null;
    $data = json_decode($response, true);
    $text = $data['choices'][0]['message']['content'] ?? null;
    return $text ? parseJsonResponse($text) : null;
}

function parseJsonResponse($text) {
    // Strip markdown fences if any
    $text = preg_replace('/^```(?:json)?\s*/m', '', $text);
    $text = preg_replace('/\s*```$/m', '', $text);
    $text = trim($text);
    $data = json_decode($text, true);
    return (json_last_error() === JSON_ERROR_NONE && is_array($data)) ? $data : null;
}

function httpPost($url, $payload, $headers) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => $payload,
        CURLOPT_HTTPHEADER     => $headers,
        CURLOPT_TIMEOUT        => 60,
        CURLOPT_SSL_VERIFYPEER => true,
    ]);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return ($response && $httpCode === 200) ? $response : null;
}

function loadHistory() {
    if (!file_exists(HISTORY_FILE)) return [];
    $data = json_decode(file_get_contents(HISTORY_FILE), true);
    return is_array($data) ? array_reverse($data) : [];
}

function saveHistory($report) {
    $history = file_exists(HISTORY_FILE)
        ? json_decode(file_get_contents(HISTORY_FILE), true) : [];
    if (!is_array($history)) $history = [];
    $history[] = $report;
    // Keep max 90 entries
    if (count($history) > 90) $history = array_slice($history, -90);
    file_put_contents(HISTORY_FILE, json_encode($history, JSON_PRETTY_PRINT));
}

function getHistoryItem($id) {
    $history = loadHistory();
    foreach ($history as $item) {
        if ($item['id'] === $id) return $item;
    }
    return null;
}

function deleteHistory($id) {
    if (!file_exists(HISTORY_FILE)) return;
    $history = json_decode(file_get_contents(HISTORY_FILE), true);
    if (!is_array($history)) return;
    $history = array_values(array_filter($history, fn($h) => $h['id'] !== $id));
    file_put_contents(HISTORY_FILE, json_encode($history, JSON_PRETTY_PRINT));
}

function levelBadge($level) {
    $map = ['High' => 'danger', 'Medium' => 'warning', 'Low' => 'info'];
    $cls = $map[$level] ?? 'secondary';
    return "<span class=\"badge bg-{$cls}\">{$level}</span>";
}

function recoBadge($level) {
    $map = ['high' => 'danger', 'medium' => 'warning', 'low' => 'info'];
    $cls = $map[strtolower($level)] ?? 'secondary';
    $icons = ['high' => '🔴', 'medium' => '🟡', 'low' => '🔵'];
    $icon = $icons[strtolower($level)] ?? '⚪';
    return "<span class=\"badge bg-{$cls}\">{$icon} " . ucfirst($level) . "</span>";
}

function fmtNum($n) {
    return number_format((float)$n, 0, ',', '.');
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>FortiGate Report Dashboard</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css">
<style>
  :root { --brand: #e85d24; }
  body { background: #f4f6fa; font-size: 14px; }
  .navbar { background: #1a1f36; }
  .navbar-brand { font-weight: 600; color: #fff !important; }
  .navbar-brand span { color: var(--brand); }
  .sidebar { min-height: calc(100vh - 56px); background: #fff; border-right: 1px solid #e5e7eb; }
  .history-item { padding: 10px 14px; border-bottom: 1px solid #f0f0f0; cursor: pointer; transition: background .15s; text-decoration: none; color: inherit; display: block; }
  .history-item:hover { background: #f8f9fa; }
  .history-item.active { background: #fff3ee; border-left: 3px solid var(--brand); }
  .history-date { font-size: 11px; color: #6c757d; }
  .stat-card { border: none; border-radius: 10px; }
  .stat-card .card-body { padding: 1rem 1.2rem; }
  .stat-label { font-size: 12px; color: #6c757d; margin-bottom: 4px; }
  .stat-value { font-size: 22px; font-weight: 600; }
  .section-card { border: none; border-radius: 10px; margin-bottom: 1rem; }
  .section-card .card-header { background: #fff; border-bottom: 1px solid #f0f0f0; font-weight: 600; font-size: 13px; color: #374151; padding: 12px 16px; border-radius: 10px 10px 0 0 !important; }
  .bar-cell { width: 80px; }
  .mini-bar { height: 6px; border-radius: 3px; background: #dee2e6; }
  .mini-bar-fill { height: 6px; border-radius: 3px; }
  .upload-zone { border: 2px dashed #d1d5db; border-radius: 12px; padding: 2.5rem; text-align: center; transition: border-color .2s, background .2s; cursor: pointer; }
  .upload-zone:hover, .upload-zone.dragover { border-color: var(--brand); background: #fff3ee; }
  .upload-zone .icon { font-size: 2.5rem; color: #9ca3af; }
  .badge-vpn { background: #fef3c7; color: #92400e; border: 1px solid #fcd34d; font-weight: 500; }
  .alert-rec { border-left: 4px solid; border-radius: 0 8px 8px 0; }
  .alert-rec.high  { border-color: #dc3545; background: #fff5f5; }
  .alert-rec.medium { border-color: #fd7e14; background: #fff8f0; }
  .alert-rec.low   { border-color: #0dcaf0; background: #f0fbff; }
  .spinner-overlay { display:none; position:fixed; inset:0; background:rgba(0,0,0,.45); z-index:9999; align-items:center; justify-content:center; flex-direction:column; gap:16px; color:#fff; }
  .spinner-overlay.show { display:flex; }
  .empty-state { text-align:center; padding: 3rem 1rem; color: #9ca3af; }
  .needs-setup { background: #fffbeb; border: 1px solid #fcd34d; border-radius: 10px; padding: 1.5rem; }
  @media (max-width: 768px) { .sidebar { min-height: auto; border-right: none; border-bottom: 1px solid #e5e7eb; } }
</style>
</head>
<body>

<!-- Spinner -->
<div class="spinner-overlay" id="spinnerOverlay">
  <div class="spinner-border text-light" style="width:3rem;height:3rem"></div>
  <div style="font-size:15px">Menganalisis laporan dengan AI...</div>
</div>

<!-- Navbar -->
<nav class="navbar navbar-expand-lg px-3 py-2">
  <span class="navbar-brand"><i class="bi bi-shield-check me-2"></i>FortiGate <span>Dashboard</span></span>
  <span class="ms-auto text-white-50" style="font-size:12px"><i class="bi bi-cpu me-1"></i>Claude + Groq AI</span>
</nav>

<div class="container-fluid">
<div class="row">

  <!-- Sidebar: History -->
  <div class="col-md-3 col-lg-2 sidebar px-0">
    <div class="p-3 border-bottom">
      <div class="fw-semibold text-muted" style="font-size:12px;text-transform:uppercase;letter-spacing:.06em">
        <i class="bi bi-clock-history me-1"></i> Riwayat Laporan
      </div>
    </div>

    <?php if (empty($history)): ?>
      <div class="p-3 text-center text-muted" style="font-size:13px">
        <i class="bi bi-inbox" style="font-size:2rem;display:block;margin-bottom:8px"></i>
        Belum ada laporan
      </div>
    <?php else: ?>
      <?php foreach ($history as $h): ?>
        <?php
          $activeClass = (isset($report['id']) && $report['id'] === $h['id']) ? 'active' : '';
          $device = $h['analysis']['device'] ?? 'Unknown';
          $period = $h['analysis']['period'] ?? $h['uploaded'];
        ?>
        <div class="d-flex align-items-center">
          <a href="?action=view&id=<?= htmlspecialchars($h['id']) ?>"
             class="history-item flex-grow-1 <?= $activeClass ?>">
            <div class="fw-semibold" style="font-size:13px"><?= htmlspecialchars($device) ?></div>
            <div class="history-date"><?= htmlspecialchars(substr($period, 0, 10)) ?></div>
            <div class="history-date text-secondary"><?= htmlspecialchars($h['uploaded']) ?></div>
          </a>
          <a href="?action=delete&id=<?= htmlspecialchars($h['id']) ?>"
             class="btn btn-link text-danger p-1 me-1"
             onclick="return confirm('Hapus laporan ini?')"
             title="Hapus"><i class="bi bi-trash" style="font-size:13px"></i></a>
        </div>
      <?php endforeach; ?>
    <?php endif; ?>
  </div>

  <!-- Main Content -->
  <div class="col-md-9 col-lg-10 py-4 px-4">

    <?php if ($needsComposer): ?>
    <!-- Setup guide -->
    <div class="needs-setup mb-4">
      <h5 class="fw-semibold"><i class="bi bi-wrench me-2"></i>Setup diperlukan</h5>
      <p class="mb-2">Install library <strong>pdfparser</strong> via Composer di cPanel sebelum menggunakan aplikasi ini:</p>
      <ol class="mb-2" style="font-size:13px">
        <li>Login ke cPanel → <strong>Terminal</strong></li>
        <li>Masuk ke folder aplikasi ini:<br>
            <code>cd <?= htmlspecialchars(__DIR__) ?></code></li>
        <li>Jalankan:<br>
            <code>composer require smalot/pdfparser</code></li>
        <li>Refresh halaman ini</li>
      </ol>
      <p class="mb-0 text-muted" style="font-size:12px">Jika Composer belum tersedia: <code>curl -sS https://getcomposer.org/installer | php</code></p>
    </div>
    <?php endif; ?>

    <?php if ($message): ?>
    <div class="alert alert-<?= $message['type'] === 'success' ? 'success' : 'danger' ?> alert-dismissible fade show">
      <?= htmlspecialchars($message['text']) ?>
      <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>

    <?php if (!$report): ?>
    <!-- Upload form -->
    <div class="card section-card">
      <div class="card-header"><i class="bi bi-upload me-2"></i>Upload Laporan FortiGate (PDF)</div>
      <div class="card-body p-4">
        <form method="POST" enctype="multipart/form-data" id="uploadForm">
          <input type="hidden" name="action" value="upload">
          <div class="upload-zone" id="uploadZone" onclick="document.getElementById('pdfInput').click()">
            <div class="icon"><i class="bi bi-file-earmark-pdf"></i></div>
            <div class="fw-semibold mt-2" id="uploadLabel">Klik atau drag & drop PDF di sini</div>
            <div class="text-muted mt-1" style="font-size:12px">Maksimal 10 MB · Format: FortiGate Cloud Summary Report</div>
            <input type="file" name="pdf" id="pdfInput" accept=".pdf" style="display:none" onchange="fileSelected(this)">
          </div>
          <div class="mt-3 text-center">
            <button type="submit" class="btn btn-lg px-5" id="submitBtn"
                    style="background:var(--brand);color:#fff;border:none" disabled
                    onclick="document.getElementById('spinnerOverlay').classList.add('show')">
              <i class="bi bi-cpu me-2"></i>Analisis dengan AI
            </button>
          </div>
        </form>
      </div>
    </div>

    <?php if (!empty($history)): ?>
    <div class="empty-state">
      <i class="bi bi-arrow-left" style="font-size:2rem;display:block"></i>
      <div class="mt-2">Pilih laporan dari riwayat di sebelah kiri</div>
    </div>
    <?php endif; ?>

    <?php else: ?>
    <!-- Report Dashboard -->
    <?php $a = $report['analysis']; ?>

    <div class="d-flex justify-content-between align-items-start mb-3 flex-wrap gap-2">
      <div>
        <h5 class="fw-bold mb-0"><?= htmlspecialchars($a['device'] ?? 'Unknown Device') ?></h5>
        <div class="text-muted" style="font-size:13px">
          <i class="bi bi-calendar3 me-1"></i><?= htmlspecialchars($a['period'] ?? '') ?>
          &nbsp;·&nbsp;
          <i class="bi bi-file-earmark-pdf me-1"></i><?= htmlspecialchars($report['filename']) ?>
          &nbsp;·&nbsp;
          Upload: <?= htmlspecialchars($report['uploaded']) ?>
        </div>
      </div>
      <a href="index.php" class="btn btn-outline-secondary btn-sm">
        <i class="bi bi-plus-circle me-1"></i>Upload Baru
      </a>
    </div>

    <!-- Summary bilingual -->
    <?php if (!empty($a['summary_id']) || !empty($a['summary'])): ?>
    <div class="card section-card mb-3" style="border-left:4px solid #0d6efd">
      <div class="card-body py-3">
        <div class="row g-3">
          <div class="col-md-6">
            <div class="d-flex gap-2 align-items-start">
              <span class="badge bg-primary" style="font-size:10px;margin-top:2px;flex-shrink:0">ID</span>
              <span style="font-size:13px"><?= htmlspecialchars($a['summary_id'] ?? $a['summary'] ?? '') ?></span>
            </div>
          </div>
          <?php if (!empty($a['summary_en'])): ?>
          <div class="col-md-6 border-start">
            <div class="d-flex gap-2 align-items-start">
              <span class="badge bg-secondary" style="font-size:10px;margin-top:2px;flex-shrink:0">EN</span>
              <span style="font-size:13px;color:#374151"><?= htmlspecialchars($a['summary_en']) ?></span>
            </div>
          </div>
          <?php endif; ?>
        </div>
      </div>
    </div>
    <?php endif; ?>

    <!-- Stat Cards -->
    <div class="row g-3 mb-3">
      <?php
      $stats = [
        ['label'=>'Total Traffic','value'=>($a['total_traffic_gb']??0).' GB','icon'=>'bi-hdd-network','bg'=>'#e8f4fd','color'=>'#0d6efd'],
        ['label'=>'Total Sesi','value'=>fmtNum($a['total_sessions']??0),'icon'=>'bi-diagram-3','bg'=>'#e8f5e9','color'=>'#198754'],
        ['label'=>'Total Ancaman','value'=>fmtNum($a['total_threats']??0),'icon'=>'bi-shield-exclamation','bg'=>'#fff3cd','color'=>'#fd7e14'],
        ['label'=>'Serangan URL','value'=>fmtNum($a['attacks']??0),'icon'=>'bi-bug','bg'=>'#fdecea','color'=>'#dc3545'],
      ];
      foreach ($stats as $s): ?>
      <div class="col-6 col-md-3">
        <div class="card stat-card" style="background:<?= $s['bg'] ?>">
          <div class="card-body">
            <div class="stat-label"><?= $s['label'] ?></div>
            <div class="stat-value" style="color:<?= $s['color'] ?>">
              <i class="<?= $s['icon'] ?> me-1" style="font-size:18px"></i><?= htmlspecialchars($s['value']) ?>
            </div>
          </div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>

    <!-- Recommendations bilingual -->
    <?php if (!empty($a['recommendations'])): ?>
    <div class="card section-card mb-3">
      <div class="card-header d-flex align-items-center gap-2">
        <i class="bi bi-exclamation-triangle text-warning"></i>
        <span>Rekomendasi Tindakan</span>
        <span class="ms-auto text-muted" style="font-size:11px;font-weight:400">
          <span class="badge bg-primary me-1">ID</span> Bahasa Indonesia &nbsp;·&nbsp;
          <span class="badge bg-secondary me-1">EN</span> English
        </span>
      </div>
      <div class="card-body">
        <?php foreach ($a['recommendations'] as $r):
          $lvl      = strtolower($r['level'] ?? 'low');
          $title_id = $r['title_id'] ?? $r['title'] ?? '';
          $title_en = $r['title_en'] ?? '';
          $desc_id  = $r['desc_id']  ?? $r['desc']  ?? '';
          $desc_en  = $r['desc_en']  ?? '';
        ?>
        <div class="alert-rec <?= htmlspecialchars($lvl) ?> p-3 mb-3">
          <div class="d-flex align-items-center gap-2 mb-2">
            <?= recoBadge($r['level'] ?? 'low') ?>
          </div>
          <div class="row g-3">
            <!-- Indonesian -->
            <div class="col-md-6">
              <div class="d-flex gap-2 align-items-start mb-1">
                <span class="badge bg-primary" style="font-size:10px;flex-shrink:0;margin-top:2px">ID</span>
                <strong style="font-size:13px"><?= htmlspecialchars($title_id) ?></strong>
              </div>
              <div class="text-muted ps-4" style="font-size:13px"><?= htmlspecialchars($desc_id) ?></div>
            </div>
            <!-- English -->
            <?php if ($title_en || $desc_en): ?>
            <div class="col-md-6" style="border-left:1px dashed #dee2e6">
              <div class="d-flex gap-2 align-items-start mb-1">
                <span class="badge bg-secondary" style="font-size:10px;flex-shrink:0;margin-top:2px">EN</span>
                <strong style="font-size:13px"><?= htmlspecialchars($title_en) ?></strong>
              </div>
              <div class="text-muted ps-4" style="font-size:13px"><?= htmlspecialchars($desc_en) ?></div>
            </div>
            <?php endif; ?>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
    <?php endif; ?>

    <div class="row g-3">
      <!-- Threat Analysis -->
      <div class="col-md-6">
        <div class="card section-card h-100">
          <div class="card-header"><i class="bi bi-shield-x me-2 text-danger"></i>Ancaman Teratas</div>
          <div class="card-body p-0">
            <table class="table table-sm table-hover mb-0">
              <thead class="table-light">
                <tr><th>Ancaman</th><th>Level</th><th class="bar-cell">%</th></tr>
              </thead>
              <tbody>
              <?php foreach (array_slice($a['threat_items']??[], 0, 8) as $t): ?>
              <tr>
                <td style="font-size:12px"><?= htmlspecialchars($t['name']??'') ?></td>
                <td><?= levelBadge($t['level']??'Low') ?></td>
                <td>
                  <?php $pct = (float)($t['percent']??'0'); ?>
                  <div class="mini-bar">
                    <div class="mini-bar-fill" style="width:<?= min($pct,100) ?>%;background:<?= $pct>50?'#dc3545':($pct>5?'#fd7e14':'#0dcaf0') ?>"></div>
                  </div>
                  <span style="font-size:11px"><?= htmlspecialchars($t['percent']??'') ?></span>
                </td>
              </tr>
              <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- Top Apps -->
      <div class="col-md-6">
        <div class="card section-card h-100">
          <div class="card-header"><i class="bi bi-bar-chart me-2 text-primary"></i>Aplikasi Trafik Tertinggi</div>
          <div class="card-body p-0">
            <table class="table table-sm table-hover mb-0">
              <thead class="table-light">
                <tr><th>Aplikasi</th><th>Traffic (GB)</th><th class="bar-cell">%</th></tr>
              </thead>
              <tbody>
              <?php foreach (array_slice($a['top_apps']??[], 0, 8) as $app): ?>
              <tr>
                <td style="font-size:12px"><?= htmlspecialchars($app['name']??'') ?></td>
                <td style="font-size:12px"><?= htmlspecialchars($app['traffic_gb']??0) ?></td>
                <td>
                  <?php $pct = (float)($app['percent']??'0'); ?>
                  <div class="mini-bar">
                    <div class="mini-bar-fill" style="width:<?= min($pct,100) ?>%;background:#0d6efd"></div>
                  </div>
                  <span style="font-size:11px"><?= htmlspecialchars($app['percent']??'') ?></span>
                </td>
              </tr>
              <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- VPN Threats -->
      <?php if (!empty($a['vpn_threats'])): ?>
      <div class="col-md-6">
        <div class="card section-card">
          <div class="card-header"><i class="bi bi-vpn me-2 text-warning"></i>VPN / Proxy Tidak Sah</div>
          <div class="card-body">
            <div class="d-flex flex-wrap gap-2">
              <?php foreach ($a['vpn_threats'] as $v): ?>
              <span class="badge badge-vpn"><i class="bi bi-slash-circle me-1"></i><?= htmlspecialchars($v) ?></span>
              <?php endforeach; ?>
            </div>
            <p class="text-muted mt-2 mb-0" style="font-size:12px">
              Aplikasi di atas terdeteksi aktif dan berisiko bypass kebijakan jaringan.
            </p>
          </div>
        </div>
      </div>
      <?php endif; ?>

      <!-- Suspicious Domains -->
      <?php if (!empty($a['suspicious_domains'])): ?>
      <div class="col-md-6">
        <div class="card section-card">
          <div class="card-header"><i class="bi bi-globe-x me-2 text-danger"></i>Domain Mencurigakan</div>
          <div class="card-body">
            <?php foreach ($a['suspicious_domains'] as $d): ?>
            <div class="d-flex align-items-center gap-2 mb-1">
              <i class="bi bi-exclamation-circle text-danger"></i>
              <code style="font-size:12px"><?= htmlspecialchars($d) ?></code>
            </div>
            <?php endforeach; ?>
          </div>
        </div>
      </div>
      <?php endif; ?>

      <!-- Web Categories -->
      <div class="col-md-6">
        <div class="card section-card">
          <div class="card-header"><i class="bi bi-browser-chrome me-2"></i>Kategori Web</div>
          <div class="card-body p-0">
            <table class="table table-sm table-hover mb-0">
              <tbody>
              <?php foreach ($a['web_categories']??[] as $wc): ?>
              <tr>
                <td style="font-size:12px"><?= htmlspecialchars($wc['name']??'') ?></td>
                <td>
                  <?php $pct=(float)($wc['percent']??'0'); $danger = stripos($wc['name']??'','proxy')!==false; ?>
                  <div class="mini-bar">
                    <div class="mini-bar-fill" style="width:<?= min($pct,100) ?>%;background:<?= $danger?'#dc3545':'#198754' ?>"></div>
                  </div>
                </td>
                <td style="font-size:12px;text-align:right">
                  <?php if ($danger): ?><span class="badge bg-danger"><?= htmlspecialchars($wc['percent']??'') ?></span>
                  <?php else: ?><?= htmlspecialchars($wc['percent']??'') ?><?php endif; ?>
                </td>
              </tr>
              <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- Top Users -->
      <div class="col-md-6">
        <div class="card section-card">
          <div class="card-header"><i class="bi bi-people me-2"></i>Pengguna Web Paling Aktif</div>
          <div class="card-body p-0">
            <table class="table table-sm table-hover mb-0">
              <thead class="table-light"><tr><th>#</th><th>User</th><th>Kunjungan</th></tr></thead>
              <tbody>
              <?php foreach ($a['top_users']??[] as $i => $u): ?>
              <tr>
                <td style="font-size:12px;color:#9ca3af"><?= $i+1 ?></td>
                <td style="font-size:12px;font-weight:500"><?= htmlspecialchars($u['name']??'') ?></td>
                <td style="font-size:12px"><?= fmtNum($u['visits']??0) ?></td>
              </tr>
              <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- VPN Tunnels -->
      <?php if (!empty($a['vpn_tunnels'])): ?>
      <div class="col-md-6">
        <div class="card section-card">
          <div class="card-header"><i class="bi bi-lock me-2 text-success"></i>VPN Tunnel Resmi</div>
          <div class="card-body p-0">
            <table class="table table-sm mb-0">
              <thead class="table-light"><tr><th>Tunnel</th><th>Kirim (GB)</th><th>Terima (GB)</th></tr></thead>
              <tbody>
              <?php foreach ($a['vpn_tunnels'] as $vt): ?>
              <tr>
                <td style="font-size:12px;font-weight:500"><?= htmlspecialchars($vt['name']??'') ?></td>
                <td style="font-size:12px"><?= htmlspecialchars($vt['sent_gb']??0) ?></td>
                <td style="font-size:12px"><?= htmlspecialchars($vt['recv_gb']??0) ?></td>
              </tr>
              <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>
      <?php endif; ?>

      <!-- Traffic by Country -->
      <?php if (!empty($a['traffic_by_country'])): ?>
      <div class="col-md-6">
        <div class="card section-card">
          <div class="card-header"><i class="bi bi-globe me-2"></i>Traffic berdasarkan Negara</div>
          <div class="card-body p-0">
            <table class="table table-sm mb-0">
              <thead class="table-light"><tr><th>Negara</th><th>Traffic (GB)</th><th class="bar-cell">%</th></tr></thead>
              <tbody>
              <?php foreach ($a['traffic_by_country'] as $c): ?>
              <tr>
                <td style="font-size:12px"><?= htmlspecialchars($c['country']??'') ?></td>
                <td style="font-size:12px"><?= htmlspecialchars($c['traffic_gb']??0) ?></td>
                <td>
                  <?php $pct=(float)($c['percent']??'0'); ?>
                  <div class="mini-bar"><div class="mini-bar-fill" style="width:<?= min($pct,100) ?>%;background:#7F77DD"></div></div>
                  <span style="font-size:11px"><?= htmlspecialchars($c['percent']??'') ?></span>
                </td>
              </tr>
              <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>
      <?php endif; ?>

      <!-- Admin Sessions -->
      <?php if (!empty($a['admin_sessions'])): ?>
      <div class="col-12">
        <div class="card section-card">
          <div class="card-header"><i class="bi bi-person-gear me-2"></i>Aktivitas Admin</div>
          <div class="card-body">
            <div class="row g-2 mb-3">
              <div class="col-auto">
                <?php if (($a['failed_admin_logins']??0) == 0): ?>
                <span class="badge bg-success"><i class="bi bi-check-circle me-1"></i>Tidak ada login gagal</span>
                <?php else: ?>
                <span class="badge bg-danger"><i class="bi bi-x-circle me-1"></i><?= (int)$a['failed_admin_logins'] ?> login gagal</span>
                <?php endif; ?>
              </div>
              <div class="col-auto">
                <?php if (!($a['virus_detected']??false)): ?>
                <span class="badge bg-success"><i class="bi bi-shield-check me-1"></i>Tidak ada virus</span>
                <?php else: ?>
                <span class="badge bg-danger"><i class="bi bi-virus me-1"></i>Virus terdeteksi!</span>
                <?php endif; ?>
              </div>
            </div>
            <table class="table table-sm mb-0">
              <thead class="table-light"><tr><th>User</th><th>Interface</th><th>Sesi</th><th>Perubahan Config</th></tr></thead>
              <tbody>
              <?php foreach ($a['admin_sessions'] as $as): ?>
              <tr>
                <td style="font-size:12px;font-weight:500"><?= htmlspecialchars($as['user']??'') ?></td>
                <td style="font-size:12px"><code><?= htmlspecialchars($as['interface']??'') ?></code></td>
                <td style="font-size:12px"><?= (int)($as['sessions']??0) ?></td>
                <td style="font-size:12px"><?= (int)($as['changes']??0) ?></td>
              </tr>
              <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>
      <?php endif; ?>

    </div><!-- /row -->
    <?php endif; // end report ?>

  </div><!-- /main -->
</div><!-- /row -->
</div><!-- /container -->

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
const zone  = document.getElementById('uploadZone');
const input = document.getElementById('pdfInput');
const btn   = document.getElementById('submitBtn');
const lbl   = document.getElementById('uploadLabel');

function fileSelected(el) {
  if (el.files.length) {
    lbl.textContent = el.files[0].name;
    if (btn) btn.disabled = false;
  }
}

if (zone) {
  zone.addEventListener('dragover',  e => { e.preventDefault(); zone.classList.add('dragover'); });
  zone.addEventListener('dragleave', () => zone.classList.remove('dragover'));
  zone.addEventListener('drop', e => {
    e.preventDefault();
    zone.classList.remove('dragover');
    if (e.dataTransfer.files[0]) {
      input.files = e.dataTransfer.files;
      fileSelected(input);
    }
  });
}
</script>
</body>
</html>