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

<section class="card">
  <h2 class="section-title"><?= $isEdit ? 'Edytuj szablon SMS' : 'Dodaj szablon SMS' ?></h2>
  <p class="muted mt-12">Wpisz tresc wiadomosci ze zmiennymi typu <code>{{zamowienie.numer}}</code>. Stopka SMSPLANET jest doklejana automatycznie przy wysylce, nie dopisuj jej w szablonie.</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">
  <form action="/settings/sms-templates/save" method="post" novalidate class="mt-12" id="js-sms-template-form">
    <input type="hidden" name="_token" value="<?= $e($csrfToken ?? '') ?>">
    <?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. Numer sledzenia">
      </label>
      <div class="form-field sms-template-active-field">
        <label class="sms-template-active-label">
          <input type="checkbox" name="is_active" value="1"<?= $isEdit ? (((int) ($template['is_active'] ?? 0)) === 1 ? ' checked' : '') : ' checked' ?>>
          <span class="field-label sms-template-active-text">Aktywny</span>
        </label>
      </div>
    </div>

    <div class="mt-12">
      <label class="form-field">
        <span class="field-label">Tresc wiadomosci *</span>
        <textarea class="form-control" name="body" id="js-sms-body" rows="6" maxlength="918" required placeholder="np. Czesc {{kupujacy.imie_nazwisko}}, Twoja przesylka {{przesylka.numer}} jest w drodze."><?= $e((string) ($template['body'] ?? '')) ?></textarea>
        <div class="sms-template-counter muted mt-4">
          <span id="js-sms-body-count">0</span> / 918 znakow
          <span class="sms-template-counter-warning" id="js-sms-body-warn" hidden>(pamietaj o stopce dodawanej przez SMSPLANET)</span>
        </div>
      </label>
    </div>

    <div class="sms-var-panel mt-12">
      <div class="sms-var-panel__head">
        <span class="field-label sms-var-panel__title">Dostepne zmienne</span>
        <span class="muted sms-var-panel__hint">Kliknij chip, aby wstawic w pozycji kursora.</span>
      </div>
      <?php foreach ($variableGroups as $groupKey => $group): ?>
        <div class="sms-var-group" data-group="<?= $e($groupKey) ?>">
          <div class="sms-var-group__label"><?= $e((string) ($group['label'] ?? '')) ?></div>
          <div class="sms-var-group__items">
            <?php foreach (($group['vars'] ?? []) as $varKey => $varDesc): ?>
              <button type="button" class="sms-var-item js-sms-var-insert" data-var="{{<?= $e($groupKey . '.' . $varKey) ?>}}" title="<?= $e((string) $varDesc) ?>">
                <code>{{<?= $e($groupKey . '.' . $varKey) ?>}}</code>
                <span class="sms-var-item__desc"><?= $e((string) $varDesc) ?></span>
              </button>
            <?php endforeach; ?>
          </div>
        </div>
      <?php endforeach; ?>
    </div>

    <div class="form-actions mt-16">
      <button type="submit" class="btn btn--primary"><?= $isEdit ? 'Zapisz zmiany' : 'Dodaj szablon' ?></button>
      <a href="/settings/sms-templates" class="btn btn--secondary">Powrot do listy</a>
    </div>
  </form>
</section>

<script>
document.addEventListener('DOMContentLoaded', function () {
  var textarea = document.getElementById('js-sms-body');
  var counter = document.getElementById('js-sms-body-count');
  var warn = document.getElementById('js-sms-body-warn');
  if (!textarea || !counter) return;

  function updateCount() {
    var len = textarea.value.length;
    counter.textContent = String(len);
    if (warn) {
      warn.hidden = len < 700;
    }
  }
  updateCount();
  textarea.addEventListener('input', updateCount);

  document.querySelectorAll('.js-sms-var-insert').forEach(function (btn) {
    btn.addEventListener('click', function () {
      var snippet = btn.getAttribute('data-var') || '';
      var start = textarea.selectionStart || 0;
      var end = textarea.selectionEnd || 0;
      var before = textarea.value.substring(0, start);
      var after = textarea.value.substring(end);
      textarea.value = before + snippet + after;
      var pos = start + snippet.length;
      textarea.focus();
      textarea.setSelectionRange(pos, pos);
      updateCount();
    });
  });
});
</script>
