<?php
$keysList = is_array($apiKeys ?? null) ? $apiKeys : [];
$newKey = (string) ($newApiKey ?? '');
$jobsList = is_array($printJobs ?? null) ? $printJobs : [];
$currentStatusFilter = (string) ($printStatusFilter ?? '');
?>

<section class="card">
  <h2 class="section-title">Drukowanie</h2>
  <p class="muted mt-12">Klucze API do uwierzytelniania aplikacji drukujacej (Windows Client).</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; ?>

  <?php if ($newKey !== ''): ?>
    <div class="alert alert--warning mt-12">
      <strong>Nowy klucz API:</strong>
      <code id="new-api-key" style="display:inline-block;padding:4px 8px;background:#f5f5f5;border:1px solid #ddd;border-radius:3px;font-size:13px;word-break:break-all;user-select:all"><?= $e($newKey) ?></code>
      <button type="button" class="btn btn--secondary btn--sm ml-8" onclick="navigator.clipboard.writeText(document.getElementById('new-api-key').textContent)">Kopiuj</button>
      <br><small class="muted">Ten klucz nie bedzie ponownie wyswietlony. Skopiuj go teraz.</small>
    </div>
  <?php endif; ?>
</section>

<section class="card mt-16">
  <h3 class="section-title">Klucze API</h3>

  <?php if (count($keysList) === 0): ?>
    <p class="muted mt-12">Brak kluczy API. Utworz pierwszy klucz ponizej.</p>
  <?php else: ?>
    <div class="table-wrap mt-12">
      <table class="table">
        <thead>
          <tr>
            <th>Nazwa</th>
            <th>Prefix</th>
            <th>Status</th>
            <th>Ostatnie uzycie</th>
            <th>Utworzono</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($keysList as $key): ?>
            <tr>
              <td><?= $e((string) ($key['name'] ?? '')) ?></td>
              <td><code><?= $e((string) ($key['key_prefix'] ?? '')) ?>...</code></td>
              <td>
                <?php if ((int) ($key['is_active'] ?? 0) === 1): ?>
                  <span class="badge badge--success">Aktywny</span>
                <?php else: ?>
                  <span class="badge badge--danger">Nieaktywny</span>
                <?php endif; ?>
              </td>
              <td><?= $e((string) ($key['last_used_at'] ?? '-')) ?></td>
              <td><?= $e((string) ($key['created_at'] ?? '')) ?></td>
              <td>
                <form method="post" action="/settings/printing/keys/<?= $e((string) ($key['id'] ?? '')) ?>/delete" style="display:inline" class="js-delete-api-key-form">
                  <input type="hidden" name="_token" value="<?= $e((string) ($csrfToken ?? '')) ?>">
                  <button type="button" class="btn btn--danger btn--sm js-delete-api-key-btn">Usun</button>
                </form>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  <?php endif; ?>
</section>

<section class="card mt-16">
  <h3 class="section-title">Nowy klucz API</h3>
  <form method="post" action="/settings/printing/keys/create" class="mt-12">
    <input type="hidden" name="_token" value="<?= $e((string) ($csrfToken ?? '')) ?>">
    <div class="form-group" style="max-width:400px">
      <label class="form-label" for="key-name">Nazwa klucza</label>
      <input type="text" name="name" id="key-name" class="form-control" placeholder="np. Komputer biurowy" required>
    </div>
    <button type="submit" class="btn btn--primary mt-8">Utworz klucz</button>
  </form>
</section>

