<!DOCTYPE html>
<html lang="<%= lang || 'id' %>">
<head>
  <meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
  <title><%= t('admin.settings.title', 'Pengaturan') %> | <%= company %></title>
  <meta name="theme-color" content="#0f172a">
  <link rel="manifest" href="/admin/manifest.webmanifest">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
  <link rel="stylesheet" href="/css/admin.css">
</head>
<body>
<%- include('partials/sidebar', { activePage: 'settings', company }) %>
<div class="mw">
  <div class="topbar">
    <div class="tb-title"><button class="hb-menu" onclick="toggleSidebar()"><i class="bi bi-list"></i></button><i class="bi bi-gear"></i> <%= t('admin.settings.system_title', 'Pengaturan Sistem') %></div>
    <div class="tb-right">
      <span class="adm-badge"><i class="bi bi-person-fill"></i> <%= (typeof session !== 'undefined' && session.isCashier) ? t('admin.role.cashier', 'Kasir') : t('admin.role.admin', 'Admin') %></span>
      <a href="/admin/logout" class="btn btn-g btn-sm"><i class="bi bi-box-arrow-left"></i> <%= t('common.logout', 'Logout') %></a>
    </div>
  </div>
  <div class="page">

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

    <div class="card mb16">
      <div class="card-hd" style="display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap">
        <h6 style="margin:0"><i class="bi bi-wallet2"></i> <%= t('admin.settings.ewallet_logs.title', 'Log Notifikasi E-Wallet (Webhook)') %></h6>
        <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">
          <button type="button" class="btn btn-g btn-sm" onclick="enableEwalletNotif()"><i class="bi bi-bell"></i> <%= t('admin.settings.ewallet_logs.enable_notif', 'Aktifkan Notif') %></button>
          <button type="button" class="btn btn-p btn-sm" onclick="toggleEwalletLive()" id="ew_live_btn"><i class="bi bi-broadcast"></i> <%= t('admin.settings.ewallet_logs.live', 'Live') %></button>
          <button type="button" class="btn btn-g btn-sm" onclick="loadEwalletLogs()"><i class="bi bi-arrow-clockwise"></i> <%= t('common.refresh', 'Refresh') %></button>
          <button type="button" class="btn btn-d btn-sm" onclick="clearEwalletLogs()"><i class="bi bi-trash"></i> <%= t('common.clear', 'Clear') %></button>
        </div>
      </div>
      <div class="card-bd">
        <div class="form-row" style="align-items:flex-end">
          <div class="fg">
            <label class="fl"><%= t('admin.settings.ewallet_logs.service', 'Service') %></label>
            <input class="fc" id="ew_service" placeholder="DANA / Gojek / ShopeePay (opsional)">
          </div>
          <div class="fg" style="flex:2">
            <label class="fl"><%= t('admin.settings.ewallet_logs.search', 'Cari') %></label>
            <input class="fc" id="ew_q" placeholder="kata kunci (opsional)">
          </div>
          <div class="fg w160">
            <label class="fl"><%= t('admin.settings.ewallet_logs.limit', 'Limit') %></label>
            <select class="fs" id="ew_limit">
              <option value="50">50</option>
              <option value="100">100</option>
              <option value="200" selected>200</option>
              <option value="500">500</option>
            </select>
          </div>
        </div>
        <div class="hint" style="margin-top:6px">
          Endpoint MacroDroid: <span class="mono">POST /api/webhook/v1/payment-notif</span>
        </div>
        <div class="hint" style="margin-top:6px" id="ew_notif_hint"></div>
        <div class="tbl-wrap" style="margin-top:10px;max-height:420px;overflow:auto">
          <table class="dtbl">
            <thead>
              <tr>
                <th style="width:160px"><%= t('common.time', 'Waktu') %></th>
                <th style="width:110px">Service</th>
                <th style="width:120px"><%= t('admin.settings.ewallet_logs.amount', 'Nominal') %></th>
                <th style="width:80px">OK</th>
                <th style="width:90px">Match</th>
                <th><%= t('admin.settings.ewallet_logs.content', 'Content') %></th>
                <th style="width:80px"><%= t('common.actions', 'Aksi') %></th>
              </tr>
            </thead>
            <tbody id="ew_logs_body">
              <tr><td colspan="7" class="text-center text-muted"><%= t('common.loading', 'Memuat data...') %></td></tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <form method="POST" action="/admin/settings">

        <div class="card mb16">
          <div class="card-hd"><h6><i class="bi bi-telegram"></i> <%= t('admin.settings.telegram.title', 'Pengaturan Telegram Bot (Backup Admin)') %></h6></div>
          <div class="card-bd">
            <div class="form-row">
              <div class="fg">
                <label class="fl"><%= t('admin.settings.telegram.status', 'Status Bot Telegram') %></label>
                <select class="fs" name="telegram_enabled">
                  <option value="true" <%= settings.telegram_enabled ? 'selected' : '' %>><%= t('common.active', 'Aktif') %></option>
                  <option value="false" <%= !settings.telegram_enabled ? 'selected' : '' %>><%= t('common.inactive', 'Nonaktif') %></option>
                </select>
              </div>
              <div class="fg">
                <label class="fl"><%= t('admin.settings.telegram.admin_id', 'Admin Telegram ID') %></label>
                <input class="fc" name="telegram_admin_id" value="<%= settings.telegram_admin_id || '' %>" placeholder="Contoh: 12345678">
              </div>
            </div>
            <div class="fg">
              <label class="fl"><%= t('admin.settings.telegram.bot_token', 'Telegram Bot Token') %></label>
              <div style="display:flex;gap:8px">
                <input class="fc" name="telegram_bot_token" value="<%= settings.telegram_bot_token || '' %>" placeholder="Dapatkan dari @BotFather">
                <button type="button" class="btn btn-g" onclick="syncTelegram()" title="<%= t('admin.settings.telegram.sync_title', 'Sinkronkan / Hapus Webhook Lama') %>"><i class="bi bi-arrow-repeat"></i> <%= t('admin.settings.telegram.sync', 'Sinkronkan') %></button>
              </div>
            </div>
          </div>
        </div>

        <div class="card mb16">
          <div class="card-hd"><h6><i class="bi bi-whatsapp"></i> <%= t('admin.settings.whatsapp.title', 'Pengaturan WhatsApp') %></h6></div>
          <div class="card-bd" style="display:grid;grid-template-columns:1fr 1fr;gap:24px">
        
        <!-- General Info -->
        <div>
          <h6 style="font-size:13px;color:var(--muted);margin-bottom:12px;text-transform:uppercase;letter-spacing:1px"><i class="bi bi-info-circle"></i> <%= t('admin.settings.app_info', 'Info Aplikasi') %></h6>
          <div class="fg">
            <label class="fl"><%= t('admin.settings.company_name', 'Nama Aplikasi / Perusahaan') %></label>
            <input class="fc" name="company_header" value="<%= settings.company_header || '' %>">
          </div>
          <div class="fg">
            <label class="fl"><%= t('admin.settings.footer_info', 'Info Footer') %></label>
            <input class="fc" name="footer_info" value="<%= settings.footer_info || '' %>">
          </div>
          <div class="form-row">
            <div class="fg">
              <label class="fl"><%= t('admin.settings.owner_name', 'Nama Manajer / Owner') %></label>
              <input class="fc" name="company_manager" value="<%= settings.company_manager || '' %>" placeholder="Admin Pusat">
            </div>
            <div class="fg">
              <label class="fl"><%= t('admin.settings.primary_phone', 'Telepon Utama (CS)') %></label>
              <input class="fc" name="company_phone" value="<%= settings.company_phone || '' %>" placeholder="081234567890">
            </div>
          </div>
          <div class="fg">
            <label class="fl"><%= t('admin.settings.company_email', 'Email Perusahaan') %></label>
            <input class="fc" name="company_email" value="<%= settings.company_email || '' %>" placeholder="support@isp.com">
          </div>
          <div class="fg">
            <label class="fl"><%= t('admin.settings.office_address', 'Alamat Kantor') %></label>
            <input class="fc" name="company_address" value="<%= settings.company_address || '' %>" placeholder="Jl. Utama No. 123">
          </div>
          <div class="form-row">
            <div class="fg">
              <label class="fl"><%= t('admin.settings.office_lat', 'Latitude Kantor') %></label>
              <input class="fc" name="office_lat" value="<%= settings.office_lat || '' %>" placeholder="-6.xxx">
            </div>
            <div class="fg">
              <label class="fl"><%= t('admin.settings.office_lng', 'Longitude Kantor') %></label>
              <input class="fc" name="office_lng" value="<%= settings.office_lng || '' %>" placeholder="106.xxx">
            </div>
          <div class="hint" style="margin-top:6px;color:var(--muted)">
            <i class="bi bi-info-circle"></i> Koordinat kantor digunakan untuk validasi lokasi absensi karyawan (geofencing)
          </div>
          <div class="form-row" style="margin-top:12px">
            <div class="fg">
              <label class="fl">
                <i class="bi bi-shield-check"></i> Geofencing Absensi
              </label>
              <select class="fs" name="attendance_geofencing">
                <option value="true" <%= settings.attendance_geofencing === 'true' || settings.attendance_geofencing === true ? 'selected' : '' %>>Aktif (Validasi Lokasi)</option>
                <option value="false" <%= settings.attendance_geofencing === 'false' || settings.attendance_geofencing === false ? 'selected' : '' %>>Nonaktif (Bebas)</option>
              </select>
            </div>
            <div class="fg">
              <label class="fl">
                <i class="bi bi-geo-alt"></i> Radius Absensi (meter)
              </label>
              <input type="number" class="fc" name="attendance_radius" value="<%= settings.attendance_radius || '100' %>" placeholder="100" min="10" max="1000">
            </div>
          </div>
          <div class="hint" style="margin-top:6px;color:var(--warning)">
            <i class="bi bi-exclamation-triangle"></i> <strong>Geofencing:</strong> Karyawan hanya bisa absen jika berada dalam radius yang ditentukan dari koordinat kantor. Nonaktifkan jika karyawan bekerja remote/lapangan.
          </div>
          </div>
          <div class="fg">
            <label class="fl"><%= t('admin.settings.operational_hours', 'Jam Operasional') %></label>
            <input class="fc" name="operational_hours" value="<%= settings.operational_hours || '' %>" placeholder="Setiap Hari: 08.00 - 22.00 WIB">
          </div>
          <div class="form-row">
            <div class="fg">
              <label class="fl"><%= t('admin.settings.server_port', 'Port Server') %></label>
              <input class="fc" type="number" name="server_port" value="<%= settings.server_port || 3001 %>">
            </div>
            <div class="fg">
              <label class="fl"><%= t('admin.settings.customer_otp_login', 'Login OTP Pelanggan') %></label>
              <select class="fs" name="login_otp_enabled">
                <option value="true" <%= settings.login_otp_enabled ? 'selected' : '' %>><%= t('admin.settings.otp_enabled', 'Aktif (Kirim via WA)') %></option>
                <option value="false" <%= !settings.login_otp_enabled ? 'selected' : '' %>><%= t('admin.settings.otp_disabled', 'Nonaktif (Langsung)') %></option>
              </select>
            </div>
          </div>
        </div>

        <!-- GenieACS & MikroTik -->
        <div>
          <h6 style="font-size:13px;color:var(--muted);margin-bottom:12px;text-transform:uppercase;letter-spacing:1px"><i class="bi bi-router"></i> <%= t('admin.settings.external_api', 'API Eksternal') %></h6>
          <div class="fg">
            <label class="fl">GenieACS API URL</label>
            <input class="fc" name="genieacs_url" value="<%= settings.genieacs_url || '' %>" placeholder="http://192.168.8.89:7557">
          </div>
          <div class="form-row">
            <div class="fg">
              <label class="fl">GenieACS Username</label>
              <input class="fc" name="genieacs_username" value="<%= settings.genieacs_username || '' %>">
            </div>
            <div class="fg">
              <label class="fl">GenieACS Password</label>
              <input class="fc" type="password" name="genieacs_password" value="<%= settings.genieacs_password || '' %>">
            </div>
          </div>

          <div class="form-row" style="margin-top:20px">
            <div class="fg">
              <label class="fl">MikroTik IP / Host</label>
              <input class="fc" name="mikrotik_host" value="<%= settings.mikrotik_host || '' %>" placeholder="192.168.1.1">
            </div>
            <div class="fg">
              <label class="fl">MikroTik API Port</label>
              <input class="fc" type="number" name="mikrotik_port" value="<%= settings.mikrotik_port || 8728 %>" placeholder="8728">
            </div>
          </div>
          <div class="form-row">
            <div class="fg">
              <label class="fl">MikroTik API User</label>
              <input class="fc" name="mikrotik_user" value="<%= settings.mikrotik_user || '' %>">
            </div>
            <div class="fg">
              <label class="fl">MikroTik API Password</label>
              <input class="fc" type="password" name="mikrotik_password" value="<%= settings.mikrotik_password || '' %>">
            </div>
          </div>

          <div class="form-row" style="margin-top:20px">
            <div class="fg">
              <label class="fl">Digiflazz Username</label>
              <input class="fc" name="digiflazz_username" value="<%= settings.digiflazz_username || '' %>" placeholder="username digiflazz">
            </div>
            <div class="fg">
              <label class="fl">Digiflazz API Key</label>
              <input class="fc" type="password" name="digiflazz_api_key" value="<%= settings.digiflazz_api_key || '' %>" placeholder="api key digiflazz">
            </div>
          </div>
          <div class="form-row">
            <div class="fg">
              <label class="fl">Digiflazz Webhook Secret</label>
              <input class="fc" name="digiflazz_webhook_secret" value="<%= settings.digiflazz_webhook_secret || '' %>" placeholder="secret untuk verifikasi webhook">
              <div style="font-size:10px; color:var(--muted); margin-top:4px">Header yang dicek: <span class="mono">X-Hub-Signature</span> (HMAC-SHA1) dan event di <span class="mono">X-Digiflazz-Event</span>.</div>
            </div>
            <div class="fg">
              <label class="fl">Digiflazz Webhook ID (Opsional)</label>
              <input class="fc" name="digiflazz_webhook_id" value="<%= settings.digiflazz_webhook_id || '' %>" placeholder="contoh: ABC123">
              <div style="font-size:10px; color:var(--muted); margin-top:4px">Dipakai untuk validasi ping event (hook_id). Tidak wajib untuk transaksi.</div>
            </div>
          </div>
          <div class="form-row">
            <div class="fg">
              <label class="fl">Webhook URL</label>
              <div class="hint"><span class="mono"><%= (typeof digiflazzWebhookUrl !== 'undefined' && digiflazzWebhookUrl) ? digiflazzWebhookUrl : ('http://' + (settings.server_host || 'localhost') + ':' + (settings.server_port || 3001) + '/webhook/digiflazz') %></span></div>
            </div>
          </div>
          <div class="form-row">
            <div class="fg">
              <label class="fl">Digiflazz Markup (Rp)</label>
              <input class="fc" type="number" name="digiflazz_markup" value="<%= settings.digiflazz_markup || 0 %>" min="0">
              <div style="font-size:10px; color:var(--muted); margin-top:4px">Dipakai saat Sync Produk: harga jual = modal + markup.</div>
            </div>
            <div class="fg">
              <label class="fl">Halaman Admin Digiflazz</label>
              <div class="hint"><a href="/admin/digiflazz" style="color:var(--brand);font-weight:700;text-decoration:none">Buka Dashboard Digiflazz</a></div>
            </div>
          </div>
        </div>

        <!-- Admin Auth -->
        <div>
          <h6 style="font-size:13px;color:var(--muted);margin-bottom:12px;text-transform:uppercase;letter-spacing:1px"><i class="bi bi-shield-lock"></i> Kredensial Admin</h6>
          <div class="form-row">
            <div class="fg">
              <label class="fl">Username Admin</label>
              <input class="fc" name="admin_username" value="<%= settings.admin_username || '' %>">
            </div>
            <div class="fg">
              <label class="fl">Password Admin</label>
              <input class="fc" type="password" name="admin_password" value="<%= settings.admin_password || '' %>">
            </div>
          </div>
          <div class="fg">
            <label class="fl">Admin API Key (Untuk akses luar)</label>
            <input class="fc" name="admin_api_key" value="<%= settings.admin_api_key || '' %>">
          </div>
        </div>

        <!-- WhatsApp -->
        <div>
          <h6 style="font-size:13px;color:var(--muted);margin-bottom:12px;text-transform:uppercase;letter-spacing:1px"><i class="bi bi-whatsapp"></i> Integrasi WhatsApp</h6>
          <div class="fg">
            <label class="fl">Enable WhatsApp Bot</label>
            <select class="fs" name="whatsapp_enabled">
              <option value="true" <%= settings.whatsapp_enabled ? 'selected' : '' %>>Aktif</option>
              <option value="false" <%= !settings.whatsapp_enabled ? 'selected' : '' %>>Nonaktif</option>
            </select>
          </div>
          <div class="fg">
            <label class="fl">Nomor Admin WA (Pisahkan dengan koma)</label>
            <input class="fc" name="whatsapp_admin_numbers" value="<%= (settings.whatsapp_admin_numbers || []).join(', ') %>" placeholder="6281xxx, 6282xxx">
          </div>
          <div class="fg">
            <label class="fl">Jeda Antar Pesan Broadcast (Detik)</label>
            <input class="fc" type="number" name="whatsapp_broadcast_delay" value="<%= settings.whatsapp_broadcast_delay || 2 %>" min="1" max="60">
            <div style="font-size:10px; color:var(--muted); margin-top:4px">Rekomendasi: Minimal 2 detik agar tidak terdeteksi spam oleh WhatsApp.</div>
          </div>
        </div>

        <!-- Payment Gateway -->
        <div style="grid-column: span 2">
          <h6 style="font-size:13px;color:var(--muted);margin-bottom:12px;text-transform:uppercase;letter-spacing:1px"><i class="bi bi-wallet2"></i> Pengaturan Payment Gateway</h6>
          
          <div class="form-row3" style="margin-bottom: 20px;">
            <div class="fg">
              <label class="fl">Default Gateway</label>
              <select class="fs" name="default_gateway">
                <option value="tripay" <%= settings.default_gateway === 'tripay' ? 'selected' : '' %>>Tripay</option>
                <option value="midtrans" <%= settings.default_gateway === 'midtrans' ? 'selected' : '' %>>Midtrans</option>
                <option value="xendit" <%= settings.default_gateway === 'xendit' ? 'selected' : '' %>>Xendit</option>
                <option value="duitku" <%= settings.default_gateway === 'duitku' ? 'selected' : '' %>>Duitku</option>
              </select>
            </div>
          </div>

          <div style="background: rgba(0,0,0,0.02); padding: 15px; border-radius: 12px; margin-bottom: 15px;">
            <h6 style="font-size:12px; margin-bottom: 10px;">QRIS Statis (Semi-Otomatis)</h6>
            <div class="form-row3">
              <div class="fg">
                <label class="fl">QRIS Static QR URL (opsional)</label>
                <input class="fc" name="qris_static_qr_url" value="<%= settings.qris_static_qr_url || '' %>" placeholder="https://.../qris.png atau link QRIS">
              </div>
              <div class="fg">
                <label class="fl">Catatan</label>
                <input class="fc" value="Pakai tombol QR di Billing untuk buat nominal unik." readonly>
              </div>
              <div class="fg">
                <label class="fl">Metode</label>
                <input class="fc" value="Semua e-wallet (QRIS) + nominal unik" readonly>
              </div>
            </div>
          </div>

          <!-- Tripay Section -->
          <div style="background: rgba(0,0,0,0.02); padding: 15px; border-radius: 12px; margin-bottom: 15px;">
            <h6 style="font-size:12px; margin-bottom: 10px;">Tripay Configuration</h6>
            <div class="form-row3">
              <div class="fg">
                <label class="fl">Status Tripay</label>
                <select class="fs" name="tripay_enabled">
                  <option value="true" <%= settings.tripay_enabled === true ? 'selected' : '' %>>Aktif</option>
                  <option value="false" <%= settings.tripay_enabled === false ? 'selected' : '' %>>Nonaktif</option>
                </select>
              </div>
              <div class="fg">
                <label class="fl">Tripay API Key</label>
                <input class="fc" name="tripay_api_key" value="<%= settings.tripay_api_key || '' %>" type="password">
              </div>
              <div class="fg">
                <label class="fl">Tripay Private Key</label>
                <input class="fc" name="tripay_private_key" value="<%= settings.tripay_private_key || '' %>" type="password">
              </div>
            </div>
            <div class="form-row3">
              <div class="fg">
                <label class="fl">Tripay Merchant Code</label>
                <input class="fc" name="tripay_merchant_code" value="<%= settings.tripay_merchant_code || '' %>" placeholder="Txxxx">
              </div>
              <div class="fg">
                <label class="fl">Tripay Mode</label>
                <select class="fs" name="tripay_mode">
                  <option value="sandbox" <%= settings.tripay_mode === 'sandbox' ? 'selected' : '' %>>Sandbox</option>
                  <option value="live" <%= settings.tripay_mode === 'live' ? 'selected' : '' %>>Live</option>
                </select>
              </div>
            </div>
          </div>

          <!-- Midtrans Section -->
          <div style="background: rgba(0,0,0,0.02); padding: 15px; border-radius: 12px;">
            <h6 style="font-size:12px; margin-bottom: 10px;">Midtrans Configuration</h6>
            <div class="form-row3">
              <div class="fg">
                <label class="fl">Status Midtrans</label>
                <select class="fs" name="midtrans_enabled">
                  <option value="true" <%= settings.midtrans_enabled === true ? 'selected' : '' %>>Aktif</option>
                  <option value="false" <%= settings.midtrans_enabled === false ? 'selected' : '' %>>Nonaktif</option>
                </select>
              </div>
              <div class="fg">
                <label class="fl">Midtrans Server Key</label>
                <input class="fc" name="midtrans_server_key" value="<%= settings.midtrans_server_key || '' %>" type="password">
              </div>
              <div class="fg">
                <label class="fl">Midtrans Mode</label>
                <select class="fs" name="midtrans_mode">
                  <option value="sandbox" <%= settings.midtrans_mode === 'sandbox' ? 'selected' : '' %>>Sandbox</option>
                  <option value="live" <%= settings.midtrans_mode === 'live' ? 'selected' : '' %>>Live</option>
                </select>
              </div>
            </div>
          </div>

          <!-- Xendit Section -->
          <div style="background: rgba(0,0,0,0.02); padding: 15px; border-radius: 12px; margin-top: 15px;">
            <h6 style="font-size:12px; margin-bottom: 10px;">Xendit Configuration</h6>
            <div class="form-row2">
              <div class="fg">
                <label class="fl">Status Xendit</label>
                <select class="fs" name="xendit_enabled">
                  <option value="true" <%= settings.xendit_enabled === true ? 'selected' : '' %>>Aktif</option>
                  <option value="false" <%= settings.xendit_enabled === false ? 'selected' : '' %>>Nonaktif</option>
                </select>
              </div>
              <div class="fg">
                <label class="fl">Xendit Secret API Key</label>
                <input class="fc" name="xendit_api_key" value="<%= settings.xendit_api_key || '' %>" type="password" placeholder="xnd_development_...">
              </div>
            </div>
            <div style="font-size: 10px; color: var(--muted); margin-top: 4px;">Xendit menggunakan callback token yang disetting di dashboard Xendit.</div>
          </div>

          <!-- Duitku Section -->
          <div style="background: rgba(0,0,0,0.02); padding: 15px; border-radius: 12px; margin-top: 15px;">
            <h6 style="font-size:12px; margin-bottom: 10px;">Duitku Configuration</h6>
            <div class="form-row3">
              <div class="fg">
                <label class="fl">Status Duitku</label>
                <select class="fs" name="duitku_enabled">
                  <option value="true" <%= settings.duitku_enabled === true ? 'selected' : '' %>>Aktif</option>
                  <option value="false" <%= settings.duitku_enabled === false ? 'selected' : '' %>>Nonaktif</option>
                </select>
              </div>
              <div class="fg">
                <label class="fl">Duitku Merchant Code</label>
                <input class="fc" name="duitku_merchant_code" value="<%= settings.duitku_merchant_code || '' %>" placeholder="Dxxxx">
              </div>
              <div class="fg">
                <label class="fl">Duitku API Key</label>
                <input class="fc" name="duitku_api_key" value="<%= settings.duitku_api_key || '' %>" type="password">
              </div>
            </div>
            <div class="form-row2">
              <div class="fg">
                <label class="fl">Duitku Mode</label>
                <select class="fs" name="duitku_mode">
                  <option value="sandbox" <%= settings.duitku_mode === 'sandbox' ? 'selected' : '' %>>Sandbox</option>
                  <option value="live" <%= settings.duitku_mode === 'live' ? 'selected' : '' %>>Live</option>
                </select>
              </div>
            </div>
          </div>

          <div class="fg" style="margin-top: 15px;">
            <label class="fl">Link Webhook (Copy ke Dashboard Gateway)</label>
            <div style="display:flex;gap:8px">
              <input class="fc" id="webhook_url" readonly value="<%= (typeof paymentWebhookUrl !== 'undefined' && paymentWebhookUrl) ? paymentWebhookUrl : ('http://' + (settings.server_host || 'localhost') + ':' + (settings.server_port || 3001) + '/customer/payment/callback') %>">
              <button type="button" class="btn btn-g" onclick="copyWebhook()"><i class="bi bi-copy"></i></button>
            </div>
            <div style="font-size: 10px; color: var(--muted); margin-top: 4px;">Gunakan link ini untuk kolom Webhook URL di Tripay atau Midtrans Notification URL.</div>
          </div>
        </div>

      </div>
      
          <div class="card-bd" style="border-top:1px solid var(--border);padding-top:20px;text-align:right">
            <button type="submit" class="btn btn-p"><i class="bi bi-save"></i> Simpan Pengaturan</button>
          </div>
        </div>
    </form>
  </div>
