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

<section class="card">
  <div class="section-header">
    <h2 class="section-title">Szablony e-mail</h2>
    <a href="/settings/email-templates/create" class="btn btn--primary btn--sm">Dodaj szablon</a>
  </div>
  <p class="muted mt-12">Szablony wiadomosci e-mail z edytorem i systemem zmiennych.</p>

  <?php if (!empty($errorMessage)): ?>
    <div class="alert alert--danger mt-12" role="alert"><?= $e((string) $errorMessage) ?></div>
  <?php endif; ?>
  <?php if (!empty($successMessage)): ?>
    <div class="alert alert--success mt-12" role="status"><?= $e((string) $successMessage) ?></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>Temat</th>
            <th>Skrzynka</th>
            <th>Zalacznik</th>
            <th>Status</th>
            <th>Akcje</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($templates as $tpl): ?>
            <?php $templateId = (int) ($tpl['id'] ?? 0); ?>
            <tr data-id="<?= $templateId ?>">
              <td><?= $e((string) ($tpl['name'] ?? '')) ?></td>
              <td><?= $e((string) ($tpl['subject'] ?? '')) ?></td>
              <td><?= $e((string) ($tpl['mailbox_name'] ?? '-')) ?></td>
              <td><?= isset($tpl['attachment_1'], $attachmentTypes[$tpl['attachment_1']]) ? $e($attachmentTypes[$tpl['attachment_1']]) : '-' ?></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 style="white-space:nowrap">
                <a href="/settings/email-templates/edit?id=<?= $templateId ?>" class="btn btn--sm btn--secondary">Edytuj</a>
                <form action="/settings/email-templates/duplicate" method="post" style="display:inline">
                  <input type="hidden" name="_token" value="<?= $e($csrfToken ?? '') ?>">
                  <input type="hidden" name="id" value="<?= $templateId ?>">
                  <button type="submit" class="btn btn--sm btn--secondary">Duplikuj</button>
                </form>
                <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/email-templates/delete" method="post" style="display:inline" class="js-confirm-delete">
                  <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/email-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; });
    });
  });

  document.querySelectorAll('.js-delete-btn').forEach(function(btn) {
    btn.addEventListener('click', function() {
      var delForm = this.closest('form');
      if (window.OrderProAlerts && window.OrderProAlerts.confirm) {
        window.OrderProAlerts.confirm(
          'Usuwanie szablonu',
          'Czy na pewno chcesz usunac ten szablon e-mail?',
          function() { delForm.submit(); }
        );
      } else {
        delForm.submit();
      }
    });
  });
});
</script>
