<?php
$templates = is_array($templates ?? null) ? $templates : [];
$mailboxes = is_array($mailboxes ?? null) ? $mailboxes : [];
$et = is_array($editTemplate ?? null) ? $editTemplate : null;
$isEdit = $et !== null;
$variableGroups = is_array($variableGroups ?? null) ? $variableGroups : [];
$attachmentTypes = is_array($attachmentTypes ?? null) ? $attachmentTypes : [];
?>

<section class="card">
  <h2 class="section-title">Szablony e-mail</h2>
  <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. Dodaj pierwszy szablon ponizej.</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): ?>
            <tr data-id="<?= (int) ($tpl['id'] ?? 0) ?>">
              <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=<?= (int) ($tpl['id'] ?? 0) ?>" 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="<?= (int) ($tpl['id'] ?? 0) ?>">
                  <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="<?= (int) ($tpl['id'] ?? 0) ?>"
                  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="<?= (int) ($tpl['id'] ?? 0) ?>">
                  <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>

<section class="card mt-16">
  <h3 class="section-title"><?= $isEdit ? 'Edytuj szablon' : 'Dodaj szablon' ?></h3>

  <form action="/settings/email-templates/save" method="post" novalidate class="mt-12" id="js-template-form">
    <input type="hidden" name="_token" value="<?= $e($csrfToken ?? '') ?>">
    <input type="hidden" name="body_html" id="js-body-html" value="<?= $e((string) ($et['body_html'] ?? '')) ?>">
    <?php if ($isEdit): ?>
      <input type="hidden" name="id" value="<?= (int) ($et['id'] ?? 0) ?>">
    <?php endif; ?>

    <div class="form-grid-2">
      <label class="form-field">
        <span class="field-label">Nazwa szablonu *</span>
        <input class="form-control" type="text" name="name" maxlength="200" required value="<?= $e((string) ($et['name'] ?? '')) ?>" placeholder="np. Potwierdzenie zamowienia">
      </label>
      <label class="form-field">
        <span class="field-label">Skrzynka nadawcza</span>
        <select class="form-control" name="mailbox_id">
          <option value="">— domyslna —</option>
          <?php foreach ($mailboxes as $mb): ?>
            <option value="<?= (int) ($mb['id'] ?? 0) ?>"<?= ((int) ($et['mailbox_id'] ?? 0)) === (int) ($mb['id'] ?? 0) ? ' selected' : '' ?>>
              <?= $e((string) ($mb['name'] ?? '')) ?> (<?= $e((string) ($mb['sender_email'] ?? '')) ?>)
            </option>
          <?php endforeach; ?>
        </select>
      </label>
    </div>

    <div class="form-grid-2 mt-0">
      <label class="form-field">
        <span class="field-label">Temat wiadomosci *</span>
        <input class="form-control" type="text" name="subject" maxlength="500" required value="<?= $e((string) ($et['subject'] ?? '')) ?>" placeholder="np. Potwierdzenie zamowienia {{zamowienie.numer}}">
      </label>
      <div class="form-field" style="display:flex;align-items:flex-end;gap:8px">
        <label style="display:flex;align-items:center;gap:6px;flex-direction:row">
          <input type="checkbox" name="is_active" value="1"<?= $isEdit ? (((int) ($et['is_active'] ?? 0)) === 1 ? ' checked' : '') : ' checked' ?>>
          <span class="field-label" style="margin:0">Aktywny</span>
        </label>
      </div>
    </div>

    <div class="form-grid-2 mt-0">
      <label class="form-field">
        <span class="field-label">Zalacznik nr 1</span>
        <select class="form-control" name="attachment_1">
          <option value="">— brak —</option>
          <?php foreach ($attachmentTypes as $atKey => $atLabel): ?>
            <option value="<?= $e($atKey) ?>"<?= ((string) ($et['attachment_1'] ?? '')) === $atKey ? ' selected' : '' ?>><?= $e($atLabel) ?></option>
          <?php endforeach; ?>
        </select>
      </label>
      <div class="form-field"></div>
    </div>

    <div class="mt-12">
      <span class="field-label">Tresc wiadomosci *</span>
      <p class="muted mt-4">Dostepne sa zmienne przesylki: <code>{{przesylka.numer}}</code> oraz <code>{{przesylka.link_sledzenia}}</code>.</p>
      <div class="email-tpl-editor-wrap mt-4">
        <div class="email-tpl-toolbar">
          <div class="email-tpl-var-dropdown">
            <button type="button" class="btn btn--sm btn--secondary" id="js-var-toggle">Wstaw zmienna ▾</button>
            <div class="email-tpl-var-panel" id="js-var-panel" style="display:none">
              <?php foreach ($variableGroups as $groupKey => $group): ?>
                <div class="email-var-group">
                  <div class="email-var-group__label"><?= $e((string) ($group['label'] ?? '')) ?></div>
                  <?php foreach (($group['vars'] ?? []) as $varKey => $varDesc): ?>
                    <button type="button" class="email-var-item" data-var="{{<?= $e($groupKey . '.' . $varKey) ?>}}" title="<?= $e((string) $varDesc) ?>">
                      {{<?= $e($groupKey . '.' . $varKey) ?>}}
                    </button>
                  <?php endforeach; ?>
                </div>
              <?php endforeach; ?>
            </div>
          </div>
          <button type="button" class="btn btn--sm btn--secondary" id="js-preview-btn">Podglad</button>
        </div>
        <div id="js-quill-editor"></div>
      </div>
    </div>

    <div class="form-actions mt-16">
      <button type="submit" class="btn btn--primary"><?= $isEdit ? 'Zapisz zmiany' : 'Dodaj szablon' ?></button>
      <?php if ($isEdit): ?>
        <a href="/settings/email-templates" class="btn btn--secondary">Anuluj</a>
      <?php endif; ?>
    </div>
  </form>