</div>

<script>
function copyWebhook() {
  const el = document.getElementById('webhook_url');
  el.select();
  document.execCommand('copy');
  alert('Link Webhook berhasil disalin!');
}
async function syncTelegram() {
  try {
    const res = await fetch('/admin/api/telegram/sync', { method: 'POST' });
    const data = await res.json();
    if (data.success) alert(data.message);
    else alert('Gagal: ' + data.error);
  } catch (e) { alert('Error: ' + e.message); }
}

function escHtml(s) {
  return String(s ?? '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;');
}

if ('serviceWorker' in navigator) {
  try { navigator.serviceWorker.register('/sw.js', { scope: '/admin/' }).catch(() => {}); } catch {}
}

async function copyText(text) {
  const v = String(text ?? '');
  try {
    if (navigator.clipboard && navigator.clipboard.writeText) {
      await navigator.clipboard.writeText(v);
      return true;
    }
  } catch {}
  try {
    const ta = document.createElement('textarea');
    ta.value = v;
    ta.style.position = 'fixed';
    ta.style.left = '-9999px';
    ta.style.top = '0';
    document.body.appendChild(ta);
    ta.focus();
    ta.select();
    const ok = document.execCommand('copy');
    ta.remove();
    return ok;
  } catch {
    return false;
  }
}

