<?php
$orderRow = is_array($order ?? null) ? $order : [];
$itemsList = is_array($items ?? null) ? $items : [];
$addressesList = is_array($addresses ?? null) ? $addresses : [];
$paymentsList = is_array($payments ?? null) ? $payments : [];
$shipmentsList = is_array($shipments ?? null) ? $shipments : [];
$packagesList = is_array($packages ?? null) ? $packages : [];
$documentsList = is_array($documents ?? null) ? $documents : [];
$notesList = is_array($notes ?? null) ? $notes : [];
$receiptsList = is_array($receipts ?? null) ? $receipts : [];
$receiptConfigsList = is_array($receiptConfigs ?? null) ? $receiptConfigs : [];
$emailTemplatesList = is_array($emailTemplates ?? null) ? $emailTemplates : [];
$emailMailboxesList = is_array($emailMailboxes ?? null) ? $emailMailboxes : [];
$historyList = is_array($history ?? null) ? $history : [];
$activityLogList = is_array($activityLog ?? null) ? $activityLog : [];
$statusPanelList = is_array($statusPanel ?? null) ? $statusPanel : [];
$statusPanelTitle = 'Statusy';
$allStatusesList = is_array($allStatuses ?? null) ? $allStatuses : [];
$currentStatusCodeValue = (string) ($currentStatusCode ?? '');
$flashSuccessMsg = (string) ($flashSuccess ?? '');
$flashErrorMsg = (string) ($flashError ?? '');
$carrierRaw = (string) ($orderRow['external_carrier_id'] ?? '');
$carrierDisplay = trim(html_entity_decode(strip_tags($carrierRaw), ENT_QUOTES | ENT_HTML5, 'UTF-8'));

$addressByType = [
    'customer' => null,
    'invoice' => null,
    'delivery' => null,
];
foreach ($addressesList as $address) {
    $type = (string) ($address['address_type'] ?? '');
    if ($type !== '' && array_key_exists($type, $addressByType) && $addressByType[$type] === null) {
        $addressByType[$type] = $address;
    }
}
?>