</section>

<div class="modal-overlay" id="js-preview-overlay" style="display:none">
  <div class="modal-box">
    <div class="modal-box__header">
      <h3 class="modal-box__title">Podglad szablonu</h3>
      <button type="button" class="modal-box__close" id="js-preview-close">&times;</button>
    </div>
    <div class="modal-box__body">
      <div class="mt-4"><strong>Temat:</strong> <span id="js-preview-subject"></span></div>
      <hr class="mt-8 mb-8">
      <div id="js-preview-body"></div>
    </div>
  </div>
</div>

<link href="https://cdn.quilljs.com/2.0.3/quill.snow.css" rel="stylesheet">
<script src="https://cdn.quilljs.com/2.0.3/quill.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
  var csrfToken = <?= json_encode($csrfToken ?? '', JSON_HEX_TAG) ?>;

  // Quill editor
  var quill = new Quill('#js-quill-editor', {
    theme: 'snow',
    modules: {
      toolbar: [
        [{ header: [1, 2, 3, false] }],
        ['bold', 'italic', 'underline', 'strike'],
        [{ color: [] }, { background: [] }],
        [{ align: [] }],
        [{ list: 'ordered' }, { list: 'bullet' }],
        ['link'],
        ['clean']
      ]
    },
    placeholder: 'Wpisz tresc wiadomosci...'
  });

  // Load existing content
  var existingHtml = document.getElementById('js-body-html').value;
  if (existingHtml) {
    quill.root.innerHTML = existingHtml;
  }

  // Sync on submit
  var form = document.getElementById('js-template-form');
  form.addEventListener('submit', function() {
    document.getElementById('js-body-html').value = quill.root.innerHTML;
  });

  // Variable panel toggle
  var varToggle = document.getElementById('js-var-toggle');
  var varPanel = document.getElementById('js-var-panel');
  varToggle.addEventListener('click', function(e) {
    e.stopPropagation();
    varPanel.style.display = varPanel.style.display === 'none' ? 'block' : 'none';
  });
  document.addEventListener('click', function(e) {
    if (!varPanel.contains(e.target) && e.target !== varToggle) {
      varPanel.style.display = 'none';
    }
  });

  // Insert variable into Quill
  varPanel.addEventListener('click', function(e) {
    var btn = e.target.closest('.email-var-item');
    if (!btn) return;
    var varText = btn.getAttribute('data-var');
    var range = quill.getSelection(true);
    quill.insertText(range.index, varText);
    quill.setSelection(range.index + varText.length);
    varPanel.style.display = 'none';
  });

  // Preview
  var previewBtn = document.getElementById('js-preview-btn');
  var previewOverlay = document.getElementById('js-preview-overlay');
  var previewClose = document.getElementById('js-preview-close');
  var previewSubject = document.getElementById('js-preview-subject');
  var previewBody = document.getElementById('js-preview-body');

  previewBtn.addEventListener('click', function() {
    var subjectVal = form.querySelector('[name="subject"]').value;
    var bodyVal = quill.root.innerHTML;

    previewBtn.disabled = true;
    previewBtn.textContent = 'Ladowanie...';

    var fd = new FormData();
    fd.append('_token', csrfToken);
    fd.append('subject', subjectVal);
    fd.append('body_html', bodyVal);

    fetch('/settings/email-templates/preview', { method: 'POST', body: fd })
      .then(function(r) { return r.json(); })
      .then(function(data) {
        if (data.success) {
          previewSubject.textContent = data.subject;
          previewBody.innerHTML = data.body_html;
          previewOverlay.style.display = 'flex';
        }
      })
      .catch(function() {})
      .finally(function() {
        previewBtn.disabled = false;
        previewBtn.textContent = 'Podglad';
      });
  });

  previewClose.addEventListener('click', function() {
    previewOverlay.style.display = 'none';
  });
  previewOverlay.addEventListener('click', function(e) {
    if (e.target === previewOverlay) previewOverlay.style.display = 'none';
  });

  // Toggle status (AJAX)
  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; });
    });
  });

  // Delete with OrderProAlerts
  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 {
        if (confirm('Czy na pewno chcesz usunac ten szablon e-mail?')) {
          delForm.submit();
        }
      }
    });
  });
});
</script>
