<?php
$rules = is_array($rules ?? null) ? $rules : [];
$historyEntries = is_array($historyEntries ?? null) ? $historyEntries : [];
$historyFilters = is_array($historyFilters ?? null) ? $historyFilters : [];
$historyEventTypes = is_array($historyEventTypes ?? null) ? $historyEventTypes : [];
$historyRuleOptions = is_array($historyRuleOptions ?? null) ? $historyRuleOptions : [];
$historyPagination = is_array($historyPagination ?? null) ? $historyPagination : [];
$activeTab = (string) ($activeTab ?? 'settings');

$historyPage = max(1, (int) ($historyPagination['page'] ?? 1));
$historyTotalPages = max(1, (int) ($historyPagination['total_pages'] ?? 1));
$historyTotal = max(0, (int) ($historyPagination['total'] ?? 0));

$eventLabels = [
    'receipt.created' => 'Utworzono paragon',
    'shipment.created' => 'Utworzenie przesylki',
    'shipment.status_changed' => 'Zmiana statusu przesylki',
    'payment.status_changed' => 'Zmiana statusu platnosci',
    'order.status_changed' => 'Zmiana statusu zamowienia',
    'order.status_aged' => 'Minelo X dni od zmiany statusu',
];

$statusLabels = [
    'success' => 'Sukces',
    'failed' => 'Blad',
];

$historyFiltersDefault = [
    'history_event_type' => (string) ($historyFilters['event_type'] ?? ''),
    'history_status' => (string) ($historyFilters['execution_status'] ?? ''),
    'history_rule_id' => (int) ($historyFilters['rule_id'] ?? 0),
    'history_order_id' => (int) ($historyFilters['order_id'] ?? 0),
    'history_date_from' => (string) ($historyFilters['date_from'] ?? ''),
    'history_date_to' => (string) ($historyFilters['date_to'] ?? ''),
    'tab' => 'history',
];

$buildHistoryUrl = static function (array $overrides = []) use ($historyFiltersDefault): string {
    $params = array_merge($historyFiltersDefault, $overrides);
    foreach ($params as $key => $value) {
        if (is_int($value) && $value <= 0) {
            $params[$key] = '';
        }
    }

    return '/settings/automation?' . http_build_query($params);
};
?>

