<?php
$orderRow = is_array($order ?? null) ? $order : [];
$itemsList = is_array($items ?? null) ? $items : [];
$notesList = is_array($notes ?? null) ? $notes : [];
$addrMap = is_array($addressByType ?? null) ? $addressByType : [];
$customer = is_array($addrMap['customer'] ?? null) ? $addrMap['customer'] : [];
$delivery = is_array($addrMap['delivery'] ?? null) ? $addrMap['delivery'] : [];

$orderNumber = trim((string) ($orderRow['internal_order_number'] ?? ''));
if ($orderNumber === '') {
    $orderNumber = '#' . (string) ($orderRow['id'] ?? 0);
}
$externalId = trim((string) ($orderRow['external_order_id'] ?? ''));
$buyerName = trim((string) ($customer['name'] ?? ''));
$buyerEmail = trim((string) ($customer['email'] ?? ''));
$buyerPhone = trim((string) ($customer['phone'] ?? ''));

$deliveryName = trim((string) ($delivery['name'] ?? ''));
$deliveryStreet = trim((string) (($delivery['street_name'] ?? '') . ' ' . ($delivery['street_number'] ?? '')));
$deliveryCity = trim((string) (($delivery['zip_code'] ?? '') . ' ' . ($delivery['city'] ?? '')));
$deliveryCountry = trim((string) ($delivery['country'] ?? ''));
$deliveryParcel = trim((string) ($delivery['parcel_name'] ?? ''));
$deliveryParcelId = trim((string) ($delivery['parcel_external_id'] ?? ''));

$fullDeliveryAddress = implode(', ', array_filter([
    $deliveryName,
    $deliveryStreet,
    $deliveryCity,
    $deliveryCountry,
    $deliveryParcel !== '' ? $deliveryParcel : null,
    $deliveryParcelId !== '' ? $deliveryParcelId : null,
]));

$totalWithTax = $orderRow['total_with_tax'] !== null ? number_format((float) $orderRow['total_with_tax'], 2, '.', ' ') : '-';
$totalPaid = $orderRow['total_paid'] !== null ? number_format((float) $orderRow['total_paid'], 2, '.', ' ') : '-';
$currency = trim((string) ($orderRow['currency'] ?? ''));

$copyIcon = '<svg class="copy-icon" xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>';
$checkIcon = '<svg class="check-icon" style="display:none" xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>';
$copyBtn = static function (string $value) use ($e, $copyIcon, $checkIcon): string {
    if ($value === '') return '';
    return ' <button type="button" class="copy-field__btn" data-copy-value="' . $e($value) . '" title="Kopiuj">' . $copyIcon . $checkIcon . '</button>';
};
?>

<div class="order-preview-section">
  <div class="order-preview-section__title"><?= $e($t('orders.preview.order_number')) ?></div>
  <div class="order-preview-kv">
    <dt>Nr:</dt>
    <dd><strong><?= $e($orderNumber) ?></strong><?= $copyBtn($orderNumber) ?></dd>
    <?php if ($externalId !== ''): ?>
      <dt>Zewn. ID:</dt>
      <dd><?= $e($externalId) ?><?= $copyBtn($externalId) ?></dd>
    <?php endif; ?>
  </div>
</div>

<div class="order-preview-section">
  <div class="order-preview-section__title"><?= $e($t('orders.preview.buyer')) ?></div>
  <div class="order-preview-kv">
    <?php if ($buyerName !== ''): ?>
      <dt>Nazwa:</dt>
      <dd><?= $e($buyerName) ?><?= $copyBtn($buyerName) ?></dd>
    <?php endif; ?>
    <?php if ($buyerEmail !== ''): ?>
      <dt>Email:</dt>
      <dd><?= $e($buyerEmail) ?><?= $copyBtn($buyerEmail) ?></dd>
    <?php endif; ?>
    <?php if ($buyerPhone !== ''): ?>
      <dt>Telefon:</dt>
      <dd><?= $e($buyerPhone) ?><?= $copyBtn($buyerPhone) ?></dd>
    <?php endif; ?>
    <?php if ($buyerName === '' && $buyerEmail === ''): ?>
      <dt></dt><dd class="muted">Brak danych</dd>
    <?php endif; ?>
  </div>
</div>

