<?php
$orderRow = is_array($order ?? null) ? $order : [];
$itemsList = is_array($items ?? null) ? $items : [];
$configsList = is_array($configs ?? null) ? $configs : [];
$sellerData = is_array($seller ?? null) ? $seller : [];
$totalGrossVal = (float) ($totalGross ?? 0);
$deliveryPriceVal = (float) ($deliveryPrice ?? 0);
$orderIdVal = (int) ($orderId ?? 0);
$existingReceiptsList = is_array($existingReceipts ?? null) ? $existingReceipts : [];
$hasExistingReceipts = $existingReceiptsList !== [];
?>

<section class="card">
  <div class="order-details-head">
    <div>
      <a href="/orders/<?= $e((string) $orderIdVal) ?>" class="order-back-link">&larr; <?= $e($t('receipts.create.back')) ?></a>
      <h2 class="section-title mt-12"><?= $e($t('receipts.create.title')) ?></h2>
      <div class="order-details-sub mt-4">
        <?= $e($t('orders.details.title')) ?> <?= $e((string) ($orderRow['internal_order_number'] ?? ('#' . $orderIdVal))) ?>
      </div>
    </div>
  </div>

  <?php if ($hasExistingReceipts): ?>
    <div class="alert alert--warning mt-12">
      <strong>Uwaga!</strong> Do tego zamówienia wystawiono już <?= $e((string) count($existingReceiptsList)) ?> paragon(ów):
      <ul class="mt-4">
        <?php foreach ($existingReceiptsList as $er): ?>
          <li>
            <strong><?= $e((string) ($er['receipt_number'] ?? '-')) ?></strong>
            <?php $erIssueDate = (string) ($er['issue_date'] ?? '-'); ?>
            — data: <?= $e(strlen($erIssueDate) >= 16 ? substr($erIssueDate, 0, 16) : $erIssueDate) ?>,
            kwota: <?= $e(number_format((float) ($er['total_gross'] ?? 0), 2, '.', ' ')) ?> PLN
            (<?= $e((string) ($er['config_name'] ?? '-')) ?>)
          </li>
        <?php endforeach; ?>
      </ul>
    </div>
  <?php endif; ?>

  <form id="receipt-create-form" method="post" action="/orders/<?= $e((string) $orderIdVal) ?>/receipt/store" class="mt-16">
    <input type="hidden" name="_token" value="<?= $e((string) ($csrfToken ?? '')) ?>">

    <div class="form-grid-2">
      <div class="form-group">
        <label class="form-label" for="config_id"><?= $e($t('receipts.create.select_config')) ?></label>
        <select name="config_id" id="config_id" class="form-control" required>
          <option value="">— <?= $e($t('receipts.create.select_config')) ?> —</option>
          <?php foreach ($configsList as $cfg): ?>
            <option value="<?= $e((string) ($cfg['id'] ?? '')) ?>">
              <?= $e((string) ($cfg['name'] ?? '')) ?> (<?= $e((string) ($cfg['number_format'] ?? '')) ?>)
            </option>
          <?php endforeach; ?>
        </select>
      </div>

      <div class="form-group">
        <label class="form-label" for="issue_date"><?= $e($t('receipts.create.issue_date')) ?></label>
        <input type="datetime-local" name="issue_date" id="issue_date" class="form-control" value="<?= $e(date('Y-m-d\TH:i')) ?>" required>
      </div>
    </div>

    <h3 class="section-title mt-16"><?= $e($t('receipts.create.items')) ?></h3>
    <div class="table-wrap mt-8">
      <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">Brak pozycji</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 ? ($qty * $price) : null;
            ?>
            <tr>
              <td><?= $e((string) ($idx + 1)) ?></td>
              <td><?= $e((string) ($item['original_name'] ?? '')) ?></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; ?>
          <?php if ($deliveryPriceVal > 0): ?>
            <tr>
              <td><?= $e((string) (count($itemsList) + 1)) ?></td>
              <td>Koszt wysylki</td>
              <td><div>-</div><div class="muted">-</div></td>
              <td>1</td>
              <td><?= $e(number_format($deliveryPriceVal, 2, '.', ' ')) ?></td>
              <td><?= $e(number_format($deliveryPriceVal, 2, '.', ' ')) ?></td>
            </tr>
          <?php endif; ?>
        </tbody>
        <tfoot>
          <tr>
            <td colspan="5" class="text-right"><strong><?= $e($t('receipts.create.total')) ?></strong></td>
            <td><strong><?= $e(number_format($totalGrossVal, 2, '.', ' ')) ?> <?= $e((string) ($orderRow['currency'] ?? 'PLN')) ?></strong></td>
          </tr>
        </tfoot>
      </table>
    </div>

    <h3 class="section-title mt-16"><?= $e($t('receipts.create.seller_data')) ?></h3>
    <div class="receipt-seller-preview mt-8">
      <dl class="order-kv">
        <dt>Firma</dt><dd><?= $e((string) ($sellerData['company_name'] ?? '-')) ?></dd>
        <dt>NIP</dt><dd><?= $e((string) ($sellerData['tax_number'] ?? '-')) ?></dd>
        <dt>Adres</dt><dd><?= $e((string) ($sellerData['street'] ?? '')) ?>, <?= $e((string) ($sellerData['postal_code'] ?? '')) ?> <?= $e((string) ($sellerData['city'] ?? '')) ?></dd>
        <dt>Telefon</dt><dd><?= $e((string) ($sellerData['phone'] ?? '-')) ?></dd>
        <dt>Email</dt><dd><?= $e((string) ($sellerData['email'] ?? '-')) ?></dd>
      </dl>
    </div>

    <div class="mt-16">
      <?php if ($hasExistingReceipts): ?>
        <button type="button" id="receipt-submit-btn" class="btn btn--primary"><?= $e($t('receipts.create.submit')) ?></button>
      <?php else: ?>
        <button type="submit" class="btn btn--primary"><?= $e($t('receipts.create.submit')) ?></button>
      <?php endif; ?>
      <a href="/orders/<?= $e((string) $orderIdVal) ?>" class="btn btn--secondary ml-8"><?= $e($t('receipts.create.cancel')) ?></a>
    </div>
  </form>
</section>

<?php if ($hasExistingReceipts): ?>
<script>
document.getElementById('receipt-submit-btn').addEventListener('click', function() {
    window.OrderProAlerts.confirm(
        'Do tego zamówienia wystawiono już paragon. Czy na pewno chcesz wystawić kolejny?',
        function() {
            document.getElementById('receipt-create-form').submit();
        }
    );
});
</script>
<?php endif; ?>