function canNotify() {
  return typeof Notification !== 'undefined';
}

function notifEnabled() {
  return localStorage.getItem('ew_notif_enabled') === '1';
}

function setNotifEnabled(v) {
  localStorage.setItem('ew_notif_enabled', v ? '1' : '0');
}

function updateNotifHint() {
  const el = document.getElementById('ew_notif_hint');
  if (!el) return;
  const perm = canNotify() ? Notification.permission : 'unsupported';
  const enabled = notifEnabled();
  let msg = '';
  if (perm === 'unsupported') msg = 'Notifikasi browser tidak didukung di device ini.';
  else if (perm === 'denied') msg = 'Notifikasi diblokir. Izinkan di pengaturan browser.';
  else if (perm === 'granted') msg = enabled ? 'Notif aktif. Notifikasi muncul saat ada log baru (mode Live).' : 'Notif siap, tapi masih nonaktif.';
  else msg = 'Klik "Aktifkan Notif" untuk minta izin notifikasi.';
  el.textContent = msg;
}

async function enableEwalletNotif() {
  if (!canNotify()) return updateNotifHint();
  try {
    const perm = await Notification.requestPermission();
    if (perm === 'granted') {
      setNotifEnabled(true);
      updateNotifHint();
      try { new Notification('E-Wallet Monitor', { body: 'Notifikasi aktif.' }); } catch {}
      return;
    }
    setNotifEnabled(false);
    updateNotifHint();
  } catch {
    setNotifEnabled(false);
    updateNotifHint();
  }
}