<section class="order-show-layout">
  <?php require __DIR__ . '/../components/order-status-panel.php'; ?>

  <div class="order-show-main">
    <section class="card order-details-page">
      <div class="order-details-head">
        <div>
          <a href="/orders/list" class="order-back-link">&larr; <?= $e($t('navigation.orders_list')) ?></a>
          <h2 class="section-title mt-12"><?= $e($t('orders.details.title')) ?> <?= $e((string) ($orderRow['internal_order_number'] ?? ('#' . ($orderId ?? 0)))) ?></h2>
          <div class="order-details-sub mt-12">
            <?php
              $sourceLabel = trim((string) ($orderRow['integration_name'] ?? ''));
              if ($sourceLabel === '') {
                  $sourceLabel = ucfirst((string) ($orderRow['source'] ?? ''));
              }
            ?>
            <span><?= $e($sourceLabel) ?></span>
            <span>ID: <?= $e((string) ($orderRow['external_order_id'] ?? '')) ?></span>
          </div>
        </div>
        <div class="order-details-actions">
          <button type="button" class="btn btn--secondary btn--disabled">Strefa klienta</button>
          <a href="/orders/<?= $e((string) ($orderId ?? 0)) ?>/shipment/prepare" class="btn btn--primary">Przygotuj przesylke</a>
          <?php if ($receiptConfigsList !== []): ?>
            <a href="/orders/<?= $e((string) ($orderId ?? 0)) ?>/receipt/create" class="btn btn--secondary">Wystaw paragon</a>
          <?php endif; ?>
          <?php
          $emailBuyerAddr = '';
          foreach ($addressesList as $a) {
              if (trim((string) ($a['email'] ?? '')) !== '') { $emailBuyerAddr = trim((string) $a['email']); break; }
          }
          $emailBtnEnabled = $emailTemplatesList !== [] && $emailMailboxesList !== [] && $emailBuyerAddr !== '';
          ?>
          <?php if ($emailBtnEnabled): ?>
            <button type="button" class="btn btn--secondary" id="btn-send-email">Wyslij e-mail</button>
          <?php else: ?>
            <button type="button" class="btn btn--secondary btn--disabled" title="Skonfiguruj skrzynke i szablony w Ustawieniach">Wyslij e-mail</button>
          <?php endif; ?>
          <button type="button" class="btn btn--secondary" id="btn-header-payment">Platnosc</button>
          <button type="button" class="btn btn--secondary btn--disabled">Drukuj</button>
          <button type="button" class="btn btn--primary btn--disabled">Pakuj</button>
          <button type="button" class="btn btn--secondary btn--disabled">Edytuj</button>
        </div>
      </div>
      <?php if ($flashSuccessMsg !== ''): ?>
        <div class="flash flash--success mt-12"><?= $e($flashSuccessMsg) ?></div>
      <?php endif; ?>
      <?php if ($flashErrorMsg !== ''): ?>
        <div class="flash flash--error mt-12"><?= $e($flashErrorMsg) ?></div>
      <?php endif; ?>

      <div class="order-status-change mt-12">
        <span class="order-details-pill"><?= $e((string) ($statusLabel ?? '-')) ?></span>
        <?php if ($allStatusesList !== []): ?>
          <form method="post" action="/orders/<?= $e((string) ($orderId ?? 0)) ?>/status" class="order-status-change__form">
            <input type="hidden" name="_token" value="<?= $e((string) ($csrfToken ?? '')) ?>">
            <select name="new_status" class="input input--sm order-status-change__select">
              <option value=""><?= $e($t('orders.details.status_change.placeholder')) ?></option>
              <?php
              $lastGroup = null;
              foreach ($allStatusesList as $statusOption):
                  $optCode = (string) ($statusOption['code'] ?? '');
                  $optName = (string) ($statusOption['name'] ?? $optCode);
                  $optGroup = (string) ($statusOption['group'] ?? '');
                  if ($optGroup !== $lastGroup):
                      if ($lastGroup !== null): ?>
                        </optgroup>
                      <?php endif;
                      if ($optGroup !== ''): ?>
                        <optgroup label="<?= $e($optGroup) ?>">
                      <?php endif;
                      $lastGroup = $optGroup;
                  endif;
              ?>
                <option value="<?= $e($optCode) ?>"<?= $optCode === $currentStatusCodeValue ? ' selected' : '' ?>><?= $e($optName) ?></option>
              <?php endforeach;
              if ($lastGroup !== null && $lastGroup !== ''): ?>
                </optgroup>
              <?php endif; ?>
            </select>
            <button type="submit" class="btn btn--primary btn--sm"><?= $e($t('orders.details.status_change.save')) ?></button>
          </form>
        <?php endif; ?>
      </div>
    </section>

    <section class="card mt-16 order-details-tabs">
      <button type="button" class="order-details-tab is-active" data-order-tab-target="details"><?= $e($t('orders.details.tabs.details')) ?></button>
      <button type="button" class="order-details-tab" data-order-tab-target="history"><?= $e($t('orders.details.tabs.history')) ?> (<?= $e((string) count($activityLogList)) ?>)</button>
      <button type="button" class="order-details-tab" data-order-tab-target="shipments"><?= $e($t('orders.details.tabs.shipments')) ?> (<?= $e((string) (count($shipmentsList) + count($packagesList))) ?>)</button>
      <button type="button" class="order-details-tab" data-order-tab-target="payments"><?= $e($t('orders.details.tabs.payments')) ?> (<?= $e((string) count($paymentsList)) ?>)</button>
      <button type="button" class="order-details-tab" data-order-tab-target="documents"><?= $e($t('orders.details.tabs.documents')) ?> (<?= $e((string) (count($documentsList) + count($receiptsList))) ?>)</button>
    </section>

    <div class="order-tab-panel is-active" data-order-tab-panel="details">
      <section class="card mt-16">
        <h3 class="section-title"><?= $e($t('orders.details.items_title')) ?> (<?= $e((string) count($itemsList)) ?>)</h3>
        <div class="table-wrap mt-12">
          <table class="table table--details">
            <thead>
              <tr>
                <th>Lp.</th>
                <th><?= $e($t('orders.details.item_name')) ?></th>
                <th>SKU/EAN</th>
                <th><?= $e($t('orders.details.item_qty')) ?></th>
                <th><?= $e($t('orders.details.item_price')) ?></th>
                <th><?= $e($t('orders.details.item_sum')) ?></th>
              </tr>
            </thead>
            <tbody>
              <?php if ($itemsList === []): ?>
                <tr><td colspan="6" class="muted"><?= $e($t('orders.empty')) ?></td></tr>
              <?php endif; ?>
              <?php foreach ($itemsList as $idx => $item): ?>
                <?php
                $qty = (float) ($item['quantity'] ?? 0);
                $price = $item['original_price_with_tax'] !== null ? (float) $item['original_price_with_tax'] : null;
                $sum = $price === null ? null : ($qty * $price);
                $media = trim((string) ($item['media_url'] ?? ''));
                ?>
                <tr>
                  <td><?= $e((string) ($idx + 1)) ?></td>
                  <td>
                    <div class="order-item-cell">
                      <?php if ($media !== ''): ?>
                        <span class="orders-image-hover-wrap">
                          <img src="<?= $e($media) ?>" alt="" class="order-item-thumb">
                          <img src="<?= $e($media) ?>" alt="" class="orders-image-hover-popup">
                        </span>
                      <?php else: ?>
                        <span class="order-item-thumb order-item-thumb--empty"></span>
                      <?php endif; ?>
                      <div>
                        <div class="order-item-name"><?= $e((string) ($item['original_name'] ?? '')) ?></div>
                        <?php $personalization = trim((string) ($item['personalization'] ?? '')); ?>
                        <?php if ($personalization !== ''): ?>
                          <div class="item-personalization">
                            <span class="item-personalization__label">Personalizacja:</span>
                            <?php foreach (explode("\n", $personalization) as $line): ?>
                              <?php if (trim($line) !== ''): ?>
                                <div class="item-personalization__line"><?= $e(trim($line)) ?></div>
                              <?php endif; ?>
                            <?php endforeach; ?>
                          </div>
                        <?php endif; ?>
                      </div>
                    </div>
                  </td>
                  <td>
                    <div><?= $e((string) ($item['sku'] ?? '-')) ?></div>
                    <div class="muted"><?= $e((string) ($item['ean'] ?? '-')) ?></div>
                  </td>
                  <td><?= $e((string) $qty) ?></td>
                  <td><?= $e($price !== null ? number_format($price, 2, '.', ' ') : '-') ?></td>
                  <td><?= $e($sum !== null ? number_format($sum, 2, '.', ' ') : '-') ?></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </section>

      <section class="mt-16 order-grid-2">
        <article class="card">
          <h3 class="section-title"><?= $e($t('orders.details.order_info')) ?></h3>
          <dl class="order-kv mt-12">
            <dt><?= $e($t('orders.details.fields.status')) ?></dt><dd><?= $e((string) ($statusLabel ?? '-')) ?></dd>
            <dt>Nr zamowienia</dt><dd><strong><?= $e((string) ($orderRow['internal_order_number'] ?? '-')) ?></strong></dd>
            <dt><?= $e($t('orders.details.fields.external_order_id')) ?></dt><dd><?= $e((string) ($orderRow['external_order_id'] ?? '-')) ?></dd>
            <dt><?= $e($t('orders.details.fields.ordered_at')) ?></dt><dd><?= $e((string) ($orderRow['ordered_at'] ?? '-')) ?></dd>
            <dt><?= $e($t('orders.details.fields.customer_login')) ?></dt><dd><?= $e((string) ($orderRow['customer_login'] ?? '-')) ?></dd>
            <dt><?= $e($t('orders.details.fields.currency')) ?></dt><dd><?= $e((string) ($orderRow['currency'] ?? '-')) ?></dd>
          </dl>
        </article>

        <article class="card">
          <h3 class="section-title"><?= $e($t('orders.details.payment_shipping')) ?></h3>
          <dl class="order-kv mt-12">
            <dt><?= $e($t('orders.details.fields.payment_status')) ?></dt><dd><?= $e((string) ($orderRow['payment_status'] ?? '-')) ?></dd>
            <dt>Typ platnosci</dt>
            <dd>
              <?php
              $paymentTypeRaw = strtoupper(trim((string) ($orderRow['external_payment_type_id'] ?? '')));
              $paymentTypeLabels = [
                  'CASH_ON_DELIVERY' => 'Za pobraniem',
                  'ONLINE' => 'Platnosc online',
                  'TRANSFER' => 'Przelew',
              ];
              $paymentTypeLabel = $paymentTypeLabels[$paymentTypeRaw] ?? ($paymentTypeRaw !== '' ? $paymentTypeRaw : '-');
              ?>
              <?php if ($paymentTypeRaw === 'CASH_ON_DELIVERY'): ?>
                <span class="order-tag is-cod"><?= $e($paymentTypeLabel) ?></span>
              <?php else: ?>
                <?= $e($paymentTypeLabel) ?>
              <?php endif; ?>
            </dd>
            <dt><?= $e($t('orders.details.fields.total_with_tax')) ?></dt><dd><?= $e((string) ($orderRow['total_with_tax'] ?? '-')) ?></dd>
            <dt><?= $e($t('orders.details.fields.total_paid')) ?></dt><dd><?= $e((string) ($orderRow['total_paid'] ?? '-')) ?></dd>
            <dt><?= $e($t('orders.details.fields.carrier')) ?></dt><dd><?= $e($carrierDisplay !== '' ? $carrierDisplay : '-') ?></dd>
            <dt><?= $e($t('orders.details.fields.send_date')) ?></dt><dd><?= $e((string) ($orderRow['send_date_max'] ?? '-')) ?></dd>
            <dt><?= $e($t('orders.details.fields.shipments_count')) ?></dt><dd><?= $e((string) count($shipmentsList)) ?></dd>
            <?php
            $latestDeliveryPkg = null;
            foreach ($packagesList as $dpkg) {
                $ds = (string) ($dpkg['delivery_status'] ?? 'unknown');
                if ($ds !== 'unknown') {
                    if ($latestDeliveryPkg === null || ($dpkg['delivery_status_updated_at'] ?? '') > ($latestDeliveryPkg['delivery_status_updated_at'] ?? '')) {
                        $latestDeliveryPkg = $dpkg;
                    }
                }
            }
            if ($latestDeliveryPkg !== null):
                $ldStatus = (string) ($latestDeliveryPkg['delivery_status'] ?? 'unknown');
                $ldLabel = \App\Modules\Shipments\DeliveryStatus::label($ldStatus);
                $ldDate = trim((string) ($latestDeliveryPkg['delivery_status_updated_at'] ?? ''));
            ?>
            <dt>Status dostawy</dt>
            <dd>
              <span class="delivery-badge delivery-badge--<?= $e($ldStatus) ?>"><?= $e($ldLabel) ?></span>
              <?php if ($ldDate !== ''): ?><small class="muted" style="margin-left:4px"><?= $e($ldDate) ?></small><?php endif; ?>
            </dd>
            <?php endif; ?>
          </dl>
        </article>
      </section>

      <section class="mt-16 order-grid-3">
        <?php foreach (['customer' => $t('orders.details.address_customer'), 'invoice' => $t('orders.details.address_invoice'), 'delivery' => $t('orders.details.address_delivery')] as $addrType => $addrTitle): ?>
          <?php $addr = is_array($addressByType[$addrType] ?? null) ? $addressByType[$addrType] : []; ?>
          <article class="card">
            <h3 class="section-title"><?= $e((string) $addrTitle) ?></h3>
            <div class="order-address mt-12">
              <?php if ($addr === []): ?>
                <?php if ($addrType === 'delivery' && $carrierDisplay !== ''): ?>
                  <div><?= $e($carrierDisplay) ?></div>
                <?php else: ?>
                  <div class="muted">-</div>
                <?php endif; ?>
              <?php else: ?>
                <div><?= $e((string) ($addr['name'] ?? '')) ?></div>
                <?php
                $invoiceCompanyName = $addrType === 'invoice' ? trim((string) ($addr['company_name'] ?? '')) : '';
                $invoiceName = $addrType === 'invoice' ? trim((string) ($addr['name'] ?? '')) : '';
                ?>
                <?php if ($addrType === 'invoice' && $invoiceCompanyName !== '' && $invoiceCompanyName !== $invoiceName): ?>
                  <div><?= $e((string) $addr['company_name']) ?></div>
                <?php endif; ?>
                <?php if ($addrType === 'invoice' && !empty($addr['company_tax_number'])): ?>
                  <div>NIP: <?= $e((string) $addr['company_tax_number']) ?></div>
                <?php endif; ?>
                <div><?= $e((string) (($addr['street_name'] ?? '') . ' ' . ($addr['street_number'] ?? ''))) ?></div>
                <div><?= $e((string) (($addr['zip_code'] ?? '') . ' ' . ($addr['city'] ?? ''))) ?></div>
                <div><?= $e((string) ($addr['country'] ?? '')) ?></div>
                <?php if ($addrType === 'delivery' && !empty($addr['parcel_name'])): ?>
                  <div><?= $e((string) $addr['parcel_name']) ?></div>
                <?php endif; ?>
                <?php if ($addrType === 'delivery' && !empty($addr['parcel_external_id'])): ?>
                  <div><?= $e((string) $addr['parcel_external_id']) ?></div>
                <?php endif; ?>
                <div><?= $e((string) ($addr['phone'] ?? '')) ?></div>
                <div><?= $e((string) ($addr['email'] ?? '')) ?></div>
              <?php endif; ?>
            </div>
          </article>
        <?php endforeach; ?>
      </section>

      <section class="mt-16 order-grid-2">
        <article class="card">
          <h3 class="section-title"><?= $e($t('orders.details.notes_title')) ?></h3>
          <div class="order-events mt-12">
            <?php if ($notesList === []): ?>
              <div class="muted">-</div>
            <?php endif; ?>
            <?php foreach ($notesList as $note): ?>
              <div class="order-event">
                <div class="order-event__head"><?= $e((string) ($note['note_type'] ?? '')) ?> | <?= $e((string) ($note['created_at_external'] ?? '')) ?></div>
                <div class="order-event__body"><?= $e((string) ($note['comment'] ?? '')) ?></div>
              </div>
            <?php endforeach; ?>
          </div>
        </article>

        <article class="card">
          <h3 class="section-title"><?= $e($t('orders.details.history_title')) ?></h3>
          <div class="order-events mt-12">
            <?php if ($historyList === []): ?>
              <div class="muted">-</div>
            <?php endif; ?>
            <?php foreach ($historyList as $event): ?>
              <div class="order-event">
                <div class="order-event__head">
                  <?= $e((string) ($event['changed_at'] ?? '')) ?>
                  <?php $changeSource = (string) ($event['change_source'] ?? ''); ?>
                  <?php if ($changeSource !== ''): ?>
                    <span class="muted">(<?= $e($changeSource) ?>)</span>
                  <?php endif; ?>
                </div>
                <div class="order-event__body"><?= $e((string) ($event['from_label'] ?? '-')) ?> &rarr; <?= $e((string) ($event['to_label'] ?? '-')) ?></div>
              </div>
            <?php endforeach; ?>
          </div>
        </article>
      </section>
    </div>

    <div class="order-tab-panel" data-order-tab-panel="history">
      <section class="card mt-16">
        <h3 class="section-title"><?= $e($t('orders.details.tabs.history')) ?></h3>
        <div class="table-wrap mt-12">
          <table class="table table--details">
            <thead>
              <tr>
                <th><?= $e($t('orders.details.activity.date')) ?></th>
                <th><?= $e($t('orders.details.activity.type')) ?></th>
                <th><?= $e($t('orders.details.activity.summary')) ?></th>
                <th><?= $e($t('orders.details.activity.actor')) ?></th>
              </tr>
            </thead>
            <tbody>
              <?php if ($activityLogList === []): ?>
                <tr><td colspan="4" class="muted"><?= $e($t('orders.details.activity.empty')) ?></td></tr>
              <?php endif; ?>
              <?php foreach ($activityLogList as $activity): ?>
                <?php
                $eventType = (string) ($activity['event_type'] ?? '');
                $eventTypeKey = 'orders.details.activity.types.' . $eventType;
                $eventTypeLabel = $t($eventTypeKey);
                if ($eventTypeLabel === $eventTypeKey) {
                    $eventTypeLabel = $eventType;
                }
                $activitySummary = (string) ($activity['summary'] ?? '');
                if ($eventType === 'import') {
                    $importDetailsRaw = (string) ($activity['details_json'] ?? '');
                    $importDetails = json_decode($importDetailsRaw, true);
                    if (is_array($importDetails)) {
                        $meta = [];
                        $triggerLabel = trim((string) ($importDetails['trigger_label'] ?? ''));
                        $sourceUpdatedAt = trim((string) ($importDetails['source_updated_at'] ?? ''));
                        if ($triggerLabel !== '') {
                            $meta[] = $triggerLabel;
                        }
                        if ($sourceUpdatedAt !== '') {
                            $meta[] = 'source_updated_at: ' . $sourceUpdatedAt;
                        }
                        if ($meta !== []) {
                            $activitySummary .= ' [' . implode('; ', $meta) . ']';
                        }
                    }
                }
                $actorType = (string) ($activity['actor_type'] ?? 'system');
                $actorName = trim((string) ($activity['actor_name'] ?? ''));
                if ($actorName !== '') {
                    $actorLabel = $actorName;
                } else {
                    $actorKey = 'orders.details.activity.actors.' . $actorType;
                    $actorLabel = $t($actorKey);
                    if ($actorLabel === $actorKey) {
                        $actorLabel = $actorType;
                    }
                }
                ?>
                <tr>
                  <td class="text-nowrap"><?= $e((string) ($activity['created_at'] ?? '')) ?></td>
                  <td><span class="activity-type-badge activity-type-badge--<?= $e($eventType) ?>"><?= $e($eventTypeLabel) ?></span></td>
                  <td><?= $e($activitySummary) ?></td>
                  <td class="muted"><?= $e($actorLabel) ?></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </section>

    </div>

    <div class="order-tab-panel" data-order-tab-panel="shipments">
      <?php if ($packagesList !== []): ?>
      <section class="card mt-16">
        <h3 class="section-title">Wygenerowane przesylki</h3>
        <div class="table-wrap mt-12">
          <table class="table table--details">
            <thead>
              <tr>
                <th>ID</th>
                <th>Status</th>
                <th>Status dostawy</th>
                <th>Nr sledzenia</th>
                <th>Przewoznik</th>
                <th>Etykieta</th>
                <th>Utworzono</th>
              </tr>
            </thead>
            <tbody>
              <?php $storageBase = dirname(__DIR__, 3) . '/storage/'; ?>
              <?php $pendingPrintIds = is_array($pendingPrintPackageIds ?? null) ? $pendingPrintPackageIds : []; ?>
              <?php foreach ($packagesList as $pkg): ?>
                <?php
                $pkgStatus = (string) ($pkg['status'] ?? 'draft');
                $pkgTracking = trim((string) ($pkg['tracking_number'] ?? ''));
                $pkgCarrierId = trim((string) ($pkg['carrier_id'] ?? ''));
                $pkgProvider = trim((string) ($pkg['provider'] ?? ''));
                $isManual = $pkgProvider === 'manual';
                $providerLabels = ['apaczka' => 'Apaczka', 'allegro_wza' => 'Allegro', 'inpost' => 'InPost', 'manual' => 'Reczna'];
                $pkgProviderLabel = $providerLabels[$pkgProvider] ?? $pkgProvider;
                $pkgCarrier = $pkgCarrierId !== '' ? ($pkgProviderLabel . ' &rarr; ' . $pkgCarrierId) : $pkgProviderLabel;
                $pkgLabelPath = trim((string) ($pkg['label_path'] ?? ''));
                if ($pkgLabelPath !== '' && !file_exists($storageBase . $pkgLabelPath)) {
                    $pkgLabelPath = '';
                }
                $pkgError = trim((string) ($pkg['error_message'] ?? ''));
                ?>
                <tr>
                  <td><?= $e((string) ($pkg['id'] ?? '')) ?></td>
                  <td>
                    <?php if ($isManual): ?>
                    <span class="order-tag is-neutral">Dodana recznie</span>
                    <?php else: ?>
                    <span class="order-tag <?= $pkgStatus === 'label_ready' || $pkgStatus === 'created' ? 'is-success' : ($pkgStatus === 'error' ? 'is-danger' : 'is-warn') ?>"
                      data-pkg-status-tag="<?= $e((string) ($pkg['id'] ?? 0)) ?>">
                      <?= $e($pkgStatus) ?>
                    </span>
                    <?php if ($pkgStatus === 'pending'): ?>
                      <button type="button" class="btn btn--xs btn--secondary mt-4"
                        data-check-pkg-status="<?= $e((string) ($pkg['id'] ?? 0)) ?>"
                        data-order-id="<?= $e((string) ($orderId ?? 0)) ?>"
                        data-auto-poll="1"
                        style="font-size:0.7rem">Sprawdz status</button>
                    <?php endif; ?>
                    <?php endif; ?>
                    <?php if ($pkgError !== ''): ?>
                      <div class="muted mt-4" style="font-size:0.75rem" data-pkg-error="<?= $e((string) ($pkg['id'] ?? 0)) ?>"><?= $e($pkgError) ?></div>
                    <?php endif; ?>
                  </td>
                  <td>
                    <?php
                    $pkgDeliveryStatus = (string) ($pkg['delivery_status'] ?? 'unknown');
                    $pkgDeliveryRaw = trim((string) ($pkg['delivery_status_raw'] ?? ''));
                    $pkgDeliveryLabel = \App\Modules\Shipments\DeliveryStatus::label($pkgDeliveryStatus);
                    $pkgDeliveryDesc = $pkgDeliveryRaw !== '' ? \App\Modules\Shipments\DeliveryStatus::description($pkgProvider, $pkgDeliveryRaw) : '';
                    $pkgDeliveryTitle = $pkgDeliveryRaw !== '' ? ($pkgDeliveryRaw . ' — ' . $pkgDeliveryDesc) : '';
                    ?>
                    <span class="delivery-badge delivery-badge--<?= $e($pkgDeliveryStatus) ?>" title="<?= $e($pkgDeliveryTitle) ?>"><?= $e($pkgDeliveryLabel) ?></span>
                  </td>
                  <td style="white-space:nowrap" data-pkg-tracking-cell="<?= $e((string) ($pkg['id'] ?? 0)) ?>">
                    <?= $e($pkgTracking !== '' ? $pkgTracking : '-') ?><?php
                    $pkgTrackUrl = \App\Modules\Shipments\DeliveryStatus::trackingUrl($pkgProvider, $pkgTracking, $pkgCarrierId);
                    if ($pkgTrackUrl !== null): ?> <a href="<?= $e($pkgTrackUrl) ?>" target="_blank" class="tracking-link" title="Sledz przesylke">&#128279;</a><?php endif; ?>
                  </td>
                  <td><?php if ($isManual): ?><?= $e($pkgCarrierId !== '' ? $pkgCarrierId : 'Reczna') ?><?php elseif ($pkgCarrierId !== ''): ?><?= $e($pkgProviderLabel) ?> &rarr; <?= $e($pkgCarrierId) ?><?php elseif ($pkgProviderLabel !== ''): ?><?= $e($pkgProviderLabel) ?><?php else: ?>-<?php endif; ?></td>
                  <td data-pkg-label-cell="<?= $e((string) ($pkg['id'] ?? 0)) ?>">
                    <?php if ($isManual): ?>
                      &mdash;
                    <?php else: ?>
                    <span style="display:inline-flex;gap:4px;align-items:center">
                    <?php if ($pkgLabelPath !== '' && $pkgStatus !== 'error'): ?>
                      <form method="post" action="/orders/<?= $e((string) ($orderId ?? 0)) ?>/shipment/<?= $e((string) ($pkg['id'] ?? 0)) ?>/label" style="display:inline">
                        <input type="hidden" name="_token" value="<?= $e($csrfToken ?? '') ?>">
                        <button type="submit" class="btn btn--sm btn--secondary">Pobierz</button>
                      </form>
                    <?php elseif ($pkgStatus !== 'error'): ?>
                      -
                    <?php endif; ?>
                    <?php if (in_array($pkgStatus, ['label_ready', 'created'], true)): ?>
                      <?php if (in_array((int) ($pkg['id'] ?? 0), $pendingPrintIds, true)): ?>
                        <button type="button" class="btn btn--sm btn--danger" disabled style="white-space:nowrap">W kolejce</button>
                      <?php else: ?>
                        <button type="button"
                          class="btn btn--sm btn--secondary btn-print-label"
                          data-package-id="<?= $e((string) ($pkg['id'] ?? 0)) ?>"
                          data-order-id="<?= $e((string) ($orderId ?? 0)) ?>"
                          title="Wyslij do drukarki">Drukuj</button>
                      <?php endif; ?>
                    <?php endif; ?>
                    </span>
                    <?php endif; ?>
                  </td>
                  <td class="text-nowrap"><?= $e((string) ($pkg['created_at'] ?? '')) ?></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </section>
      <?php endif; ?>

      <?php if ($shipmentsList !== []): ?>
      <section class="card mt-16">
        <h3 class="section-title">Wysylki z Allegro</h3>
        <div class="table-wrap mt-12">
          <table class="table table--details">
            <thead>
              <tr>
                <th>Nr sledzenia</th>
                <th>Przewoznik</th>
                <th>Data nadania</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($shipmentsList as $sh): ?>
                <tr>
                  <td><?= $e(trim((string) ($sh['tracking_number'] ?? '-'))) ?></td>
                  <td><?= $e(trim((string) ($sh['carrier_provider_id'] ?? '-'))) ?></td>
                  <td class="text-nowrap"><?= $e(trim((string) ($sh['posted_at'] ?? '-'))) ?></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </section>
      <?php endif; ?>

      <?php if ($packagesList === [] && $shipmentsList === []): ?>
      <section class="card mt-16">
        <h3 class="section-title"><?= $e($t('orders.details.tabs.shipments')) ?></h3>
        <p class="muted mt-12">Brak przesylek dla tego zamowienia.</p>
      </section>
      <?php endif; ?>

      <section class="card mt-16">
        <h3 class="section-title">Dodaj reczny numer przesylki</h3>
        <form method="POST" action="/orders/<?= $e((string) ($orderId ?? 0)) ?>/shipment/manual" class="manual-tracking-form mt-12">
          <input type="hidden" name="_token" value="<?= $e($csrfToken ?? '') ?>">
          <input type="text" name="tracking_number" placeholder="Nr przesylki" required class="form-control">
          <input type="text" name="carrier_name" placeholder="Przewoznik (opcjonalnie)" class="form-control">
          <button type="submit" class="btn btn--primary">Dodaj</button>
        </form>
      </section>
    </div>

    <div class="order-tab-panel" data-order-tab-panel="payments">
      <section class="card mt-16">
        <h3 class="section-title"><?= $e($t('orders.details.tabs.payments')) ?></h3>

        <?php
        $paymentStatusNum = isset($orderRow['payment_status']) ? (int) $orderRow['payment_status'] : null;
        $paymentStatusLabels = [0 => 'Nieopłacone', 1 => 'Częściowo opłacone', 2 => 'Opłacone', 3 => 'Zwrócone'];
        $paymentStatusClasses = [0 => 'is-danger', 1 => 'is-warn', 2 => 'is-success', 3 => 'is-neutral'];
        $paymentTypeLabels = [
            'ONLINE'           => 'Płatność online',
            'CASH_ON_DELIVERY' => 'Za pobraniem',
            'TRANSFER'         => 'Przelew bankowy',
        ];
        $providerLabels = [
            'AF'      => 'Allegro Pay',
            'PAYU'    => 'PayU',
            'PRZELEWY24' => 'Przelewy24',
        ];
        ?>

        <div class="payment-summary mt-12">
          <div class="payment-summary__row">
            <span class="payment-summary__label">Status płatności</span>
            <span class="payment-summary__value">
              <?php if ($paymentStatusNum !== null && isset($paymentStatusLabels[$paymentStatusNum])): ?>
                <span class="order-tag <?= $e($paymentStatusClasses[$paymentStatusNum] ?? 'is-neutral') ?>">
                  <?= $e($paymentStatusLabels[$paymentStatusNum]) ?>
                </span>
              <?php else: ?>
                <span class="muted">—</span>
              <?php endif; ?>
            </span>
          </div>
          <div class="payment-summary__row">
            <span class="payment-summary__label">Kwota do zapłaty</span>
            <span class="payment-summary__value">
              <?= $e($orderRow['total_with_tax'] !== null ? number_format((float) $orderRow['total_with_tax'], 2, '.', ' ') . ' ' . ($orderRow['currency'] ?? '') : '—') ?>
            </span>
          </div>
          <div class="payment-summary__row">
            <span class="payment-summary__label">Kwota opłacona</span>
            <span class="payment-summary__value">
              <?= $e($orderRow['total_paid'] !== null ? number_format((float) $orderRow['total_paid'], 2, '.', ' ') . ' ' . ($orderRow['currency'] ?? '') : '—') ?>
            </span>
          </div>
        </div>

        <div class="mt-12">
          <button type="button" class="btn btn--sm btn--primary" id="btn-add-payment">+ Dodaj płatność</button>
        </div>

        <div class="payment-add-form mt-12" id="payment-add-form" style="display:none">
          <div class="payment-add-form__row">
            <div class="payment-add-form__field">
              <label for="payment-amount">Kwota</label>
              <input type="number" id="payment-amount" step="0.01" min="0.01" required
                value="<?= $e(number_format(max(0, (float) ($orderRow['total_with_tax'] ?? 0) - (float) ($orderRow['total_paid'] ?? 0)), 2, '.', '')) ?>">
            </div>
            <div class="payment-add-form__field">
              <label for="payment-type">Typ płatności</label>
              <select id="payment-type" required>
                <option value="ONLINE">Płatność online</option>
                <option value="TRANSFER">Przelew bankowy</option>
                <option value="CASH_ON_DELIVERY">Za pobraniem</option>
              </select>
            </div>
            <div class="payment-add-form__field">
              <label for="payment-date">Data</label>
              <input type="date" id="payment-date" value="<?= $e(date('Y-m-d')) ?>">
            </div>
            <div class="payment-add-form__field">
              <label for="payment-comment">Komentarz</label>
              <input type="text" id="payment-comment" placeholder="opcjonalny">
            </div>
          </div>
          <div class="payment-add-form__actions mt-8">
            <button type="button" class="btn btn--sm btn--primary" id="btn-save-payment">Zapisz</button>
            <button type="button" class="btn btn--sm btn--outline" id="btn-cancel-payment">Anuluj</button>
          </div>
        </div>

        <?php if ($paymentsList === []): ?>
          <p class="muted mt-16" id="payments-empty-msg">Brak zarejestrowanych płatności.</p>
        <?php else: ?>
          <div class="table-wrap mt-16">
            <table class="table table--details">
              <thead>
                <tr>
                  <th>Data płatności</th>
                  <th>Typ</th>
                  <th>Dostawca</th>
                  <th>Kwota</th>
                  <th>ID płatności</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($paymentsList as $payment): ?>
                  <?php
                  $ptRaw = strtoupper(trim((string) ($payment['payment_type_id'] ?? '')));
                  $ptLabel = $paymentTypeLabels[$ptRaw] ?? ($ptRaw !== '' ? $ptRaw : '—');
                  $providerRaw = strtoupper(trim((string) ($payment['comment'] ?? '')));
                  $providerLabel = $providerLabels[$providerRaw] ?? ($providerRaw !== '' ? $providerRaw : '—');
                  $amount = $payment['amount'] !== null
                      ? number_format((float) $payment['amount'], 2, '.', ' ') . ' ' . ($payment['currency'] ?? '')
                      : '—';
                  $payDate = (string) ($payment['payment_date'] ?? '');
                  ?>
                  <tr>
                    <td class="text-nowrap"><?= $e($payDate !== '' ? $payDate : '—') ?></td>
                    <td>
                      <?php if ($ptRaw === 'CASH_ON_DELIVERY'): ?>
                        <span class="order-tag is-cod"><?= $e($ptLabel) ?></span>
                      <?php else: ?>
                        <?= $e($ptLabel) ?>
                      <?php endif; ?>
                    </td>
                    <td><?= $e($providerLabel) ?></td>
                    <td class="text-nowrap"><strong><?= $e($amount) ?></strong></td>
                    <td class="muted" style="font-size:11px"><?= $e((string) ($payment['source_payment_id'] ?? '—')) ?></td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        <?php endif; ?>
      </section>
    </div>

    <div class="order-tab-panel" data-order-tab-panel="documents">
      <section class="card mt-16">
        <h3 class="section-title"><?= $e($t('orders.details.tabs.documents')) ?></h3>
        <?php if ($receiptsList === [] && $documentsList === []): ?>
          <p class="muted mt-12"><?= $e($t('receipts.documents.empty')) ?></p>
        <?php endif; ?>
        <?php if ($receiptsList !== []): ?>
          <h4 class="section-title mt-12">Paragony</h4>
          <div class="table-wrap mt-8">
            <table class="table table--details">
              <thead>
                <tr>
                  <th><?= $e($t('receipts.documents.number')) ?></th>
                  <th><?= $e($t('receipts.documents.issue_date')) ?></th>
                  <th><?= $e($t('receipts.documents.total_gross')) ?></th>
                  <th><?= $e($t('receipts.documents.config')) ?></th>
                  <th><?= $e($t('receipts.documents.actions')) ?></th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($receiptsList as $receipt): ?>
                  <tr>
                    <td><strong><?= $e((string) ($receipt['receipt_number'] ?? '')) ?></strong></td>
                    <?php $issueDateOrder = (string) ($receipt['issue_date'] ?? ''); ?>
                    <td class="text-nowrap"><?= $e(strlen($issueDateOrder) >= 16 ? substr($issueDateOrder, 0, 16) : $issueDateOrder) ?></td>
                    <td class="text-nowrap"><?= $e($receipt['total_gross'] !== null ? number_format((float) $receipt['total_gross'], 2, '.', ' ') : '-') ?></td>
                    <td><?= $e((string) ($receipt['config_name'] ?? '-')) ?></td>
                    <td>
                      <a href="/orders/<?= $e((string) ($orderId ?? 0)) ?>/receipt/<?= $e((string) ($receipt['id'] ?? '')) ?>" class="btn btn--sm btn--secondary"><?= $e($t('receipts.documents.preview')) ?></a>
                      <a href="/orders/<?= $e((string) ($orderId ?? 0)) ?>/receipt/<?= $e((string) ($receipt['id'] ?? '')) ?>/pdf" class="btn btn--sm btn--secondary">PDF</a>
                    </td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        <?php endif; ?>
        <?php if ($documentsList !== []): ?>
          <h4 class="section-title mt-12">Dokumenty zewnetrzne</h4>
          <div class="table-wrap mt-8">
            <table class="table table--details">
              <thead>
                <tr>
                  <th>Numer</th>
                  <th>Typ</th>
                  <th>Kwota brutto</th>
                  <th>Data</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($documentsList as $doc): ?>
                  <tr>
                    <td><strong><?= $e((string) ($doc['document_number'] ?? '-')) ?></strong></td>
                    <td><?= $e((string) ($doc['document_type_id'] ?? '-')) ?></td>
                    <td class="text-nowrap"><?= $e($doc['price_with_tax'] !== null ? number_format((float) $doc['price_with_tax'], 2, '.', ' ') . ' ' . ($doc['currency'] ?? '') : '-') ?></td>
                    <td class="text-nowrap"><?= $e((string) ($doc['source_created_at'] ?? '-')) ?></td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        <?php endif; ?>
      </section>
    </div>
  </div>
