<?php
/**
 * dashboard.php — NEXUS Bot Control Panel Dashboard
 *
 * Included by index.php after authentication.
 * Variables available: $botConfig, $options
 */

if (!defined('ADMIN_USER')) {
    header('Location: /');
    exit;
}

// Extract values for the template
$instanceId     = htmlspecialchars($botConfig['instance_id'] ?? '', ENT_QUOTES);
$accessToken    = htmlspecialchars($botConfig['access_token'] ?? '', ENT_QUOTES);
$apiBaseUrl     = htmlspecialchars($botConfig['api_base_url'] ?? '', ENT_QUOTES);
$webhookSecret  = htmlspecialchars($botConfig['webhook_secret'] ?? '', ENT_QUOTES);
$welcomeMessage = htmlspecialchars($botConfig['welcome_message'] ?? '', ENT_QUOTES);
$apiNewOrder    = htmlspecialchars($botConfig['api_new_order'] ?? '', ENT_QUOTES);

$networks          = $options['networks'] ?? [];
$voucherCategories = $options['voucher_categories'] ?? [];
$transferData      = $options['transfer_data'] ?? ['title' => '', 'lines' => []];

$transferTitle = htmlspecialchars($transferData['title'] ?? '', ENT_QUOTES);
$transferLines = implode("\n", array_map('htmlspecialchars', $transferData['lines'] ?? []));

$networksJson  = htmlspecialchars(json_encode($networks, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT), ENT_QUOTES);
$vouchersJson  = htmlspecialchars(json_encode($voucherCategories, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT), ENT_QUOTES);

