<div class="row g-3">
  <?php foreach ($businessLines as $bl): ?>
  <?php $existing = null; foreach ($rows as $r) { if ((int) $r['business_line_id'] === (int) $bl['id']) { $existing = $r; break; } } ?>
  <div class="col-md-6">
    <div class="ab-card">
      <div class="ab-card-header">
        <h2><?= e($bl['name']) ?> <span class="ab-badge bg-secondary-soft ab-mono" title="This business line's ID — use this value for business_line_id when embedding its chat widget">id: <?= (int) $bl['id'] ?></span></h2>
        <?php if ($existing): ?><span class="ab-badge <?= $existing['is_live'] ? 'bg-success-soft' : 'bg-secondary-soft' ?>"><?= $existing['is_live'] ? 'Live' : 'Draft' ?></span><?php endif; ?>
      </div>
      <div class="ab-card-body">
        <form class="ab-chatbot-form" data-bl="<?= (int) $bl['id'] ?>">
          <input type="hidden" name="business_line_id" value="<?= (int) $bl['id'] ?>">
          <div class="mb-2"><label class="form-label">Bot Name</label><input class="form-control" name="bot_name" value="<?= e($existing['bot_name'] ?? 'A&B Assistant') ?>" required></div>
          <div class="mb-2"><label class="form-label">Greeting Message</label><textarea class="form-control" name="greeting_message" rows="2"><?= e($existing['greeting_message'] ?? '') ?></textarea></div>
          <div class="mb-3"><label class="form-label">Handoff Keywords (comma-separated)</label><input class="form-control" name="handoff_keywords" value="<?= e($existing['handoff_keywords'] ?? '') ?>" placeholder="manager, supervisor, complaint"></div>
          <div class="mb-3">
            <label class="form-label">Allowed Website Domain</label>
            <input class="form-control" name="allowed_origin" value="<?= e($existing['allowed_origin'] ?? '') ?>" placeholder="https://aandbcleaner.org">
            <div class="form-text">The exact website this business's chat widget is embedded on. Required for the widget to actually work when called from that site — browsers block it otherwise. Include <code>www.</code> only if visitors reach the site that way.</div>
          </div>
          <div class="form-check form-switch mb-3">
            <input class="form-check-input" type="checkbox" name="is_live" <?= !empty($existing['is_live']) ? 'checked' : '' ?>>
            <label class="form-check-label">Live on website</label>
          </div>
          <button type="submit" class="btn btn-primary btn-sm">Save</button>
        </form>
      </div>
    </div>
  </div>
  <?php endforeach; ?>
</div>

<div class="ab-card mt-3">
  <div class="ab-card-header"><h2>Embed Snippet</h2></div>
  <div class="ab-card-body">
    <p class="ab-cell-sub">Copy the block below for whichever business's widget you're adding to its website — <code>business_line_id</code> is already filled in correctly for each, no need to look it up separately. Paste it just before <code>&lt;/body&gt;</code> on the pages where you want the chat widget to appear.</p>

    <ul class="nav ab-tabs mb-2">
      <?php foreach ($businessLines as $i => $bl): ?>
      <li class="nav-item"><a class="nav-link <?= $i === 0 ? 'active' : '' ?>" data-bs-toggle="tab" href="#embedTab<?= (int) $bl['id'] ?>"><?= e($bl['name']) ?></a></li>
      <?php endforeach; ?>
    </ul>

    <div class="tab-content">
      <?php foreach ($businessLines as $i => $bl): ?>
      <div class="tab-pane fade <?= $i === 0 ? 'show active' : '' ?>" id="embedTab<?= (int) $bl['id'] ?>">
        <div class="d-flex justify-content-end mb-1">
          <button class="btn btn-light-soft btn-sm ab-copy-snippet" data-target="snippet-<?= (int) $bl['id'] ?>"><i class="bi bi-clipboard me-1"></i>Copy</button>
        </div>
        <pre class="ab-mono small border rounded-3 p-3 mb-0" id="snippet-<?= (int) $bl['id'] ?>" style="background:var(--ab-canvas); white-space:pre-wrap;">&lt;script&gt;
(function () {
  var BUSINESS_LINE_ID = <?= (int) $bl['id'] ?>; // <?= e($bl['name']) ?>
  var API_BASE = '<?= base_url('') ?>';
  var conversationId = null;

  window.abChatbotSend = function (message, onReply) {
    var body = conversationId
      ? { conversation_id: conversationId, message: message, business_line_id: BUSINESS_LINE_ID }
      : null;

    var request = conversationId
      ? fetch(API_BASE + 'widget/chatbot/message', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
      : fetch(API_BASE + 'widget/chatbot/start', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ business_line_id: BUSINESS_LINE_ID }) });

    request.then(function (r) { return r.json(); }).then(function (res) {
      if (res.data.conversation_id) conversationId = res.data.conversation_id;
      onReply(res.data.message || res.data.reply);
    });
  };

  // Call window.abChatbotSend('start') first (with no prior message) to
  // get the greeting, then call it again with the visitor's typed
  // message each time they send one. Wire these two calls up to your
  // own chat widget UI (open button, message input, message list).
})();
&lt;/script&gt;</pre>
      </div>
      <?php endforeach; ?>
    </div>

    <p class="ab-cell-sub mt-2 mb-0">Raw endpoint shape, if you're building your own widget UI from scratch instead of using the snippet above:</p>
    <pre class="ab-mono small border rounded-3 p-3 mb-0" style="background:var(--ab-canvas);">POST <?= base_url('widget/chatbot/start') ?>   { business_line_id }
POST <?= base_url('widget/chatbot/message') ?> { conversation_id, message, business_line_id }</pre>
  </div>
</div>

<script>
document.querySelectorAll('.ab-chatbot-form').forEach(function (form) {
  form.addEventListener('submit', function (e) {
    e.preventDefault();
    var fd = new FormData(form);
    var data = Object.fromEntries(fd.entries());
    data.is_live = form.is_live.checked ? 1 : 0;

    abFetch('<?= base_url('chatbot-settings') ?>', { method: 'POST', body: data })
      .then(function (res) { abToast(res.message); setTimeout(function () { window.location.reload(); }, 600); })
      .catch(function (err) { abShowFormErrors(form, err.errors); abToast(err.message || 'Save failed.', 'danger'); });
  });
});

document.querySelectorAll('.ab-copy-snippet').forEach(function (btn) {
  btn.addEventListener('click', function () {
    var el = document.getElementById(btn.dataset.target);
    navigator.clipboard.writeText(el.textContent).then(function () {
      if (typeof abToast === 'function') abToast('Snippet copied to clipboard.');
    });
  });
});
</script>