</section>

<script>
(function () {
  var tabButtons = document.querySelectorAll('[data-order-tab-target]');
  var tabPanels = document.querySelectorAll('[data-order-tab-panel]');
  if (!tabButtons.length || !tabPanels.length) return;

  function setActiveTab(target) {
    var key = target || 'details';
    tabButtons.forEach(function (btn) {
      btn.classList.toggle('is-active', btn.getAttribute('data-order-tab-target') === key);
    });
    tabPanels.forEach(function (panel) {
      panel.classList.toggle('is-active', panel.getAttribute('data-order-tab-panel') === key);
    });
  }

  var storageKey = 'orderDetailTab';

  tabButtons.forEach(function (button) {
    button.addEventListener('click', function () {
      var target = button.getAttribute('data-order-tab-target') || 'details';
      setActiveTab(target);
      try { localStorage.setItem(storageKey, target); } catch (e) {}
    });
  });

  var forceTab = <?= json_encode($flashSuccessMsg !== '' && strpos($flashSuccessMsg, 'Przesylka') !== false ? 'shipments' : '') ?>;
  var savedTab = null;
  try { savedTab = localStorage.getItem(storageKey); } catch (e) {}
  setActiveTab(forceTab || savedTab || 'details');

  // Header "Platnosc" button — switch to payments tab and open form
  var btnHeaderPayment = document.getElementById('btn-header-payment');
  if (btnHeaderPayment) {
    btnHeaderPayment.addEventListener('click', function () {
      setActiveTab('payments');
      try { localStorage.setItem(storageKey, 'payments'); } catch (e) {}
      var form = document.getElementById('payment-add-form');
      if (form) form.style.display = '';
    });
  }

  // Print label button handler (delegated for dynamically added buttons)
  document.addEventListener('click', function (e) {
    var btn = e.target.closest('.btn-print-label');
    if (!btn) return;
    var packageId = btn.getAttribute('data-package-id');
    if (!packageId) return;
    btn.disabled = true;
    var originalText = btn.innerHTML;
    btn.innerHTML = 'Wysylam...';
    var csrfInput = document.querySelector('input[name="_token"]');
    var csrf = csrfInput ? csrfInput.value : '<?= $e($csrfToken ?? '') ?>';

    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 || res.status === 409) {
        btn.innerHTML = 'W kolejce';
        btn.disabled = true;
        btn.classList.remove('btn--secondary');
        btn.classList.add('btn--danger');
      } else {
        var msg = (res.data && res.data.error) ? res.data.error : 'Nieznany blad';
        if (window.OrderProAlerts) { window.OrderProAlerts.show({ message: msg, type: 'error' }); }
        btn.innerHTML = originalText;
        btn.disabled = false;
      }
    })
    .catch(function () {
      if (window.OrderProAlerts) { window.OrderProAlerts.show({ message: 'Blad sieci.', type: 'error' }); }
      btn.innerHTML = originalText;
      btn.disabled = false;
    });
  });

})();
</script>

