<?php
$providersList = is_array($providers ?? null) ? $providers : [];
$mappingsList = is_array($mappings ?? null) ? $mappings : [];
$normalizedOptionsList = is_array($normalizedOptions ?? null) ? $normalizedOptions : [];
$currentProvider = (string) ($provider ?? 'inpost');
?>

<section class="card">
  <h2 class="section-title">Mapowanie statusów dostawy</h2>
  <p class="muted mt-12">Konfiguracja przypisania surowych statusów z API przewoźników do znormalizowanych statusów w aplikacji.</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">
  <nav class="content-tabs-nav" aria-label="Wybierz przewoźnika">
    <?php foreach ($providersList as $provKey => $provLabel): ?>
      <a class="content-tab-btn<?= $currentProvider === $provKey ? ' is-active' : '' ?>"
         href="/settings/delivery-status-mappings?provider=<?= $e(rawurlencode($provKey)) ?>">
        <?= $e($provLabel) ?>
      </a>
    <?php endforeach; ?>
  </nav>

  <?php if ($mappingsList === []): ?>
    <p class="muted mt-16">Brak mapowań dla tego przewoźnika.</p>
  <?php else: ?>
    <form id="dsm-bulk-form" action="/settings/delivery-status-mappings/save-bulk" method="post" class="mt-16">
      <input type="hidden" name="_token" value="<?= $e($csrfToken ?? '') ?>">
      <input type="hidden" name="provider" value="<?= $e($currentProvider) ?>">

      <div class="table-wrapper">
        <table class="table table--compact">
          <thead>
            <tr>
              <th>Status surowy</th>
              <th>Opis</th>
              <th>Status znormalizowany</th>
              <th>Akcje</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($mappingsList as $mapping): ?>
              <?php
              $rawStatus = (string) ($mapping['raw_status'] ?? '');
              $desc = (string) ($mapping['description'] ?? '');
              $normalized = (string) ($mapping['normalized_status'] ?? '');
              $isCustom = !empty($mapping['is_custom']);
              ?>
              <tr class="<?= $isCustom ? 'dsm-row--custom' : '' ?>">
                <td>
                  <code class="dsm-raw-status"><?= $e($rawStatus) ?></code>
                  <input type="hidden" name="raw_status[]" value="<?= $e($rawStatus) ?>">
                </td>
                <td>
                  <input type="text" name="description[]" class="form-control form-control--sm"
                         value="<?= $e($desc) ?>" maxlength="255">
                </td>
                <td>
                  <select name="normalized_status[]" class="form-control form-control--sm">
                    <?php foreach ($normalizedOptionsList as $optValue => $optLabel): ?>
                      <option value="<?= $e($optValue) ?>"<?= $optValue === $normalized ? ' selected' : '' ?>>
                        <?= $e($optLabel) ?>
                      </option>
                    <?php endforeach; ?>
                  </select>
                </td>
                <td>
                  <?php if ($isCustom): ?>
                    <button type="button" class="btn btn--danger btn--sm js-dsm-reset"
                            data-raw-status="<?= $e($rawStatus) ?>"
                            data-confirm-msg="Przywrócić domyślne mapowanie dla &quot;<?= $e($rawStatus) ?>&quot;?">Resetuj</button>
                  <?php else: ?>
                    <span class="muted">domyślne</span>
                  <?php endif; ?>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>

      <div class="form-actions mt-16">
        <button type="submit" class="btn btn--primary">Zapisz wszystkie</button>
        <button type="button" class="btn btn--danger" id="js-dsm-reset-all">Resetuj wszystkie</button>
      </div>
    </form>

    <form id="dsm-reset-all-form" action="/settings/delivery-status-mappings/reset-all" method="post" style="display:none;">
      <input type="hidden" name="_token" value="<?= $e($csrfToken ?? '') ?>">
      <input type="hidden" name="provider" value="<?= $e($currentProvider) ?>">
    </form>

    <form id="dsm-reset-form" action="/settings/delivery-status-mappings/reset" method="post" style="display:none;">
      <input type="hidden" name="_token" value="<?= $e($csrfToken ?? '') ?>">
      <input type="hidden" name="provider" value="<?= $e($currentProvider) ?>">
      <input type="hidden" name="raw_status" id="dsm-reset-raw-status" value="">
    </form>
  <?php endif; ?>
</section>

<script>
(function() {
  var resetForm = document.getElementById('dsm-reset-form');
  var resetInput = document.getElementById('dsm-reset-raw-status');
  if (!resetForm || !resetInput) return;

  var resetAllBtn = document.getElementById('js-dsm-reset-all');
  var resetAllForm = document.getElementById('dsm-reset-all-form');
  if (resetAllBtn && resetAllForm) {
    resetAllBtn.addEventListener('click', function() {
      if (window.OrderProAlerts && typeof window.OrderProAlerts.confirm === 'function') {
        window.OrderProAlerts.confirm({
          title: 'Resetuj wszystkie mapowania',
          message: 'Przywrócić wszystkie mapowania do domyślnych dla tego przewoźnika?',
          confirmLabel: 'Resetuj wszystkie',
          cancelLabel: 'Anuluj',
          danger: true
        }).then(function(accepted) {
          if (!accepted) return;
          resetAllForm.submit();
        });
      } else {
        resetAllForm.submit();
      }
    });
  }

  document.querySelectorAll('.js-dsm-reset').forEach(function(btn) {
    btn.addEventListener('click', function() {
      var rawStatus = btn.getAttribute('data-raw-status') || '';
      var message = btn.getAttribute('data-confirm-msg') || 'Przywrócić domyślne?';

      if (window.OrderProAlerts && typeof window.OrderProAlerts.confirm === 'function') {
        window.OrderProAlerts.confirm({
          title: 'Resetuj mapowanie',
          message: message,
          confirmLabel: 'Resetuj',
          cancelLabel: 'Anuluj',
          danger: true
        }).then(function(accepted) {
          if (!accepted) return;
          resetInput.value = rawStatus;
          resetForm.submit();
        });
      } else {
        resetInput.value = rawStatus;
        resetForm.submit();
      }
    });
  });
})();
</script>
