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

<section class="card">
  <h2 class="section-title"><?= $isEdit ? 'Edytuj szablon e-mail' : 'Dodaj szablon e-mail' ?></h2>
  <p class="muted mt-12">Skonfiguruj temat, tresc i zmienne, ktore beda podstawiane podczas wysylki.</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">
  <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) ($template['body_html'] ?? '')) ?>">
    <?php if ($isEdit): ?>
      <input type="hidden" name="id" value="<?= (int) ($template['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) ($template['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 $mailbox): ?>
            <?php $mailboxId = (int) ($mailbox['id'] ?? 0); ?>
            <option value="<?= $mailboxId ?>"<?= ((int) ($template['mailbox_id'] ?? 0)) === $mailboxId ? ' selected' : '' ?>>
              <?= $e((string) ($mailbox['name'] ?? '')) ?> (<?= $e((string) ($mailbox['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) ($template['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) ($template['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 $attachmentKey => $attachmentLabel): ?>
            <option value="<?= $e($attachmentKey) ?>"<?= ((string) ($template['attachment_1'] ?? '')) === $attachmentKey ? ' selected' : '' ?>><?= $e($attachmentLabel) ?></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>
      <a href="/settings/email-templates" class="btn btn--secondary">Powrot do listy</a>
    </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) ?>;

  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...'
  });

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

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

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

  varPanel.addEventListener('click', function(event) {
    var button = event.target.closest('.email-var-item');
    if (!button) {
      return;
    }

    var variableText = button.getAttribute('data-var');
    var range = quill.getSelection(true);
    quill.insertText(range.index, variableText);
    quill.setSelection(range.index + variableText.length);
    varPanel.style.display = 'none';
  });

  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 formData = new FormData();
    formData.append('_token', csrfToken);
    formData.append('subject', subjectVal);
    formData.append('body_html', bodyVal);

    fetch('/settings/email-templates/preview', { method: 'POST', body: formData })
      .then(function(response) { return response.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(event) {
    if (event.target === previewOverlay) {
      previewOverlay.style.display = 'none';
    }
  });
});
</script>