<script>
(function () {
  var POPUP_GAP = 12;
  document.addEventListener('mouseenter', function (e) {
    if (!e.target || !e.target.closest) return;
    var wrap = e.target.closest('.orders-image-hover-wrap');
    if (!wrap) return;
    var popup = wrap.querySelector('.orders-image-hover-popup');
    if (!popup) return;
    var rect = wrap.getBoundingClientRect();
    var pw = 350;
    var ph = 350;
    var left = rect.right + POPUP_GAP;
    if (left + pw > window.innerWidth) {
      left = rect.left - pw - POPUP_GAP;
    }
    var top = rect.top + rect.height / 2 - ph / 2;
    if (top < 4) top = 4;
    if (top + ph > window.innerHeight - 4) top = window.innerHeight - 4 - ph;
    popup.style.left = left + 'px';
    popup.style.top = top + 'px';
  }, true);
})();
</script>

<script>
(function () {
  'use strict';

  var csrfToken = (document.querySelector('input[name="_token"]') || {}).value || '';

  function updateRowSuccess(pkgId, orderId, data) {
    var tag = document.querySelector('[data-pkg-status-tag="' + pkgId + '"]');
    if (tag) {
      tag.className = 'order-tag is-success';
      tag.textContent = data.status;
    }

    var btn = document.querySelector('[data-check-pkg-status="' + pkgId + '"]');
    if (btn) btn.remove();

    var trackingCell = document.querySelector('[data-pkg-tracking-cell="' + pkgId + '"]');
    if (trackingCell && data.tracking_number) {
      trackingCell.textContent = data.tracking_number;
    }

    var labelCell = document.querySelector('[data-pkg-label-cell="' + pkgId + '"]');
    if (labelCell) {
      var html = '<span style="display:inline-flex;gap:4px;align-items:center">';
      if (data.status === 'label_ready') {
        html += '<form method="post" action="/orders/' + orderId + '/shipment/' + pkgId + '/label" style="display:inline">'
          + '<input type="hidden" name="_token" value="' + csrfToken + '">'
          + '<button type="submit" class="btn btn--sm btn--secondary">Pobierz</button></form>';
      }
      html += '<button type="button" class="btn btn--sm btn--secondary btn-print-label"'
        + ' data-package-id="' + pkgId + '" data-order-id="' + orderId + '" title="Wyslij do drukarki">Drukuj</button>';
      html += '</span>';
      labelCell.innerHTML = html;
    }
  }

  function updateRowError(pkgId, errorMsg) {
    var tag = document.querySelector('[data-pkg-status-tag="' + pkgId + '"]');
    if (tag) {
      tag.className = 'order-tag is-danger';
      tag.textContent = 'error';
    }

    var btn = document.querySelector('[data-check-pkg-status="' + pkgId + '"]');
    if (btn) btn.remove();

    var errEl = document.querySelector('[data-pkg-error="' + pkgId + '"]');
    if (!errEl && tag) {
      errEl = document.createElement('div');
      errEl.className = 'muted mt-4';
      errEl.style.fontSize = '0.75rem';
      errEl.setAttribute('data-pkg-error', pkgId);
      tag.parentNode.appendChild(errEl);
    }
    if (errEl) errEl.textContent = errorMsg || 'Blad tworzenia przesylki';
  }

  function pollPackageStatus(pkgId, orderId, btn, attempt) {
    if (btn) {
      btn.disabled = true;
      btn.textContent = 'Sprawdzam... (' + (attempt + 1) + ')';
    }
    fetch('/orders/' + orderId + '/shipment/' + pkgId + '/status')
      .then(function (r) { return r.json(); })
      .then(function (data) {
        if (data.status === 'label_ready' || data.status === 'created') {
          updateRowSuccess(pkgId, orderId, data);
        } else if (data.status === 'in_progress' || data.status === 'pending') {
          if (attempt < 12) {
            var delay = Math.min(2000 * Math.pow(1.5, attempt), 15000);
            setTimeout(function () {
              pollPackageStatus(pkgId, orderId, btn, attempt + 1);
            }, delay);
          } else if (btn) {
            btn.textContent = 'Sprawdz ponownie';
            btn.disabled = false;
          }
        } else if (data.status === 'error') {
          updateRowError(pkgId, data.error);
        }
      })
      .catch(function () {
        if (btn) {
          btn.textContent = 'Blad sieci';
          btn.disabled = false;
        }
      });
  }

  document.querySelectorAll('[data-check-pkg-status]').forEach(function (btn) {
    btn.addEventListener('click', function () {
      pollPackageStatus(
        btn.getAttribute('data-check-pkg-status'),
        btn.getAttribute('data-order-id'),
        btn,
        0
      );
    });
  });

  document.querySelectorAll('[data-check-pkg-status][data-auto-poll="1"]').forEach(function (btn, idx) {
    setTimeout(function () {
      pollPackageStatus(
        btn.getAttribute('data-check-pkg-status'),
        btn.getAttribute('data-order-id'),
        btn,
        0
      );
    }, 500 + idx * 400);
  });
})();
</script>