$logSize = is_file(LOG_PATH) ? round(filesize(LOG_PATH) / 1024, 1) : 0;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>NEXUS · Dashboard</title>
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@300;400;500;600;700&family=Outfit:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<style>
  :root {
    --bg-primary: #0a0b0f;
    --bg-secondary: #12131a;
    --bg-card: #161720;
    --bg-input: #1a1b27;
    --border: #252736;
    --border-hover: #3a3d54;
    --accent: #00e5a0;
    --accent-dim: rgba(0, 229, 160, 0.08);
    --accent-glow: rgba(0, 229, 160, 0.25);
    --accent-secondary: #6c5ce7;
    --danger: #ff4757;
    --warning: #ffa502;
    --text-primary: #e8e9f0;
    --text-secondary: #7a7d96;
    --text-muted: #4a4d64;
    --radius: 12px;
    --radius-sm: 8px;
  }
  * { margin: 0; padding: 0; box-sizing: border-box; }
  body {
    font-family: 'Outfit', sans-serif;
    background: var(--bg-primary);
    color: var(--text-primary);
    min-height: 100vh;
    overflow-x: hidden;
  }
  /* ===== BACKGROUND ===== */
  .bg-grid {
    position: fixed; inset: 0; z-index: 0;
    background-image:
      linear-gradient(rgba(0,229,160,0.03) 1px, transparent 1px),
      linear-gradient(90deg, rgba(0,229,160,0.03) 1px, transparent 1px);
    background-size: 60px 60px;
    animation: gridPulse 8s ease-in-out infinite;
  }
  @keyframes gridPulse { 0%,100%{opacity:.5} 50%{opacity:1} }
  .bg-glow {
    position: fixed; width: 600px; height: 600px;
    border-radius: 50%; filter: blur(150px); opacity: 0.15;
    z-index: 0; pointer-events: none;
  }
  .bg-glow-1 { top:-200px; right:-100px; background:var(--accent); animation:glowFloat 12s ease-in-out infinite; }
  .bg-glow-2 { bottom:-200px; left:-100px; background:var(--accent-secondary); animation:glowFloat 15s ease-in-out infinite reverse; }
  @keyframes glowFloat { 0%,100%{transform:translate(0,0)} 50%{transform:translate(40px,30px)} }
  @keyframes fadeSlideUp { from{opacity:0;transform:translateY(30px)} to{opacity:1;transform:translateY(0)} }

  /* ===== TOP BAR ===== */
  .topbar {
    display: flex; align-items: center; justify-content: space-between;
    padding: 16px 32px; border-bottom: 1px solid var(--border);
    background: rgba(10,11,15,0.85); backdrop-filter: blur(20px);
    position: sticky; top: 0; z-index: 10;
  }
  .topbar-left { display: flex; align-items: center; gap: 14px; }
  .topbar-logo {
    width: 36px; height: 36px;
    background: linear-gradient(135deg, var(--accent), var(--accent-secondary));
    border-radius: 10px; display: flex; align-items: center;
    justify-content: center; font-size: 16px; color: #fff;
  }
  .topbar-title {
    font-family: 'JetBrains Mono', monospace;
    font-weight: 700; font-size: 16px; letter-spacing: 2px;
  }
  .topbar-right { display: flex; align-items: center; gap: 16px; }
  .bot-status {
    display: flex; align-items: center; gap: 8px;
    padding: 8px 16px; background: rgba(0,229,160,0.08);
    border: 1px solid rgba(0,229,160,0.2); border-radius: 100px;
    font-family: 'JetBrains Mono', monospace; font-size: 12px;
    color: var(--accent); font-weight: 500;
  }
  .bot-status .pulse {
    width: 8px; height: 8px; background: var(--accent);
    border-radius: 50%; animation: dotBlink 1.5s infinite;
  }
  @keyframes dotBlink { 0%,100%{opacity:1} 50%{opacity:.3} }
  .topbar-user {
    font-family: 'JetBrains Mono', monospace; font-size: 12px;
    color: var(--text-secondary);
  }
  .btn-logout {
    padding: 8px 18px; background: transparent;
    border: 1px solid var(--border); border-radius: var(--radius-sm);
    color: var(--text-secondary); font-family: 'JetBrains Mono', monospace;
    font-size: 11px; letter-spacing: 1px; cursor: pointer; transition: all 0.2s;
    text-decoration: none;
  }
  .btn-logout:hover { border-color: var(--danger); color: var(--danger); }

  /* ===== NAV TABS ===== */
  .nav-tabs {
    display: flex; gap: 0; border-bottom: 1px solid var(--border);
    background: rgba(10,11,15,0.6); padding: 0 32px;
  }
  .nav-tab {
    padding: 14px 24px; font-family: 'JetBrains Mono', monospace;
    font-size: 12px; letter-spacing: 1px; color: var(--text-muted);
    cursor: pointer; border-bottom: 2px solid transparent;
    transition: all 0.2s; user-select: none;
  }
  .nav-tab:hover { color: var(--text-secondary); }
  .nav-tab.active { color: var(--accent); border-bottom-color: var(--accent); }

  /* ===== DASHBOARD CONTENT ===== */
  .dash-content {
    max-width: 960px; margin: 0 auto; padding: 40px 32px 80px;
    position: relative; z-index: 1;
  }
  .tab-panel { display: none; animation: fadeSlideUp 0.4s ease; }
  .tab-panel.active { display: block; }

  .dash-header { margin-bottom: 40px; }
  .dash-header h2 { font-size: 26px; font-weight: 600; margin-bottom: 6px; }
  .dash-header p { color: var(--text-secondary); font-size: 14px; }

  /* ===== OVERVIEW CARDS ===== */
  .overview-grid {
    display: grid; grid-template-columns: repeat(3, 1fr);
    gap: 16px; margin-bottom: 36px;
  }
  .overview-card {
    background: var(--bg-card); border: 1px solid var(--border);
    border-radius: var(--radius); padding: 22px; transition: all 0.3s;
    animation: fadeSlideUp 0.6s cubic-bezier(0.16,1,0.3,1) backwards;
  }
  .overview-card:nth-child(1) { animation-delay: 0.1s; }
  .overview-card:nth-child(2) { animation-delay: 0.2s; }
  .overview-card:nth-child(3) { animation-delay: 0.3s; }
  .overview-card:hover { border-color: var(--border-hover); transform: translateY(-2px); }
  .overview-card .oc-label {
    font-family: 'JetBrains Mono', monospace; font-size: 11px;
    letter-spacing: 1.5px; text-transform: uppercase;
    color: var(--text-muted); margin-bottom: 10px;
  }
  .overview-card .oc-value { font-size: 28px; font-weight: 700; }
  .overview-card .oc-value.green { color: var(--accent); }
  .overview-card .oc-value.purple { color: var(--accent-secondary); }
  .overview-card .oc-value.orange { color: var(--warning); }

  /* ===== CONFIG SECTIONS ===== */
  .config-section {
    background: var(--bg-card); border: 1px solid var(--border);
    border-radius: var(--radius); margin-bottom: 20px; overflow: hidden;
    animation: fadeSlideUp 0.6s cubic-bezier(0.16,1,0.3,1) backwards;
  }
  .config-header {
    display: flex; align-items: center; justify-content: space-between;
    padding: 22px 28px; cursor: pointer; transition: background 0.2s; user-select: none;
  }
  .config-header:hover { background: rgba(255,255,255,0.02); }
  .config-header-left { display: flex; align-items: center; gap: 14px; }
  .config-icon {
    width: 40px; height: 40px; border-radius: 10px;
    display: flex; align-items: center; justify-content: center; font-size: 18px;
  }
  .config-icon.green  { background: rgba(0,229,160,0.1); }
  .config-icon.purple { background: rgba(108,92,231,0.1); }
  .config-icon.orange { background: rgba(255,165,2,0.1); }
  .config-icon.red    { background: rgba(255,71,87,0.1); }
  .config-icon.blue   { background: rgba(88,166,255,0.1); }
  .config-title { font-weight: 600; font-size: 15px; }
  .config-subtitle { font-size: 12px; color: var(--text-muted); margin-top: 2px; }
  .config-chevron { color: var(--text-muted); transition: transform 0.3s; font-size: 14px; }
  .config-section.open .config-chevron { transform: rotate(180deg); }
  .config-body { max-height: 0; overflow: hidden; transition: max-height 0.4s cubic-bezier(0.16,1,0.3,1); }
  .config-section.open .config-body { max-height: 1200px; }
  .config-body-inner { padding: 0 28px 28px; border-top: 1px solid var(--border); padding-top: 24px; }

  /* ===== CONFIG CONTROLS ===== */
  .config-row {
    display: flex; align-items: flex-start; justify-content: space-between;
    padding: 14px 0; border-bottom: 1px solid rgba(255,255,255,0.03); gap: 16px;
  }
  .config-row:last-child { border-bottom: none; }
  .config-row-label { font-size: 14px; color: var(--text-primary); }
  .config-row-desc { font-size: 12px; color: var(--text-muted); margin-top: 2px; }
  .config-text, .config-number {
    padding: 10px 14px; background: var(--bg-input);
    border: 1px solid var(--border); border-radius: var(--radius-sm);
    color: var(--text-primary); font-family: 'JetBrains Mono', monospace;
    font-size: 13px; outline: none; transition: border-color 0.2s;
  }
  .config-text:focus, .config-number:focus { border-color: var(--accent); }
  .config-text { width: 320px; }
  .config-number { width: 90px; text-align: center; }
  .config-textarea {
    width: 100%; min-height: 80px; padding: 12px 14px;
    background: var(--bg-input); border: 1px solid var(--border);
    border-radius: var(--radius-sm); color: var(--text-primary);
    font-family: 'JetBrains Mono', monospace; font-size: 13px;
    outline: none; resize: vertical; transition: border-color 0.2s;
    line-height: 1.5;
  }
  .config-textarea:focus { border-color: var(--accent); }
  .config-textarea.json-editor { min-height: 180px; font-size: 12px; }
  .config-row.full-width { flex-direction: column; gap: 10px; }

  /* ===== BUTTONS ===== */
  .save-bar {
    display: flex; justify-content: flex-end; gap: 12px; margin-top: 32px;
    animation: fadeSlideUp 0.6s cubic-bezier(0.16,1,0.3,1) 0.5s backwards;
  }
  .btn-save {
    padding: 14px 32px; background: linear-gradient(135deg, var(--accent), #00c896);
    color: var(--bg-primary); font-family: 'JetBrains Mono', monospace;
    font-size: 13px; font-weight: 700; letter-spacing: 1px;
    text-transform: uppercase; border: none; border-radius: var(--radius-sm);
    cursor: pointer; transition: all 0.3s;
  }
  .btn-save:hover { transform: translateY(-2px); box-shadow: 0 6px 24px rgba(0,229,160,0.3); }
  .btn-save:disabled { opacity: 0.6; cursor: not-allowed; transform: none; }
  .btn-reset {
    padding: 14px 24px; background: transparent; color: var(--text-secondary);
    font-family: 'JetBrains Mono', monospace; font-size: 13px; font-weight: 500;
    letter-spacing: 1px; text-transform: uppercase;
    border: 1px solid var(--border); border-radius: var(--radius-sm);
    cursor: pointer; transition: all 0.2s;
  }
  .btn-reset:hover { border-color: var(--danger); color: var(--danger); }
  .btn-sm {
    padding: 8px 16px; font-family: 'JetBrains Mono', monospace;
    font-size: 11px; letter-spacing: 1px; border-radius: var(--radius-sm);
    cursor: pointer; transition: all 0.2s; border: 1px solid var(--border);
    background: transparent; color: var(--text-secondary);
  }
  .btn-sm:hover { border-color: var(--accent); color: var(--accent); }
  .btn-sm.danger:hover { border-color: var(--danger); color: var(--danger); }

  /* ===== LOG VIEWER ===== */
  .log-container {
    background: var(--bg-input); border: 1px solid var(--border);
    border-radius: var(--radius-sm); padding: 16px; min-height: 300px;
    max-height: 500px; overflow-y: auto; font-family: 'JetBrains Mono', monospace;
    font-size: 12px; line-height: 1.7; white-space: pre-wrap; word-break: break-all;
  }
  .log-container .line-error { color: #f85149; }
  .log-container .line-warn  { color: #d29922; }
  .log-container .line-ok    { color: #3fb950; }
  .log-container .line-info  { color: #58a6ff; }
  .log-controls {
    display: flex; gap: 8px; margin-bottom: 16px; flex-wrap: wrap; align-items: center;
  }
  .log-info {
    font-family: 'JetBrains Mono', monospace; font-size: 11px;
    color: var(--text-muted); margin-left: auto;
  }

  /* ===== TOAST ===== */
  .toast {
    position: fixed; bottom: 30px; left: 50%;
    transform: translateX(-50%) translateY(100px);
    background: var(--bg-card); border: 1px solid var(--accent);
    border-radius: var(--radius-sm); padding: 14px 28px;
    font-family: 'JetBrains Mono', monospace; font-size: 13px;
    color: var(--accent); z-index: 100;
    transition: transform 0.4s cubic-bezier(0.16,1,0.3,1);
    box-shadow: 0 8px 32px rgba(0,229,160,0.15);
  }
  .toast.error { border-color: var(--danger); color: var(--danger); }
  .toast.show { transform: translateX(-50%) translateY(0); }

  /* ===== RESPONSIVE ===== */
  @media (max-width: 700px) {
    .overview-grid { grid-template-columns: 1fr; }
    .topbar { padding: 14px 18px; }
    .dash-content { padding: 24px 18px 60px; }
    .config-text { width: 180px; }
    .topbar-title { display: none; }
    .topbar-user { display: none; }
    .nav-tabs { padding: 0 16px; overflow-x: auto; }
    .nav-tab { padding: 12px 16px; font-size: 11px; white-space: nowrap; }
  }
</style>
</head>
<body>
<div class="bg-grid"></div>
<div class="bg-glow bg-glow-1"></div>
<div class="bg-glow bg-glow-2"></div>

<!-- ===== TOP BAR ===== -->
<div class="topbar">
  <div class="topbar-left">
    <div class="topbar-logo">&hexmark;</div>
    <span class="topbar-title">NEXUS</span>
  </div>
  <div class="topbar-right">
    <div class="bot-status"><span class="pulse"></span> Online</div>
    <span class="topbar-user"><?= htmlspecialchars($_SESSION['user'] ?? 'admin') ?></span>
    <a href="#" class="btn-logout" onclick="doLogout(); return false;">Logout</a>
  </div>
</div>

<!-- ===== NAV TABS ===== -->
<div class="nav-tabs">
  <div class="nav-tab active" data-tab="overview">Overview</div>
  <div class="nav-tab" data-tab="bot-config">Bot Config</div>
  <div class="nav-tab" data-tab="options">Options</div>
  <div class="nav-tab" data-tab="logs">Logs</div>
</div>

<div class="dash-content">

  <!-- ============================================================ -->
  <!-- TAB: Overview                                                 -->
  <!-- ============================================================ -->
  <div class="tab-panel active" id="tab-overview">
    <div class="dash-header">
      <h2>Dashboard</h2>
      <p>Overview of your NEXUS bot instance.</p>
    </div>
    <div class="overview-grid">
      <div class="overview-card">
        <div class="oc-label">Instance</div>
        <div class="oc-value green" style="font-size:18px;"><?= $instanceId ?: 'Not set' ?></div>
      </div>
      <div class="overview-card">
        <div class="oc-label">Networks</div>
        <div class="oc-value purple"><?= count($networks) ?></div>
      </div>
      <div class="overview-card">
        <div class="oc-label">Voucher Types</div>
        <div class="oc-value orange"><?= count($voucherCategories) ?></div>
      </div>
    </div>
    <div class="overview-grid">
      <div class="overview-card">
        <div class="oc-label">API Base URL</div>
        <div class="oc-value" style="font-size:14px; color:var(--text-secondary); word-break:break-all;"><?= $apiBaseUrl ?: 'Not set' ?></div>
      </div>
      <div class="overview-card">
        <div class="oc-label">Webhook Secret</div>
        <div class="oc-value" style="font-size:14px; color:var(--text-secondary);"><?= $webhookSecret ? '******' : 'Not set' ?></div>
      </div>
      <div class="overview-card">
        <div class="oc-label">Log Size</div>
        <div class="oc-value" style="font-size:14px; color:var(--text-secondary);"><?= $logSize ?> KB</div>
      </div>
    </div>
  </div>

  <!-- ============================================================ -->
  <!-- TAB: Bot Config                                               -->
  <!-- ============================================================ -->
  <div class="tab-panel" id="tab-bot-config">
    <div class="dash-header">
      <h2>Bot Configuration</h2>
      <p>Edit your WhatsApp bot connection settings (bot.config.json).</p>
    </div>

    <!-- API Connection -->
    <div class="config-section open">
      <div class="config-header" onclick="toggleSection(this.parentElement, event)">
        <div class="config-header-left">
          <div class="config-icon green">&#9881;</div>
          <div>
            <div class="config-title">API Connection</div>
            <div class="config-subtitle">wifi2fm.com API credentials and endpoint</div>
          </div>
        </div>
        <span class="config-chevron">&#9660;</span>
      </div>
      <div class="config-body">
        <div class="config-body-inner">
          <div class="config-row">
            <div>
              <div class="config-row-label">Instance ID</div>
              <div class="config-row-desc">Your wifi2fm instance identifier</div>
            </div>
            <input type="text" class="config-text" id="cfg-instance-id" value="<?= $instanceId ?>">
          </div>
          <div class="config-row">
            <div>
              <div class="config-row-label">Access Token</div>
              <div class="config-row-desc">API authentication token</div>
            </div>
            <input type="password" class="config-text" id="cfg-access-token" value="<?= $accessToken ?>">
          </div>
          <div class="config-row">
            <div>
              <div class="config-row-label">API Base URL</div>
              <div class="config-row-desc">Base URL for the wifi2fm API</div>
            </div>
            <input type="text" class="config-text" id="cfg-api-base-url" value="<?= $apiBaseUrl ?>">
          </div>
        </div>
      </div>
    </div>

    <!-- Security -->
    <div class="config-section">
      <div class="config-header" onclick="toggleSection(this.parentElement, event)">
        <div class="config-header-left">
          <div class="config-icon purple">&#128737;</div>
          <div>
            <div class="config-title">Security</div>
            <div class="config-subtitle">Webhook secret and API endpoint protection</div>
          </div>
        </div>
        <span class="config-chevron">&#9660;</span>
      </div>
      <div class="config-body">
        <div class="config-body-inner">
          <div class="config-row">
            <div>
              <div class="config-row-label">Webhook Secret</div>
              <div class="config-row-desc">Secret key to validate incoming webhooks (leave empty to skip)</div>
            </div>
            <input type="text" class="config-text" id="cfg-webhook-secret" value="<?= $webhookSecret ?>">
          </div>
          <div class="config-row">
            <div>
              <div class="config-row-label">New Order API URL</div>
              <div class="config-row-desc">Endpoint for submitting new orders. Must be reachable from this server on port 80 or 443.</div>
            </div>
            <div style="display:flex;gap:8px;align-items:center;flex:1;">
              <input type="text" class="config-text" id="cfg-api-new-order" value="<?= $apiNewOrder ?>" style="flex:1;">
              <button type="button" id="btn-test-api" onclick="testApiConnection()" style="white-space:nowrap;">Test</button>
            </div>
          </div>
          <div id="api-test-result" style="display:none;margin-top:6px;padding:8px 12px;border-radius:6px;font-size:13px;line-height:1.5;"></div>
        </div>
      </div>
    </div>

    <!-- Welcome Message -->
    <div class="config-section">
      <div class="config-header" onclick="toggleSection(this.parentElement, event)">
        <div class="config-header-left">
          <div class="config-icon orange">&#128172;</div>
          <div>
            <div class="config-title">Welcome Message</div>
            <div class="config-subtitle">Greeting sent to new users on first contact</div>
          </div>
        </div>
        <span class="config-chevron">&#9660;</span>
      </div>
      <div class="config-body">
        <div class="config-body-inner">
          <div class="config-row full-width">
            <div>
              <div class="config-row-label">Message Text</div>
              <div class="config-row-desc">Supports line breaks. Shown once per new conversation.</div>
            </div>
            <textarea class="config-textarea" id="cfg-welcome-message" rows="4"><?= $welcomeMessage ?></textarea>
          </div>
        </div>
      </div>
    </div>

    <div class="save-bar">
      <button class="btn-reset" onclick="location.reload()">Discard</button>
      <button class="btn-save" id="btnSaveBotConfig" onclick="saveBotConfig()">Save Config</button>
    </div>
  </div>

  <!-- ============================================================ -->
  <!-- TAB: Options                                                  -->
  <!-- ============================================================ -->
  <div class="tab-panel" id="tab-options">
    <div class="dash-header">
      <h2>Bot Options</h2>
      <p>Networks, voucher categories, and transfer data (options.json).</p>
    </div>

    <!-- Networks -->
    <div class="config-section open">
      <div class="config-header" onclick="toggleSection(this.parentElement, event)">
        <div class="config-header-left">
          <div class="config-icon blue">&#127760;</div>
          <div>
            <div class="config-title">Networks</div>
            <div class="config-subtitle">Available mobile networks</div>
          </div>
        </div>
        <span class="config-chevron">&#9660;</span>
      </div>
      <div class="config-body">
        <div class="config-body-inner">
          <div class="config-row full-width">
            <div>
              <div class="config-row-label">Networks JSON</div>
              <div class="config-row-desc">Array of {id, name} objects</div>
            </div>
            <textarea class="config-textarea json-editor" id="cfg-networks"><?= $networksJson ?></textarea>
          </div>
        </div>
      </div>
    </div>

    <!-- Voucher Categories -->
    <div class="config-section">
      <div class="config-header" onclick="toggleSection(this.parentElement, event)">
        <div class="config-header-left">
          <div class="config-icon green">&#127915;</div>
          <div>
            <div class="config-title">Voucher Categories</div>
            <div class="config-subtitle">Available voucher types and pricing</div>
          </div>
        </div>
        <span class="config-chevron">&#9660;</span>
      </div>
      <div class="config-body">
        <div class="config-body-inner">
          <div class="config-row full-width">
            <div>
              <div class="config-row-label">Vouchers JSON</div>
              <div class="config-row-desc">Array of {id, network_id, name, price, currency} objects</div>
            </div>
            <textarea class="config-textarea json-editor" id="cfg-vouchers"><?= $vouchersJson ?></textarea>
          </div>
        </div>
      </div>
    </div>

    <!-- Transfer Data -->
    <div class="config-section">
      <div class="config-header" onclick="toggleSection(this.parentElement, event)">
        <div class="config-header-left">
          <div class="config-icon purple">&#127974;</div>
          <div>
            <div class="config-title">Transfer Data</div>
            <div class="config-subtitle">Bank transfer details shown to users</div>
          </div>
        </div>
        <span class="config-chevron">&#9660;</span>
      </div>
      <div class="config-body">
        <div class="config-body-inner">
          <div class="config-row">
            <div>
              <div class="config-row-label">Title</div>
              <div class="config-row-desc">Heading shown above transfer details</div>
            </div>
            <input type="text" class="config-text" id="cfg-transfer-title" value="<?= $transferTitle ?>">
          </div>
          <div class="config-row full-width">
            <div>
              <div class="config-row-label">Transfer Lines</div>
              <div class="config-row-desc">One line per row. Each line is a separate entry.</div>
            </div>
            <textarea class="config-textarea" id="cfg-transfer-lines" rows="6"><?= $transferLines ?></textarea>
          </div>
        </div>
      </div>
    </div>

    <div class="save-bar">
      <button class="btn-reset" onclick="location.reload()">Discard</button>
      <button class="btn-save" id="btnSaveOptions" onclick="saveOptions()">Save Options</button>
    </div>
  </div>

  <!-- ============================================================ -->
  <!-- TAB: Logs                                                     -->
  <!-- ============================================================ -->
  <div class="tab-panel" id="tab-logs">
    <div class="dash-header">
      <h2>Bot Logs</h2>
      <p>Live log output from the WhatsApp webhook handler.</p>
    </div>
    <div class="log-controls">
      <button class="btn-sm" onclick="loadLogs()">Refresh</button>
      <button class="btn-sm danger" onclick="clearLogs()">Clear Logs</button>
      <span class="log-info" id="logInfo">Loading...</span>
    </div>
    <div class="log-container" id="logOutput">Loading logs...</div>
  </div>

</div>

<!-- Toast -->
<div class="toast" id="toast"></div>

<script>
// ─────────────────────────────────────────────────────────────
// Tab Navigation
// ─────────────────────────────────────────────────────────────
document.querySelectorAll('.nav-tab').forEach(tab => {
  tab.addEventListener('click', () => {
    document.querySelectorAll('.nav-tab').forEach(t => t.classList.remove('active'));
    document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
    tab.classList.add('active');
    document.getElementById('tab-' + tab.dataset.tab).classList.add('active');
    if (tab.dataset.tab === 'logs') loadLogs();
  });
});

// ─────────────────────────────────────────────────────────────
// Section Toggle
// ─────────────────────────────────────────────────────────────
function toggleSection(el, e) {
  if (e.target.closest('input, select, textarea, label.toggle, button')) return;
  el.classList.toggle('open');
}

// ─────────────────────────────────────────────────────────────
// Toast
// ─────────────────────────────────────────────────────────────
function showToast(msg, isError) {
  const t = document.getElementById('toast');
  t.textContent = msg;
  t.className = 'toast show' + (isError ? ' error' : '');
  setTimeout(() => t.classList.remove('show'), 3000);
}

// ─────────────────────────────────────────────────────────────
// API Helper
// ─────────────────────────────────────────────────────────────
function apiPost(data) {
  return fetch('/', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Requested-With': 'XMLHttpRequest'
    },
    body: JSON.stringify(data)
  }).then(r => r.json());
}

// ─────────────────────────────────────────────────────────────
// Logout
// ─────────────────────────────────────────────────────────────
function doLogout() {
  apiPost({ action: 'logout' }).then(() => {
    window.location.href = '/';
  }).catch(() => {
    window.location.href = '/';
  });
}

// ─────────────────────────────────────────────────────────────
// Save Bot Config
// ─────────────────────────────────────────────────────────────
function saveBotConfig() {
  const btn = document.getElementById('btnSaveBotConfig');
  btn.disabled = true;
  btn.textContent = 'Saving...';

  const config = {
    instance_id:     document.getElementById('cfg-instance-id').value.trim(),
    access_token:    document.getElementById('cfg-access-token').value.trim(),
    api_base_url:    document.getElementById('cfg-api-base-url').value.trim(),
    webhook_secret:  document.getElementById('cfg-webhook-secret').value.trim(),
    welcome_message: document.getElementById('cfg-welcome-message').value,
    api_new_order:   document.getElementById('cfg-api-new-order').value.trim()
  };

  apiPost({ action: 'save_bot_config', config: config })
    .then(data => {
      if (data.success) {
        showToast('Bot config saved successfully');
      } else {
        showToast(data.error || 'Save failed', true);
      }
    })
    .catch(() => showToast('Network error', true))
    .finally(() => {
      btn.disabled = false;
      btn.textContent = 'Save Config';
    });
}

// ─────────────────────────────────────────────────────────────
// Test API Connection
// ─────────────────────────────────────────────────────────────
function testApiConnection() {
  const url = document.getElementById('cfg-api-new-order').value.trim();
  const btn = document.getElementById('btn-test-api');
  const result = document.getElementById('api-test-result');

  if (!url) {
    result.style.display = 'block';
    result.style.background = '#fff3cd';
    result.style.color = '#856404';
    result.textContent = 'Enter an API URL first.';
    return;
  }

  btn.disabled = true;
  btn.textContent = 'Testing...';
  result.style.display = 'none';

  apiPost({ action: 'test_api_connection', url })
    .then(data => {
      result.style.display = 'block';
      if (data.reachable) {
        result.style.background = '#d1e7dd';
        result.style.color = '#0a3622';
        result.textContent = `Reachable — HTTP ${data.http_code} in ${data.time_ms}ms.`;
      } else {
        result.style.background = '#f8d7da';
        result.style.color = '#58151c';
        let msg = `Cannot connect — ${data.curl_error || 'unknown error'} (errno ${data.curl_errno}).`;
        if (data.hint) msg += '\n\n' + data.hint;
        result.textContent = msg;
      }
    })
    .catch(() => {
      result.style.display = 'block';
      result.style.background = '#f8d7da';
      result.style.color = '#58151c';
      result.textContent = 'Network error while running test.';
    })
    .finally(() => {
      btn.disabled = false;
      btn.textContent = 'Test';
    });
}

// ─────────────────────────────────────────────────────────────
// Save Options
// ─────────────────────────────────────────────────────────────
function saveOptions() {
  const btn = document.getElementById('btnSaveOptions');
  btn.disabled = true;
  btn.textContent = 'Saving...';

  // Parse JSON fields
  let networks, vouchers;
  try {
    networks = JSON.parse(document.getElementById('cfg-networks').value);
    if (!Array.isArray(networks)) throw new Error('Networks must be an array');
  } catch (e) {
    showToast('Invalid Networks JSON: ' + e.message, true);
    btn.disabled = false;
    btn.textContent = 'Save Options';
    return;
  }

  try {
    vouchers = JSON.parse(document.getElementById('cfg-vouchers').value);
    if (!Array.isArray(vouchers)) throw new Error('Vouchers must be an array');
  } catch (e) {
    showToast('Invalid Vouchers JSON: ' + e.message, true);
    btn.disabled = false;
    btn.textContent = 'Save Options';
    return;
  }

  // Build transfer data
  const transferTitle = document.getElementById('cfg-transfer-title').value;
  const transferLines = document.getElementById('cfg-transfer-lines').value
    .split('\n')
    .filter(line => line.trim() !== '');

  const options = {
    networks: networks,
    voucher_categories: vouchers,
    transfer_data: {
      title: transferTitle,
      lines: transferLines
    }
  };

  apiPost({ action: 'save_options', options: options })
    .then(data => {
      if (data.success) {
        showToast('Options saved successfully');
      } else {
        showToast(data.error || 'Save failed', true);
      }
    })
    .catch(() => showToast('Network error', true))
    .finally(() => {
      btn.disabled = false;
      btn.textContent = 'Save Options';
    });
}

// ─────────────────────────────────────────────────────────────
// Logs
// ─────────────────────────────────────────────────────────────
function loadLogs() {
  apiPost({ action: 'get_logs', lines: 200 })
    .then(data => {
      if (!data.success) {
        document.getElementById('logOutput').textContent = 'Failed to load logs.';
        return;
      }
      const container = document.getElementById('logOutput');
      container.innerHTML = '';

      if (data.lines.length === 0) {
        container.textContent = 'No log entries found.';
      } else {
        data.lines.forEach(line => {
          const span = document.createElement('span');
          span.textContent = line + '\n';
          if (/ERROR|FAILED|Fatal/i.test(line))       span.className = 'line-error';
          else if (/Warning/i.test(line))              span.className = 'line-warn';
          else if (/OK|success/i.test(line))           span.className = 'line-ok';
          else if (/\[router\]|\[normalize\]/i.test(line)) span.className = 'line-info';
          container.appendChild(span);
        });
        container.scrollTop = container.scrollHeight;
      }

      document.getElementById('logInfo').textContent =
        data.total + ' lines | ' + data.size_kb + ' KB';
    })
    .catch(() => {
      document.getElementById('logOutput').textContent = 'Error loading logs.';
    });
}

function clearLogs() {
  if (!confirm('Clear all logs? This cannot be undone.')) return;
  apiPost({ action: 'clear_logs' })
    .then(data => {
      if (data.success) {
        showToast('Logs cleared');
        loadLogs();
      } else {
        showToast(data.error || 'Failed to clear logs', true);
      }
    })
    .catch(() => showToast('Network error', true));
}
</script>
</body>
</html>