<section class="card mt-16">
  <h3 class="section-title">Kolejka wydruku</h3>

  <div class="mt-12 print-queue-filters">
    <a href="/settings/printing" class="btn btn--sm <?= $currentStatusFilter === '' ? 'btn--primary' : 'btn--secondary' ?>">Wszystkie</a>
    <a href="/settings/printing?print_status=pending" class="btn btn--sm <?= $currentStatusFilter === 'pending' ? 'btn--primary' : 'btn--secondary' ?>">Oczekujace</a>
    <a href="/settings/printing?print_status=completed" class="btn btn--sm <?= $currentStatusFilter === 'completed' ? 'btn--primary' : 'btn--secondary' ?>">Wydrukowane</a>
    <a href="/settings/printing?print_status=failed" class="btn btn--sm <?= $currentStatusFilter === 'failed' ? 'btn--primary' : 'btn--secondary' ?>">Nieudane</a>
  </div>

  <?php if (count($jobsList) === 0): ?>
    <p class="muted mt-12">Brak zlecen wydruku<?= $currentStatusFilter !== '' ? ' o statusie "' . $e($currentStatusFilter) . '"' : '' ?>.</p>
  <?php else: ?>
    <div class="table-wrap mt-12">
      <table class="table print-queue-table">
        <thead>
          <tr>
            <th>Data</th>
            <th>Zamowienie</th>
            <th>Tracking</th>
            <th>Status</th>
            <th>Wydrukowano</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($jobsList as $job): ?>
            <?php
            $jobId = (int) ($job['id'] ?? 0);
            $jobStatus = (string) ($job['status'] ?? 'pending');
            $jobOrderNum = trim((string) ($job['order_number'] ?? ''));
            $jobTracking = trim((string) ($job['tracking_number'] ?? ''));
            $jobCreatedAt = (string) ($job['created_at'] ?? '');
            $jobCompletedAt = (string) ($job['completed_at'] ?? '');
            $jobOrderId = (int) ($job['order_id'] ?? 0);
            $jobPackageId = (int) ($job['package_id'] ?? 0);

            $badgeClass = 'print-status-badge--pending';
            $badgeLabel = 'Oczekuje';
            if ($jobStatus === 'completed') {
                $badgeClass = 'print-status-badge--completed';
                $badgeLabel = 'Wydrukowano';
            } elseif ($jobStatus === 'failed') {
                $badgeClass = 'print-status-badge--failed';
                $badgeLabel = 'Blad';
            }
            ?>
            <tr>
              <td class="text-nowrap"><?= $e($jobCreatedAt) ?></td>
              <td>
                <?php if ($jobOrderId > 0): ?>
                  <a href="/orders/<?= $e((string) $jobOrderId) ?>"><?= $e($jobOrderNum !== '' ? $jobOrderNum : '#' . $jobOrderId) ?></a>
                <?php else: ?>
                  -
                <?php endif; ?>
              </td>
              <td><?= $e($jobTracking !== '' ? $jobTracking : '-') ?></td>
              <td><span class="print-status-badge <?= $e($badgeClass) ?>"><?= $e($badgeLabel) ?></span></td>
              <td class="text-nowrap"><?= $e($jobCompletedAt !== '' ? $jobCompletedAt : '-') ?></td>
              <td>
                <div class="print-queue-actions">
                  <?php if ($jobStatus === 'failed' && $jobPackageId > 0): ?>
                    <button type="button"
                      class="btn btn--sm btn--secondary btn-retry-print"
                      data-package-id="<?= $e((string) $jobPackageId) ?>"
                      data-csrf="<?= $e((string) ($csrfToken ?? '')) ?>">Ponow</button>
                  <?php endif; ?>
                  <form method="post" action="/settings/printing/jobs/delete" class="print-queue-delete-form">
                    <input type="hidden" name="_token" value="<?= $e((string) ($csrfToken ?? '')) ?>">
                    <input type="hidden" name="id" value="<?= $e((string) $jobId) ?>">
                    <button
                      type="button"
                      class="btn btn--sm btn--danger js-delete-print-job"
                      data-job-id="<?= $e((string) $jobId) ?>"
                    >Usun</button>
                  </form>
                </div>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  <?php endif; ?>
</section>

<script>
(function () {
  document.querySelectorAll('.js-delete-print-job').forEach(function (btn) {
    btn.addEventListener('click', function () {
      var form = btn.closest('form');
      if (!form) return;
      if (window.OrderProAlerts && window.OrderProAlerts.confirm) {
        window.OrderProAlerts.confirm({
          title: 'Usuwanie wpisu z kolejki',
          message: 'Czy na pewno chcesz usunac ten wpis kolejki wydruku?',
          confirmLabel: 'Usun',
          cancelLabel: 'Anuluj',
          danger: true
        }).then(function (confirmed) {
          if (confirmed) {
            form.submit();
          }
        });
      } else {
        form.submit();
      }
    });
  });

  document.querySelectorAll('.js-delete-api-key-btn').forEach(function (btn) {
    btn.addEventListener('click', function () {
      var form = btn.closest('form');
      if (!form) return;
      if (window.OrderProAlerts && window.OrderProAlerts.confirm) {
        window.OrderProAlerts.confirm({
          title: 'Usuwanie klucza API',
          message: 'Czy na pewno chcesz usunac ten klucz API?',
          confirmLabel: 'Usun',
          cancelLabel: 'Anuluj',
          danger: true
        }).then(function (confirmed) {
          if (confirmed) {
            form.submit();
          }
        });
      } else {
        form.submit();
      }
    });
  });

  document.querySelectorAll('.btn-retry-print').forEach(function (btn) {
    btn.addEventListener('click', function () {
      var packageId = btn.getAttribute('data-package-id');
      var csrf = btn.getAttribute('data-csrf');
      if (!packageId || !csrf) return;

      btn.disabled = true;
      btn.textContent = 'Wysylam...';

      fetch('/api/print/jobs', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: '_token=' + encodeURIComponent(csrf) + '&package_id=' + encodeURIComponent(packageId)
      })
      .then(function (r) { return r.json().then(function (d) { return { status: r.status, data: d }; }); })
      .then(function (res) {
        if (res.status === 201) {
          window.location.reload();
        } else {
          var msg = (res.data && res.data.error) ? res.data.error : 'Nieznany blad';
          if (window.OrderProAlerts) {
            window.OrderProAlerts.show({ message: msg, type: 'error' });
          }
          btn.disabled = false;
          btn.textContent = 'Ponow';
        }
      })
      .catch(function () {
        if (window.OrderProAlerts) {
          window.OrderProAlerts.show({ message: 'Blad sieci.', type: 'error' });
        }
        btn.disabled = false;
        btn.textContent = 'Ponow';
      });
    });
  });
})();
</script>
