<!DOCTYPE html>
<html lang="<%= lang || 'id' %>">
<head>
  <meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
  <title><%= t('admin.broadcast.title', 'Broadcast WhatsApp') %> | <%= company %></title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
  <link rel="stylesheet" href="/css/admin.css">
  <style>
    .wa-tabs { display: flex; gap: 10px; margin-bottom: 14px; border-bottom: 1px solid var(--border); padding-bottom: 10px; }
    .wa-tab { padding: 8px 14px; border-radius: 8px; cursor: pointer; color: var(--muted); transition: all 0.2s; font-weight: 700; text-decoration: none; }
    .wa-tab:hover { background: rgba(255,255,255,0.06); color: var(--text); }
    .wa-tab.active { background: var(--primary); color: white; }
  </style>
</head>
<body>
<%- include('partials/sidebar', { activePage: 'whatsapp', 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-megaphone"></i> <%= t('admin.broadcast.title', 'Broadcast WhatsApp') %></div>
    <div class="tb-right">
      <span class="adm-badge"><i class="bi bi-person-fill"></i> <%= (typeof session !== 'undefined' && session.isCashier) ? t('admin.role.cashier', 'Kasir') : t('admin.role.admin', 'Admin') %></span>
      <a href="/admin/logout" class="btn btn-g btn-sm"><i class="bi bi-box-arrow-left"></i></a>
    </div>
  </div>
  <div class="page">
    <% const waTab = 'broadcast'; %>

    <% 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="wa-tabs">
      <a href="/admin/whatsapp" class="wa-tab <%= waTab==='status' ? 'active' : '' %>"><i class="bi bi-phone"></i> Status</a>
      <a href="/admin/whatsapp/broadcast" class="wa-tab <%= waTab==='broadcast' ? 'active' : '' %>"><i class="bi bi-megaphone"></i> Broadcast & Pengingat</a>
    </div>

    <div class="card">
      <div class="card-hd" style="display: flex; justify-content: space-between; align-items: center;">
        <h6><i class="bi bi-send-fill"></i> <%= t('admin.broadcast.send_mass', 'Kirim Pesan Massal') %></h6>
        <div id="broadcastCounter" class="badge bp" style="display: none;">
          <span class="spinner-border spinner-border-sm me-1" role="status" aria-hidden="true"></span>
          <%= t('admin.broadcast.sending', 'Mengirim:') %> <span id="sentCount">0</span>/<span id="totalCount">0</span>
          (<span id="failedCount" class="text-danger ms-1">0</span> <%= t('admin.broadcast.failed', 'Gagal') %>)
        </div>
      </div>
      <form id="broadcastForm" method="POST" action="/admin/whatsapp/broadcast" data-confirm="<%= t('admin.broadcast.confirm_send', 'Kirim pesan broadcast sekarang? Pastikan target dan pesan sudah benar.') %>">
        <div class="card-bd">
          <div class="alert alert-i" style="margin-bottom: 10px;">
            <i class="bi bi-info-circle"></i> <%= t('admin.broadcast.info', 'Pesan akan dikirim menggunakan nomor WhatsApp Bot Anda secara otomatis dengan jeda aman per pesan agar tidak terdeteksi sebagai spam.') %>
          </div>



          <div class="form-row" style="margin-bottom: 15px;">
            <div class="fg">
              <label class="fl"><%= t('admin.broadcast.target', 'Target Penerima') %></label>
              <select class="fs" name="target" id="targetSelect" required style="width: 100%;">
                <option value="all"><%= t('admin.broadcast.target_all', 'Semua Pelanggan (Aktif & Isolir)') %></option>
                <option value="active"><%= t('admin.broadcast.target_active', 'Hanya Pelanggan Aktif') %></option>
                <option value="suspended"><%= t('admin.broadcast.target_suspended', 'Hanya Pelanggan Terisolir') %></option>
                <option value="unpaid"><%= t('admin.broadcast.target_unpaid', 'Pelanggan yang Punya Tunggakan Tagihan') %></option>
              </select>
            </div>
            <div class="fg">
              <label class="fl"><%= t('admin.broadcast.delay', 'Jeda Antar Pesan (Detik)') %></label>
              <input class="fc" type="number" name="delay" value="<%= getSetting('whatsapp_broadcast_delay', 2) %>" min="1" max="60">
            </div>
          </div>

          <div class="alert alert-d alert-permanent" style="margin-bottom: 20px; border: 1px solid rgba(248,81,73,0.4);">
            <i class="bi bi-exclamation-triangle-fill"></i> <strong><%= t('admin.broadcast.warning_title', 'PERINGATAN PENTING:') %></strong> <%= t('admin.broadcast.warning_body', 'Penggunaan fitur broadcast massal berisiko menyebabkan akun WhatsApp Anda DIBLOKIR (BANNED) oleh pihak Meta jika dianggap melanggar ketentuan spam. Pastikan pesan relevan bagi pelanggan. Developer aplikasi tidak bertanggung jawab atas segala risiko pemblokiran akun.') %>
          </div>
          
          <div class="form-row">
            <div class="fg" style="width: 100%;">
              <label class="fl"><%= t('admin.broadcast.message', 'Isi Pesan WhatsApp') %></label>
              <textarea class="fc" name="message" id="messageBox" rows="8" required style="width: 100%;"></textarea>
              <div style="font-size: 11px; color: var(--muted); margin-top: 6px;">
                <i class="bi bi-info-circle"></i> <%= t('admin.broadcast.variables', 'Variabel:') %> <b>{{nama}}</b>, <b>{{tagihan}}</b>, <b>{{rincian}}</b>, <b>{{paket}}</b>, <b>{{link}}</b> (<%= t('admin.broadcast.portal_link', 'Link Portal') %>).
                <br>
                <i class="bi bi-chat-text"></i> <%= t('admin.broadcast.formatting', 'Gunakan *Tebal*, _Miring_, atau ~Coret~ sesuai standar WhatsApp.') %>
              </div>
            </div>
          </div>
        </div>
        <div class="card-bd" style="border-top: 1px solid var(--border); background: var(--bg2); display: flex; justify-content: flex-end;">
          <button type="submit" class="btn btn-p"><i class="bi bi-send"></i> <%= t('admin.broadcast.start', 'Mulai Broadcast') %></button>
        </div>
      </form>
    </div>

    <div class="card">
      <div class="card-hd">
        <h6><i class="bi bi-alarm"></i> Pengingat Tagihan Otomatis</h6>
      </div>
      <form method="POST" action="/admin/whatsapp/auto-billing" onsubmit="return confirm('Simpan pengaturan pengingat tagihan otomatis?');">
        <div class="card-bd">
          <%
            const defaultAutoBillingMsg =
              `Yth. Pelanggan {{nama}},\n\n` +
              `Ini adalah pengingat sebelum tanggal jatuh tempo/isolir.\n\n` +
              `📦 *Paket:* {{paket}}\n` +
              `💰 *Total Tagihan:* Rp {{tagihan}}\n` +
              `📅 *Periode:* {{rincian}}\n\n` +
              `Mohon segera melakukan pembayaran melalui portal pelanggan: {{link}}\n\n` +
              `Terima kasih atas kerja samanya.\n` +
              `Salam,\nAdmin ${company}`;
            const autoBillingMsg = getSetting('whatsapp_auto_billing_message', defaultAutoBillingMsg);
          %>
          <div class="form-row" style="margin-bottom: 12px;">
            <div class="fg" style="width: 100%;">
              <label class="fl">Status</label>
              <label style="display:flex; align-items:center; gap:10px; font-weight:800; color: var(--text);">
                <input type="checkbox" name="enabled" value="1" <%= getSetting('whatsapp_auto_billing_enabled', false) ? 'checked' : '' %>>
                Aktifkan pengingat tagihan otomatis
              </label>
              <div style="font-size: 11px; color: var(--muted); margin-top: 6px;">
                Sistem akan mengirim pengingat ke pelanggan yang punya tunggakan pada H-1 sebelum tanggal isolir (isolate_day).
              </div>
            </div>
          </div>

          <div class="form-row" style="margin-bottom: 12px;">
            <div class="fg">
              <label class="fl">Jeda Antar Pesan (Detik)</label>
              <input class="fc" type="number" name="delay" value="<%= getSetting('whatsapp_broadcast_delay', 2) %>" min="1" max="60">
              <div style="font-size: 11px; color: var(--muted); margin-top: 6px;">
                Dipakai untuk pengingat otomatis dan default broadcast.
              </div>
            </div>
          </div>

          <div class="form-row">
            <div class="fg" style="width: 100%;">
              <label class="fl">Isi Pesan WhatsApp</label>
              <textarea class="fc" name="message" rows="8" required style="width: 100%;"><%= autoBillingMsg %></textarea>
              <div style="font-size: 11px; color: var(--muted); margin-top: 6px;">
                <i class="bi bi-info-circle"></i> Variabel: <b>{{nama}}</b>, <b>{{tagihan}}</b>, <b>{{rincian}}</b>, <b>{{paket}}</b>, <b>{{link}}</b> (link login otomatis).
              </div>
            </div>
          </div>
        </div>
        <div class="card-bd" style="border-top: 1px solid var(--border); background: var(--bg2); display: flex; justify-content: flex-end;">
          <button type="submit" class="btn btn-p"><i class="bi bi-save"></i> Simpan</button>
        </div>
      </form>
    </div>

  </div>
</div>

<script>
const I18N = {
  confirmChangeTarget: "<%= t('admin.broadcast.confirm_change_target', 'Ganti target penerima? Pesan yang sudah Anda ketik akan ditimpa dengan template baru.') %>",
  sendingText: "<%= t('admin.broadcast.sending_btn', 'Sedang Mengirim...') %>",
  donePrefix: "<%= t('admin.broadcast.done_prefix', 'Selesai:') %>",
  sentSuffix: "<%= t('admin.broadcast.sent_suffix', 'dikirim') %>",
  startBtn: "<%= t('admin.broadcast.start', 'Mulai Broadcast') %>"
};
const templates = {
  all: `Yth. Pelanggan {{nama}},\n\nBersama ini kami informasikan bahwa akan ada pemeliharaan jaringan rutin pada:\nHari/Tanggal: ...\nPukul: ...\n\nSelama proses tersebut, layanan internet (Paket {{paket}}) akan terganggu sementara waktu. Kami memohon maaf atas ketidaknyamanan ini.\n\nCek status layanan di: {{link}}\n\nTerima kasih.\nSalam,\nAdmin <%= company %>`,
  
  active: `Yth. Pelanggan Setia {{nama}},\n\nTerima kasih telah mempercayakan kebutuhan internet Anda kepada kami. Nikmati terus layanan terbaik Paket {{paket}} tanpa hambatan.\n\nKelola akun Anda di: {{link}}\n\nSalam,\nAdmin <%= company %>`,
  
  suspended: `Yth. Pelanggan {{nama}},\n\nMohon maaf, layanan internet Anda saat ini sedang dinonaktifkan (Terisolir). \n\nTotal tunggakan Anda: *Rp {{tagihan}}* (Periode: {{rincian}}).\n\nSilakan bayar melalui portal kami: {{link}}\n\nSalam,\nAdmin <%= company %>`,
  
  unpaid: `Yth. Pelanggan {{nama}},\n\nBerdasarkan data sistem kami, Anda memiliki tagihan internet yang *BELUM LUNAS*.\n\n📦 *Paket:* {{paket}}\n💰 *Total Tagihan:* Rp {{tagihan}}\n📅 *Periode:* {{rincian}}\n\nMohon segera melakukan pembayaran melalui portal pelanggan: {{link}}\n\nTerima kasih atas kerja samanya.\nSalam,\nAdmin <%= company %>`
};

const targetSelect = document.getElementById('targetSelect');
const messageBox = document.getElementById('messageBox');

// Set template awal
messageBox.value = templates[targetSelect.value];

// Ganti template saat dropdown berubah
targetSelect.addEventListener('change', function() {
  if (confirm(I18N.confirmChangeTarget)) {
    messageBox.value = templates[this.value];
  } else {
    // Revert dropdown if canceled
    for(let i=0; i<this.options.length; i++) {
      if(templates[this.options[i].value] === messageBox.value) {
        this.selectedIndex = i;
        break;
      }
    }
  }
});

setTimeout(()=>document.querySelectorAll('.alert:not(.alert-permanent)').forEach(a=>a.style.display='none'),5000);

// Polling Broadcast Status
const broadcastCounter = document.getElementById('broadcastCounter');
const sentCountEl = document.getElementById('sentCount');
const totalCountEl = document.getElementById('totalCount');
const failedCountEl = document.getElementById('failedCount');
const submitBtn = document.querySelector('button[type="submit"]');
const broadcastForm = document.getElementById('broadcastForm');

if (broadcastForm) {
  broadcastForm.addEventListener('submit', function (e) {
    const msg = String(broadcastForm.dataset.confirm || '').trim();
    if (msg && !confirm(msg)) e.preventDefault();
  });
}

async function checkBroadcastStatus() {
  try {
    const res = await fetch('/admin/api/whatsapp/broadcast-status');
    const status = await res.json();
    
    if (status.active) {
      broadcastCounter.style.display = 'inline-flex';
      sentCountEl.textContent = status.sent;
      totalCountEl.textContent = status.total;
      failedCountEl.textContent = status.failed;
      submitBtn.disabled = true;
      submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span> ' + I18N.sendingText;
    } else {
      if (status.total > 0 && status.sent + status.failed === status.total) {
        // Just finished
        broadcastCounter.className = 'badge bs';
        broadcastCounter.innerHTML = `<i class="bi bi-check-circle-fill me-1"></i> ${I18N.donePrefix} ${status.sent}/${status.total} ${I18N.sentSuffix}`;
        submitBtn.disabled = false;
        submitBtn.innerHTML = '<i class="bi bi-send"></i> ' + I18N.startBtn;
      } else {
        broadcastCounter.style.display = 'none';
      }
    }
  } catch (e) { console.error('Status check failed', e); }
}

// Start polling
setInterval(checkBroadcastStatus, 2000);
checkBroadcastStatus();
</script>
</body>
</html>