<section class="card">
  <div class="section-header">
    <h2 class="section-title">Zadania automatyczne</h2>
    <a href="/settings/automation/create" class="btn btn--primary btn--sm">Dodaj zadanie</a>
  </div>
  <p class="muted mt-8">Reguly automatyzacji wykonywane po wystapieniu zdarzenia.</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; ?>

  <nav class="content-tabs-nav mt-12" aria-label="Zakladki automatyzacji">
    <button type="button" class="content-tab-btn<?= $activeTab === 'settings' ? ' is-active' : '' ?>" data-tab-target="automation-tab-settings">Ustawienia</button>
    <button type="button" class="content-tab-btn<?= $activeTab === 'history' ? ' is-active' : '' ?>" data-tab-target="automation-tab-history">Historia</button>
  </nav>

  <div class="content-tab-panel<?= $activeTab === 'settings' ? ' is-active' : '' ?>" data-tab-panel="automation-tab-settings">
    <?php if (count($rules) === 0): ?>
      <p class="muted mt-12">Brak zadan automatycznych. Kliknij "Dodaj zadanie" aby utworzyc pierwsza regule.</p>
    <?php else: ?>
      <div class="table-wrap mt-12">
        <table class="table">
          <thead>
            <tr>
              <th>Nazwa</th>
              <th>Zdarzenie</th>
              <th>Warunkow</th>
              <th>Akcji</th>
              <th>Status</th>
              <th>Akcje</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($rules as $rule): ?>
              <tr>
                <td><?= $e((string) ($rule['name'] ?? '')) ?></td>
                <td><?= $e($eventLabels[(string) ($rule['event_type'] ?? '')] ?? (string) ($rule['event_type'] ?? '')) ?></td>
                <td><?= (int) ($rule['conditions_count'] ?? 0) ?></td>
                <td><?= (int) ($rule['actions_count'] ?? 0) ?></td>
                <td>
                  <?php if (((int) ($rule['is_active'] ?? 0)) === 1): ?>
                    <span class="badge badge--success">Aktywne</span>
                  <?php else: ?>
                    <span class="badge badge--muted">Nieaktywne</span>
                  <?php endif; ?>
                </td>
                <td class="automation-actions-cell">
                  <a href="/settings/automation/edit?id=<?= (int) ($rule['id'] ?? 0) ?>" class="btn btn--sm btn--secondary">Edytuj</a>
                  <form action="/settings/automation/duplicate" method="post" class="automation-inline-form">
                    <input type="hidden" name="_token" value="<?= $e($csrfToken ?? '') ?>">
                    <input type="hidden" name="id" value="<?= (int) ($rule['id'] ?? 0) ?>">
                    <button type="submit" class="btn btn--sm btn--secondary">Duplikuj</button>
                  </form>
                  <form action="/settings/automation/toggle" method="post" class="automation-inline-form">
                    <input type="hidden" name="_token" value="<?= $e($csrfToken ?? '') ?>">
                    <input type="hidden" name="id" value="<?= (int) ($rule['id'] ?? 0) ?>">
                    <button type="submit" class="btn btn--sm btn--secondary">
                      <?= ((int) ($rule['is_active'] ?? 0)) === 1 ? 'Dezaktywuj' : 'Aktywuj' ?>
                    </button>
                  </form>
                  <form action="/settings/automation/delete" method="post" class="automation-inline-form js-confirm-delete">
                    <input type="hidden" name="_token" value="<?= $e($csrfToken ?? '') ?>">
                    <input type="hidden" name="id" value="<?= (int) ($rule['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; ?>
  </div>

  <div class="content-tab-panel<?= $activeTab === 'history' ? ' is-active' : '' ?>" data-tab-panel="automation-tab-history">
    <form method="get" action="/settings/automation" class="automation-history-filters mt-12">
      <input type="hidden" name="tab" value="history">

      <label class="form-field">
        <span class="field-label">Zdarzenie</span>
        <select class="form-control" name="history_event_type">
          <option value="">Wszystkie</option>
          <?php foreach ($historyEventTypes as $eventType): ?>
            <?php $eventTypeString = (string) $eventType; ?>
            <option value="<?= $e($eventTypeString) ?>"<?= $eventTypeString === (string) ($historyFilters['event_type'] ?? '') ? ' selected' : '' ?>>
              <?= $e($eventLabels[$eventTypeString] ?? $eventTypeString) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </label>

      <label class="form-field">
        <span class="field-label">Status</span>
        <select class="form-control" name="history_status">
          <option value="">Wszystkie</option>
          <?php foreach ($statusLabels as $statusKey => $statusLabel): ?>
            <option value="<?= $e($statusKey) ?>"<?= $statusKey === (string) ($historyFilters['execution_status'] ?? '') ? ' selected' : '' ?>>
              <?= $e($statusLabel) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </label>

      <label class="form-field">
        <span class="field-label">Regula</span>
        <select class="form-control" name="history_rule_id">
          <option value="0">Wszystkie</option>
          <?php foreach ($historyRuleOptions as $ruleOption): ?>
            <?php $ruleOptionId = (int) ($ruleOption['id'] ?? 0); ?>
            <option value="<?= $ruleOptionId ?>"<?= $ruleOptionId === (int) ($historyFilters['rule_id'] ?? 0) ? ' selected' : '' ?>>
              <?= $e((string) ($ruleOption['name'] ?? '')) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </label>

      <label class="form-field">
        <span class="field-label">ID zamowienia</span>
        <input class="form-control" type="number" min="1" step="1" name="history_order_id" value="<?= (int) ($historyFilters['order_id'] ?? 0) > 0 ? $e((string) (int) ($historyFilters['order_id'] ?? 0)) : '' ?>">
      </label>

      <label class="form-field">
        <span class="field-label">Data od</span>
        <input class="form-control" type="date" name="history_date_from" value="<?= $e((string) ($historyFilters['date_from'] ?? '')) ?>">
      </label>

      <label class="form-field">
        <span class="field-label">Data do</span>
        <input class="form-control" type="date" name="history_date_to" value="<?= $e((string) ($historyFilters['date_to'] ?? '')) ?>">
      </label>

      <div class="automation-history-filters__actions">
        <button type="submit" class="btn btn--primary btn--sm">Filtruj</button>
        <a href="/settings/automation?tab=history" class="btn btn--secondary btn--sm">Wyczysc</a>
      </div>
    </form>

    <div class="table-wrap mt-12">
      <table class="table">
        <thead>
          <tr>
            <th>Kiedy</th>
            <th>Zdarzenie</th>
            <th>Regula</th>
            <th>Zamowienie</th>
            <th>Status</th>
            <th>Wynik</th>
          </tr>
        </thead>
        <tbody>
          <?php if ($historyEntries === []): ?>
            <tr>
              <td class="muted" colspan="6">Brak wpisow historii dla wybranych filtrow.</td>
            </tr>
          <?php else: ?>
            <?php foreach ($historyEntries as $entry): ?>
              <?php
                $entryStatus = (string) ($entry['execution_status'] ?? '');
                $entryOrderId = (int) ($entry['order_id'] ?? 0);
              ?>
              <tr>
                <td><?= $e((string) ($entry['executed_at'] ?? '')) ?></td>
                <td><?= $e($eventLabels[(string) ($entry['event_type'] ?? '')] ?? (string) ($entry['event_type'] ?? '')) ?></td>
                <td><?= $e((string) ($entry['rule_name'] ?? '')) ?></td>
                <td>
                  <?php if ($entryOrderId > 0): ?>
                    <a href="/orders/<?= $entryOrderId ?>">#<?= $entryOrderId ?></a>
                  <?php else: ?>
                    <span class="muted">-</span>
                  <?php endif; ?>
                </td>
                <td>
                  <?php if ($entryStatus === 'success'): ?>
                    <span class="badge badge--success">Sukces</span>
                  <?php elseif ($entryStatus === 'failed'): ?>
                    <span class="badge badge--danger">Blad</span>
                  <?php else: ?>
                    <span class="badge badge--muted"><?= $e($entryStatus) ?></span>
                  <?php endif; ?>
                </td>
                <td><?= $e((string) ($entry['result_message'] ?? '')) ?></td>
              </tr>
            <?php endforeach; ?>
          <?php endif; ?>
        </tbody>
      </table>
    </div>

    <?php if ($historyTotalPages > 1): ?>
      <div class="table-list__footer">
        <div class="pagination">
          <a class="pagination__item<?= $historyPage <= 1 ? ' is-disabled' : '' ?>" href="<?= $e($buildHistoryUrl(['history_page' => 1])) ?>">&laquo;</a>
          <a class="pagination__item<?= $historyPage <= 1 ? ' is-disabled' : '' ?>" href="<?= $e($buildHistoryUrl(['history_page' => max(1, $historyPage - 1)])) ?>">&lsaquo;</a>

          <?php $startPage = max(1, $historyPage - 2); ?>
          <?php $endPage = min($historyTotalPages, $historyPage + 2); ?>
          <?php for ($page = $startPage; $page <= $endPage; $page++): ?>
            <a class="pagination__item<?= $page === $historyPage ? ' is-active' : '' ?>" href="<?= $e($buildHistoryUrl(['history_page' => $page])) ?>">
              <?= $e((string) $page) ?>
            </a>
          <?php endfor; ?>

          <a class="pagination__item<?= $historyPage >= $historyTotalPages ? ' is-disabled' : '' ?>" href="<?= $e($buildHistoryUrl(['history_page' => min($historyTotalPages, $historyPage + 1)])) ?>">&rsaquo;</a>
          <a class="pagination__item<?= $historyPage >= $historyTotalPages ? ' is-disabled' : '' ?>" href="<?= $e($buildHistoryUrl(['history_page' => $historyTotalPages])) ?>">&raquo;</a>
        </div>
        <div class="muted">Strona <?= $e((string) $historyPage) ?> z <?= $e((string) $historyTotalPages) ?>, wpisow: <?= $e((string) $historyTotal) ?></div>
      </div>
    <?php endif; ?>
  </div>
