<?php
$templates = is_array($templates ?? null) ? $templates : [];
?>

<section class="card">
  <div class="section-header">
    <h2 class="section-title">Szablony SMS</h2>
    <a href="/settings/sms-templates/create" class="btn btn--primary btn--sm">Dodaj szablon</a>
  </div>
  <p class="muted mt-12">Szybkie szablony wiadomosci SMS do wstawiania z zakladki SMS w szczegolach zamowienia. Stopka SMSPLANET jest doklejana automatycznie.</p>

  <?php if (!empty($errorMessage)): ?>
    <div class="mt-12"><?php $type='danger'; $message=(string) $errorMessage; $dismissible=true; include dirname(__DIR__) . '/components/alert.php'; ?></div>
  <?php endif; ?>
  <?php if (!empty($successMessage)): ?>
    <div class="mt-12"><?php $type='success'; $message=(string) $successMessage; $dismissible=true; include dirname(__DIR__) . '/components/alert.php'; ?></div>
  <?php endif; ?>
</section>

<section class="card mt-16">
  <h3 class="section-title">Lista szablonow</h3>

  <?php if (count($templates) === 0): ?>
    <p class="muted mt-12">Brak szablonow. Kliknij "Dodaj szablon", aby utworzyc pierwszy.</p>
  <?php else: ?>
    <div class="table-wrap mt-12">
      <table class="table">
        <thead>
          <tr>
            <th>Nazwa</th>
            <th>Tresc</th>
            <th>Status</th>
            <th>Akcje</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($templates as $tpl): ?>
            <?php
              $templateId = (int) ($tpl['id'] ?? 0);
              $bodyPreview = trim((string) ($tpl['body'] ?? ''));
              if (function_exists('mb_strlen') ? mb_strlen($bodyPreview) > 80 : strlen($bodyPreview) > 80) {
                  $bodyPreview = (function_exists('mb_substr') ? mb_substr($bodyPreview, 0, 80) : substr($bodyPreview, 0, 80)) . '...';
              }
            ?>
            <tr data-id="<?= $templateId ?>">
              <td><?= $e((string) ($tpl['name'] ?? '')) ?></td>
              <td><?= $e($bodyPreview) ?></td>
              <td>
                <?php if (((int) ($tpl['is_active'] ?? 0)) === 1): ?>
                  <span class="badge badge--success js-status-badge">Aktywny</span>
                <?php else: ?>
                  <span class="badge badge--muted js-status-badge">Nieaktywny</span>
                <?php endif; ?>
              </td>
              <td class="sms-template-actions">
                <a href="/settings/sms-templates/edit?id=<?= $templateId ?>" class="btn btn--sm btn--secondary">Edytuj</a>
                <button type="button" class="btn btn--sm btn--secondary js-toggle-btn"
                  data-id="<?= $templateId ?>"
                  data-active="<?= (int) ($tpl['is_active'] ?? 0) ?>">
                  <?= ((int) ($tpl['is_active'] ?? 0)) === 1 ? 'Dezaktywuj' : 'Aktywuj' ?>
                </button>
                <form action="/settings/sms-templates/delete" method="post" class="inline-form js-confirm-delete" data-confirm-title="Usuwanie szablonu" data-confirm-message="Czy na pewno chcesz usunac ten szablon SMS?">
                  <input type="hidden" name="_token" value="<?= $e($csrfToken ?? '') ?>">
                  <input type="hidden" name="id" value="<?= $templateId ?>">
                  <button type="button" class="btn btn--sm btn--danger js-delete-btn">Usun</button>
                </form>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  <?php endif; ?>
</section>

<script>
document.addEventListener('DOMContentLoaded', function () {
  var csrfToken = <?= json_encode($csrfToken ?? '', JSON_HEX_TAG) ?>;

  document.querySelectorAll('.js-toggle-btn').forEach(function (btn) {
    btn.addEventListener('click', function () {
      var id = this.getAttribute('data-id');
      var isActive = this.getAttribute('data-active') === '1';
      var toggleBtn = this;

      var fd = new FormData();
      fd.append('_token', csrfToken);
      fd.append('id', id);

      toggleBtn.disabled = true;
      fetch('/settings/sms-templates/toggle', { method: 'POST', body: fd })
        .then(function (r) { return r.json(); })
        .then(function (data) {
          if (data.success) {
            var newActive = !isActive;
            toggleBtn.setAttribute('data-active', newActive ? '1' : '0');
            toggleBtn.textContent = newActive ? 'Dezaktywuj' : 'Aktywuj';
            var badge = toggleBtn.closest('tr').querySelector('.js-status-badge');
            if (badge) {
              badge.textContent = newActive ? 'Aktywny' : 'Nieaktywny';
              badge.className = 'badge js-status-badge ' + (newActive ? 'badge--success' : 'badge--muted');
            }
          }
        })
        .catch(function () {})
        .finally(function () { toggleBtn.disabled = false; });
    });
  });
});
</script>
