<?php
$currentTab = (string) ($tab ?? 'statuses');
$statusesList = is_array($statuses ?? null) ? $statuses : [];
$errorMessage = (string) ($errorMessage ?? '');
$successMessage = (string) ($successMessage ?? '');
$csrfToken = (string) ($csrfToken ?? '');
?>

<section class="card">
  <h2 class="section-title">Statusy przesyłek</h2>
  <?php if ($errorMessage !== ''): ?>
    <div class="mt-12"><?php $type='danger'; $message=(string) $errorMessage; $dismissible=true; include dirname(__DIR__) . '/components/alert.php'; ?></div>
  <?php endif; ?>
  <?php if ($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">
  <nav class="content-tabs-nav" aria-label="Zakładki">
    <a class="content-tab-btn<?= $currentTab === 'statuses' ? ' is-active' : '' ?>"
       href="/settings/delivery-statuses?tab=statuses">Statusy</a>
    <a class="content-tab-btn<?= $currentTab === 'mapping' ? ' is-active' : '' ?>"
       href="/settings/delivery-statuses?tab=mapping">Mapowanie dostawy</a>
  </nav>

  <?php if ($currentTab === 'statuses'): ?>

    <div class="form-actions mt-16">
      <a href="/settings/delivery-statuses/new" class="btn btn--primary btn--sm">+ Dodaj status</a>
    </div>

    <div class="table-wrapper mt-12">
      <table class="table table--compact">
        <thead>
          <tr>
            <th>Kolor</th>
            <th>Klucz</th>
            <th>Etykieta</th>
            <th>Kolejność</th>
            <th>Końcowy</th>
            <th>Akcje</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($statusesList as $row): ?>
            <?php
            $rowId = (int) ($row['id'] ?? 0);
            $rowKey = (string) ($row['key'] ?? '');
            $rowLabel = (string) ($row['label_pl'] ?? '');
            $rowColor = (string) ($row['color'] ?? '#6c757d');
            $rowSortOrder = (int) ($row['sort_order'] ?? 0);
            $rowIsTerminal = !empty($row['is_terminal']);
            $rowIsSystem = !empty($row['is_system']);
            ?>
            <tr>
              <td>
                <span class="delivery-status-swatch" style="--status-color: <?= $e($rowColor) ?>"></span>
              </td>
              <td><code><?= $e($rowKey) ?></code></td>
              <td><?= $e($rowLabel) ?></td>
              <td><?= $rowSortOrder ?></td>
              <td><?= $rowIsTerminal ? '✓' : '' ?></td>
              <td>
                <?php if (!$rowIsSystem): ?>
                  <a href="/settings/delivery-statuses/<?= $rowId ?>/edit"
                     class="btn btn--sm btn--secondary">Edytuj</a>
                  <button type="button"
                          class="btn btn--sm btn--danger js-ds-delete"
                          data-id="<?= $rowId ?>"
                          data-label="<?= $e($rowLabel) ?>">Usuń</button>
                  <form id="ds-delete-<?= $rowId ?>"
                        action="/settings/delivery-statuses/<?= $rowId ?>/delete"
                        method="post" style="display:none;">
                    <input type="hidden" name="_token" value="<?= $e($csrfToken) ?>">
                  </form>
                <?php else: ?>
                  <span class="muted">—</span>
                <?php endif; ?>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>

  <?php else: ?>

    <?php
    $mappingBaseUrl = '/settings/delivery-statuses?tab=mapping';
    include __DIR__ . '/_delivery-status-mappings-content.php';
    ?>

  <?php endif; ?>
</section>

<script>
(function() {
  // Delete with confirm
  document.querySelectorAll('.js-ds-delete').forEach(function(btn) {
    btn.addEventListener('click', function() {
      var id = btn.getAttribute('data-id');
      var label = btn.getAttribute('data-label') || '';
      var form = document.getElementById('ds-delete-' + id);
      if (!form) return;

      if (window.OrderProAlerts && typeof window.OrderProAlerts.confirm === 'function') {
        window.OrderProAlerts.confirm({
          title: 'Usuń status',
          message: 'Usunąć status "' + label + '"? Operacja jest nieodwracalna.',
          confirmLabel: 'Usuń',
          cancelLabel: 'Anuluj',
          danger: true
        }).then(function(accepted) {
          if (accepted) form.submit();
        });
      } else {
        form.submit();
      }
    });
  });
})();
</script>