<script>
(function () {
  var btnAdd = document.getElementById('btn-add-payment');
  var btnSave = document.getElementById('btn-save-payment');
  var btnCancel = document.getElementById('btn-cancel-payment');
  var form = document.getElementById('payment-add-form');
  if (!btnAdd || !form) return;

  btnAdd.addEventListener('click', function () {
    form.style.display = '';
    btnAdd.style.display = 'none';
  });

  btnCancel.addEventListener('click', function () {
    form.style.display = 'none';
    btnAdd.style.display = '';
  });

  btnSave.addEventListener('click', function () {
    var amount = parseFloat(document.getElementById('payment-amount').value);
    var paymentType = document.getElementById('payment-type').value;
    var paymentDate = document.getElementById('payment-date').value;
    var comment = document.getElementById('payment-comment').value;

    if (!amount || amount <= 0) {
      window.OrderProAlerts.error('Kwota musi być większa od 0.');
      return;
    }
    if (!paymentType) {
      window.OrderProAlerts.error('Wybierz typ płatności.');
      return;
    }

    btnSave.disabled = true;
    btnSave.textContent = 'Zapisywanie...';

    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/orders/<?= (int) $orderId ?>/payment/add', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    xhr.onload = function () {
      var resp;
      try { resp = JSON.parse(xhr.responseText); } catch (e) { resp = {}; }
      if (xhr.status >= 200 && xhr.status < 300 && resp.ok) {
        window.location.reload();
      } else {
        window.OrderProAlerts.error(resp.error || 'Błąd zapisu płatności.');
        btnSave.disabled = false;
        btnSave.textContent = 'Zapisz';
      }
    };
    xhr.onerror = function () {
      window.OrderProAlerts.error('Błąd połączenia z serwerem.');
      btnSave.disabled = false;
      btnSave.textContent = 'Zapisz';
    };
    xhr.send(
      '_token=<?= $e($csrfToken) ?>' +
      '&amount=' + encodeURIComponent(amount) +
      '&payment_type_id=' + encodeURIComponent(paymentType) +
      '&payment_date=' + encodeURIComponent(paymentDate) +
      '&comment=' + encodeURIComponent(comment)
    );
  });
})();
</script>

<?php require __DIR__ . '/partials/email-send-modal.php'; ?>
