<div class="d-flex justify-content-end mb-3">
  <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#abTemplateModal" id="abNewTemplateBtn"><i class="bi bi-plus-lg me-1"></i>New Template</button>
</div>

<div class="row g-3">
  <?php foreach ($rows as $t): ?>
  <div class="col-md-4">
    <div class="ab-card h-100">
      <div class="ab-card-body">
        <div class="d-flex justify-content-between align-items-start">
          <h3 class="fs-6"><?= e($t['name']) ?></h3>
          <div class="dropdown">
            <button class="btn btn-icon btn-light-soft btn-sm" data-bs-toggle="dropdown"><i class="bi bi-three-dots"></i></button>
            <ul class="dropdown-menu dropdown-menu-end">
              <li><a class="dropdown-item ab-edit-template" href="#" data-id="<?= (int) $t['id'] ?>">Edit</a></li>
              <li><a class="dropdown-item text-danger ab-delete-template" href="#" data-id="<?= (int) $t['id'] ?>">Delete</a></li>
            </ul>
          </div>
        </div>
        <span class="ab-badge bg-secondary-soft mb-2"><?= e(ucfirst(str_replace('_',' ',$t['category']))) ?></span>
        <p class="ab-cell-sub mb-1"><?= e($t['subject']) ?></p>
        <div class="small ab-text-faint" style="max-height:60px; overflow:hidden;"><?= strip_tags($t['body_html']) ?></div>
      </div>
    </div>
  </div>
  <?php endforeach; ?>
  <?php if (empty($rows)): ?><div class="col-12"><div class="ab-empty"><i class="bi bi-envelope-paper"></i><h3>No templates yet</h3></div></div><?php endif; ?>
</div>

<div class="modal fade" id="abTemplateModal" tabindex="-1">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header"><h5 class="modal-title" id="abTemplateModalTitle">New Template</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
      <div class="modal-body">
        <form id="abTemplateForm">
          <input type="hidden" name="id">
          <div class="row g-3">
            <div class="col-md-6"><label class="form-label ab-req">Name</label><input class="form-control" name="name" required></div>
            <div class="col-md-6"><label class="form-label ab-req">Category</label>
              <select class="form-select" name="category" required>
                <option value="welcome">Welcome</option><option value="follow_up">Follow-up</option>
                <option value="birthday">Birthday</option><option value="re_engagement">Re-engagement</option>
                <option value="newsletter">Newsletter</option><option value="general">General</option>
              </select>
            </div>
            <div class="col-12"><label class="form-label ab-req">Subject</label><input class="form-control" name="subject" required></div>
            <div class="col-12"><label class="form-label ab-req">Body (HTML)</label><textarea class="form-control" name="body_html" rows="8" required></textarea></div>
          </div>
        </form>
      </div>
      <div class="modal-footer"><button class="btn btn-light-soft" data-bs-dismiss="modal">Cancel</button><button class="btn btn-primary" id="abTemplateSaveBtn">Save Template</button></div>
    </div>
  </div>
</div>

<script>
document.getElementById('abNewTemplateBtn').addEventListener('click', function () {
  var form = document.getElementById('abTemplateForm');
  form.reset(); form.id.value = '';
  document.getElementById('abTemplateModalTitle').textContent = 'New Template';
});

document.querySelectorAll('.ab-edit-template').forEach(function (link) {
  link.addEventListener('click', function (e) {
    e.preventDefault();
    abFetch('<?= base_url('email-templates') ?>/' + this.dataset.id).then(function (res) {
      var t = res.data;
      var form = document.getElementById('abTemplateForm');
      form.id.value = t.id; form.name.value = t.name; form.category.value = t.category;
      form.subject.value = t.subject; form.body_html.value = t.body_html;
      document.getElementById('abTemplateModalTitle').textContent = 'Edit Template';
      new bootstrap.Modal(document.getElementById('abTemplateModal')).show();
    });
  });
});

document.getElementById('abTemplateSaveBtn').addEventListener('click', function () {
  var form = document.getElementById('abTemplateForm');
  var id = form.id.value;
  var data = Object.fromEntries(new FormData(form).entries());
  var url = id ? '<?= base_url('email-templates') ?>/' + id : '<?= base_url('email-templates') ?>';

  abFetch(url, { method: id ? 'PATCH' : 'POST', body: data }).then(function (res) {
    abToast(res.message);
    bootstrap.Modal.getInstance(document.getElementById('abTemplateModal')).hide();
    setTimeout(function () { window.location.reload(); }, 600);
  }).catch(function (err) {
    abShowFormErrors(form, err.errors);
    abToast(err.message || 'Save failed.', 'danger');
  });
});

document.querySelectorAll('.ab-delete-template').forEach(function (link) {
  link.addEventListener('click', function (e) {
    e.preventDefault();
    if (!confirm('Delete this template?')) return;
    abFetch('<?= base_url('email-templates') ?>/' + this.dataset.id, { method: 'DELETE' })
      .then(function (res) { abToast(res.message); setTimeout(function () { window.location.reload(); }, 600); })
      .catch(function (err) { abToast(err.message, 'danger'); });
  });
});
</script>