let ewLastId = Number(localStorage.getItem('ew_last_id') || 0);
let ewLiveTimer = null;
let ewLiveActive = false;

function showEwalletNotification(row) {
  if (!notifEnabled()) return;
  if (!canNotify() || Notification.permission !== 'granted') return;
  const svc = String(row?.service || 'E-Wallet');
  const amt = row?.parsed_ok ? `Rp ${(Number(row.parsed_amount) || 0).toLocaleString('id-ID')}` : 'Nominal tidak terdeteksi';
  const body = String(row?.content || '').replace(/\r?\n/g, ' ').slice(0, 140);
  try {
    new Notification(`${svc}: ${amt}`, { body });
  } catch {}
}

function toggleEwalletLive() {
  ewLiveActive = !ewLiveActive;
  const btn = document.getElementById('ew_live_btn');
  if (btn) {
    btn.className = ewLiveActive ? 'btn btn-d btn-sm' : 'btn btn-p btn-sm';
    btn.innerHTML = ewLiveActive ? '<i class="bi bi-stop-circle"></i> Stop' : '<i class="bi bi-broadcast"></i> Live';
  }
  if (ewLiveTimer) {
    clearInterval(ewLiveTimer);
    ewLiveTimer = null;
  }
  if (ewLiveActive) {
    loadEwalletLogs(true);
    ewLiveTimer = setInterval(() => loadEwalletLogs(true), 5000);
  }
}