</section>

<script>
document.addEventListener('DOMContentLoaded', function() {
  var tabStorageKey = 'settings_automation_active_tab';
  var tabs = document.querySelectorAll('[data-tab-target]');
  var panels = document.querySelectorAll('[data-tab-panel]');
  var tabsByTarget = {};
  tabs.forEach(function(tab) {
    var target = tab.getAttribute('data-tab-target');
    if (target) {
      tabsByTarget[target] = tab;
    }
  });

  function activateTab(target, persist) {
    if (!tabsByTarget[target]) {
      return;
    }
    tabs.forEach(function(node) { node.classList.remove('is-active'); });
    panels.forEach(function(panel) { panel.classList.remove('is-active'); });
    tabsByTarget[target].classList.add('is-active');
    var panel = document.querySelector('[data-tab-panel="' + target + '"]');
    if (panel) {
      panel.classList.add('is-active');
    }
    if (persist) {
      try {
        window.localStorage.setItem(tabStorageKey, target);
      } catch (error) {
        // Ignorujemy brak dostepu do localStorage.
      }
    }
  }

  var params = new URLSearchParams(window.location.search);
  var explicitTab = params.get('tab');
  var hasHistoryQuery = [
    'history_event_type',
    'history_status',
    'history_rule_id',
    'history_order_id',
    'history_date_from',
    'history_date_to',
    'history_page'
  ].some(function(key) {
    var value = params.get(key);
    return value !== null && value !== '' && value !== '0';
  });

  if (explicitTab !== 'settings' && explicitTab !== 'history' && !hasHistoryQuery) {
    try {
      var savedTab = window.localStorage.getItem(tabStorageKey);
      if (savedTab) {
        activateTab(savedTab, false);
      }
    } catch (error) {
      // Ignorujemy brak dostepu do localStorage.
    }
  } else if (explicitTab === 'history') {
    activateTab('automation-tab-history', true);
  } else if (explicitTab === 'settings') {
    activateTab('automation-tab-settings', true);
  }

  tabs.forEach(function(tab) {
    tab.addEventListener('click', function() {
      var target = tab.getAttribute('data-tab-target');
      activateTab(target, true);
    });
  });

  document.querySelectorAll('.js-delete-btn').forEach(function(btn) {
    btn.addEventListener('click', function() {
      var form = this.closest('form');
      if (window.OrderProAlerts && typeof window.OrderProAlerts.confirm === 'function') {
        window.OrderProAlerts.confirm(
          'Usuwanie zadania',
          'Czy na pewno chcesz usunac to zadanie automatyczne?',
          function() { form.submit(); }
        );
        return;
      }
      form.submit();
    });
  });
});
</script>