<div class="order-preview-section">
  <div class="order-preview-section__title"><?= $e($t('orders.preview.delivery_address')) ?></div>
  <?php if ($delivery !== []): ?>
    <div class="order-preview-kv">
      <?php if ($deliveryName !== ''): ?>
        <dt>Odbiorca:</dt>
        <dd><?= $e($deliveryName) ?><?= $copyBtn($deliveryName) ?></dd>
      <?php endif; ?>
      <?php if ($deliveryStreet !== ''): ?>
        <dt>Ulica:</dt>
        <dd><?= $e($deliveryStreet) ?></dd>
      <?php endif; ?>
      <?php if ($deliveryCity !== ''): ?>
        <dt>Miasto:</dt>
        <dd><?= $e($deliveryCity) ?></dd>
      <?php endif; ?>
      <?php if ($deliveryParcel !== ''): ?>
        <dt>Punkt:</dt>
        <dd><?= $e($deliveryParcel) ?><?= $deliveryParcelId !== '' ? ' (' . $e($deliveryParcelId) . ')' : '' ?></dd>
      <?php endif; ?>
    </div>
    <div style="margin-top:4px">
      <button type="button" class="copy-field__btn" data-copy-value="<?= $e($fullDeliveryAddress) ?>" title="Kopiuj caly adres" style="font-size:11px;opacity:0.7">
        <?= $copyIcon ?> Kopiuj caly adres
      </button>
    </div>
  <?php else: ?>
    <div class="muted">Brak danych</div>
  <?php endif; ?>
</div>

<?php if ($itemsList !== []): ?>
<div class="order-preview-section">
  <div class="order-preview-section__title"><?= $e($t('orders.preview.products')) ?> (<?= $e((string) count($itemsList)) ?>)</div>
  <table class="order-preview-items">
    <thead>
      <tr>
        <th>Produkt</th>
        <th>Ilosc</th>
        <th>Cena</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($itemsList as $item): ?>
        <?php
        $qty = (float) ($item['quantity'] ?? 0);
        $price = $item['original_price_with_tax'] !== null ? (float) $item['original_price_with_tax'] : null;
        $media = trim((string) ($item['media_url'] ?? ''));
        $personalization = trim((string) ($item['personalization'] ?? ''));
        ?>
        <tr>
          <td>
            <div class="order-preview-item-cell">
              <?php if ($media !== ''): ?>
                <img src="<?= $e($media) ?>" alt="" class="order-preview-item-thumb">
              <?php else: ?>
                <span class="order-preview-item-thumb order-preview-item-thumb--empty"></span>
              <?php endif; ?>
              <div class="order-preview-item-info">
                <div class="order-preview-item-name"><?= $e((string) ($item['original_name'] ?? '-')) ?></div>
                <?php if ($personalization !== ''): ?>
                  <div class="order-preview-personalization">
                    <?php foreach (explode("\n", $personalization) as $line): ?>
                      <?php if (trim($line) !== ''): ?>
                        <div class="order-preview-personalization__line"><?= $e(trim($line)) ?></div>
                      <?php endif; ?>
                    <?php endforeach; ?>
                  </div>
                <?php endif; ?>
              </div>
            </div>
          </td>
          <td><?= $e((string) $qty) ?></td>
          <td><?= $e($price !== null ? number_format($price, 2, '.', ' ') . ' ' . $currency : '-') ?></td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>
<?php endif; ?>

<?php if ($notesList !== []): ?>
<div class="order-preview-section">
  <div class="order-preview-section__title"><?= $e($t('orders.preview.notes')) ?></div>
  <div class="order-preview-notes">
    <?php foreach ($notesList as $note): ?>
      <div class="order-preview-notes__item">
        <div class="order-preview-notes__type"><?= $e((string) ($note['note_type'] ?? '')) ?> | <?= $e((string) ($note['created_at_external'] ?? '')) ?></div>
        <div class="order-preview-notes__text"><?= $e((string) ($note['comment'] ?? '')) ?><?= $copyBtn(trim((string) ($note['comment'] ?? ''))) ?></div>
      </div>
    <?php endforeach; ?>
  </div>
</div>
<?php endif; ?>

<div class="order-preview-section">
  <div class="order-preview-section__title"><?= $e($t('orders.preview.summary')) ?></div>
  <div class="order-preview-kv">
    <dt>Razem:</dt>
    <dd><strong><?= $e($totalWithTax . ' ' . $currency) ?></strong></dd>
    <dt>Oplacono:</dt>
    <dd><?= $e($totalPaid . ' ' . $currency) ?></dd>
    <?php
    $paymentType = strtoupper(trim((string) ($orderRow['external_payment_type_id'] ?? '')));
    if ($paymentType !== ''):
    ?>
      <dt>Platnosc:</dt>
      <dd><?= $e($paymentType) ?></dd>
    <?php endif; ?>
  </div>
</div>