async function loadEwalletLogs() {
  const body = document.getElementById('ew_logs_body');
  const service = document.getElementById('ew_service')?.value || '';
  const q = document.getElementById('ew_q')?.value || '';
  const limit = document.getElementById('ew_limit')?.value || '200';
  if (!body) return;
  body.innerHTML = '<tr><td colspan="7" class="text-center text-muted">Memuat...</td></tr>';
  try {
    const url = `/admin/api/webhook/payment-notif/logs?limit=${encodeURIComponent(limit)}&service=${encodeURIComponent(service)}&q=${encodeURIComponent(q)}`;
    const res = await fetch(url);
    const data = await res.json();
    if (!res.ok || !data.ok) throw new Error(data.error || 'Gagal memuat log');
    const rows = Array.isArray(data.rows) ? data.rows : [];
    if (rows.length === 0) {
      body.innerHTML = '<tr><td colspan="7" class="text-center text-muted">Belum ada data.</td></tr>';
      return;
    }
    const newest = rows[0];
    const newestId = Number(newest?.id || 0);
    if (newestId && ewLastId === 0) {
      ewLastId = newestId;
      localStorage.setItem('ew_last_id', String(ewLastId));
    } else if (newestId && newestId > ewLastId) {
      ewLastId = newestId;
      localStorage.setItem('ew_last_id', String(ewLastId));
      showEwalletNotification(newest);
    }

    body.innerHTML = rows.map(r => {
      const ok = Number(r.parsed_ok || 0) ? 'Y' : 'N';
      const amount = (r.parsed_amount != null && r.parsed_amount !== '') ? Number(r.parsed_amount).toLocaleString('id-ID') : '-';
      const created = r.created_at ? escHtml(r.created_at) : '-';
      const svc = escHtml(r.service || '-');
      const content = escHtml((r.content || '').replace(/\r?\n/g, ' '));
      const okBadge = ok === 'Y' ? '<span class="badge s">OK</span>' : '<span class="badge w">-</span>';
      const amountHtml = ok === 'Y'
        ? `<span class="mono" style="font-weight:900;color:#065f46">Rp ${amount}</span>`
        : `<span class="mono">Rp ${amount}</span>`;
      const rawEnc = encodeURIComponent(String(r.content || ''));
      const rawShortEnc = encodeURIComponent(String(r.content || '').replace(/\r?\n/g, ' ').slice(0, 180));
      const matchedId = Number(r.matched_invoice_id || 0) || 0;
      const matchHtml = matchedId
        ? `<a class="mono" href="/admin/billing?search=${matchedId}" target="_blank">#${matchedId}</a>`
        : '<span class="muted">-</span>';
      return `<tr>
        <td class="mono">${created}</td>
        <td>${svc}</td>
        <td>${amountHtml}</td>
        <td>${okBadge}</td>
        <td>${matchHtml}</td>
        <td style="max-width:720px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis" title="${content}">${content}</td>
        <td>
          <button type="button" class="btn btn-g btn-sm btn-copy-ew" data-raw="${rawEnc}" data-short="${rawShortEnc}">
            <i class="bi bi-copy"></i>
          </button>
        </td>
      </tr>`;
    }).join('');

    body.querySelectorAll('.btn-copy-ew').forEach(btn => {
      btn.addEventListener('click', async () => {
        const rawEnc = btn.getAttribute('data-raw') || '';
        const rawShortEnc = btn.getAttribute('data-short') || '';
        const decoded = decodeURIComponent(rawEnc);
        const shortText = rawShortEnc ? decodeURIComponent(rawShortEnc) : 'Tersalin.';
        const ok = await copyText(decoded);
        if (ok) {
          alert(`Tersalin:\n${shortText}`);
        } else {
          alert('Gagal menyalin.');
        }
      });
    });
  } catch (e) {
    body.innerHTML = `<tr><td colspan="7" class="text-center text-muted">${escHtml(e.message)}</td></tr>`;
  }
}

async function clearEwalletLogs() {
  if (!confirm('Hapus semua log e-wallet?')) return;
  try {
    const res = await fetch('/admin/api/webhook/payment-notif/clear', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' });
    const data = await res.json();
    if (!res.ok || !data.ok) throw new Error(data.error || 'Gagal menghapus log');
    await loadEwalletLogs();
  } catch (e) {
    alert(e.message);
  }
}

setTimeout(loadEwalletLogs, 200);
setTimeout(updateNotifHint, 250);
setTimeout(()=>document.querySelectorAll('.alert').forEach(a=>a.style.display='none'),5000);
</script>
</body>
</html>
