<?php
$printOptions = is_array($print_options ?? null) ? $print_options : [];
$bodySections = print_sections_ordered([
  'party_block' => ['enabled' => true, 'title' => 'بيانات العميل والفاتورة', 'order' => 10],
  'hero_totals' => ['enabled' => true, 'title' => 'ملخص سريع', 'order' => 20],
  'items_table' => ['enabled' => true, 'title' => 'تفاصيل الفاتورة', 'order' => 30],
  'notes' => ['enabled' => true, 'title' => 'ملاحظات', 'order' => 40],
  'totals' => ['enabled' => true, 'title' => 'الملخص المالي', 'order' => 50],
], $printOptions, 'body');

if (($print_format ?? 'a4') === 'receipt'):
$customerName = (string)($inv['party_name'] ?? $inv['customer_name'] ?? $inv['customer'] ?? '-');
$customerCode = trim((string)($inv['customer_code'] ?? $inv['party_code'] ?? ''));
$invoiceNo = (string)($inv['invoice_no'] ?? '');
$invoiceDate = (string)substr((string)($inv['invoice_date'] ?? ''), 0, 10);
$warehouseName = trim((string)($inv['warehouse_name'] ?? ''));
$notes = trim((string)($inv['notes'] ?? ''));
$subtotal = (float)($inv['subtotal'] ?? $inv['total'] ?? 0);
$discount = (float)($inv['discount_amount'] ?? 0);
$vatEnabled = (int)($inv['vat_enabled'] ?? 0) === 1;
$vatAmount = (float)($inv['vat_amount'] ?? 0);
$grandTotal = (float)($inv['grand_total'] ?? $inv['total'] ?? ($subtotal - $discount + ($vatEnabled ? $vatAmount : 0)));
$totalQty = 0.0; foreach (($lines ?? []) as $ln) { $totalQty += (float)($ln['qty'] ?? 0); }
?>
<?php foreach ($bodySections as $sectionKey => $section): if (empty($section['enabled'])) { continue; } ?>
  <?php if ($sectionKey === 'party_block'): ?>
<div class="receipt-meta-grid two-col">
  <div><span>العميل</span><strong><?= e($customerName ?: '-') ?></strong></div>
  <?php if ($customerCode !== ''): ?><div><span>كود العميل</span><strong><?= e($customerCode) ?></strong></div><?php endif; ?>
  <?php if ($warehouseName !== ''): ?><div><span>المخزن</span><strong><?= e($warehouseName) ?></strong></div><?php endif; ?>
  <div><span>عدد البنود</span><strong><?= e((string)count($lines ?? [])) ?></strong></div>
</div>
  <?php elseif ($sectionKey === 'items_table'): ?>
<table class="receipt-table">
  <thead><tr><th>#</th><th>الصنف</th><th>الكمية</th><th>الإجمالي</th></tr></thead>
  <tbody>
    <?php $i = 0; foreach (($lines ?? []) as $ln): $i++; ?>
      <tr>
        <td><?= $i ?></td>
        <td><?= e((string)($ln['name'] ?? $ln['item_name'] ?? '')) ?><div class="receipt-line-meta"><?= e(format_money($ln['price'] ?? $ln['unit_price'] ?? 0)) ?> × <?= e(format_qty($ln['qty'] ?? 0)) ?></div></td>
        <td><?= e(format_qty($ln['qty'] ?? 0)) ?></td>
        <td><?= e(format_money($ln['line_total'] ?? 0)) ?></td>
      </tr>
    <?php endforeach; ?>
  </tbody>
</table>
  <?php elseif ($sectionKey === 'totals'): ?>
<div class="receipt-summary">
  <div><span>إجمالي الكمية</span><strong><?= e(format_qty($totalQty)) ?></strong></div>
  <div><span>الإجمالي قبل الخصم</span><strong><?= e(format_money($subtotal)) ?></strong></div>
  <?php if ($discount != 0): ?><div><span>الخصم</span><strong><?= e(format_money($discount)) ?></strong></div><?php endif; ?>
  <?php if ($vatEnabled): ?><div><span>الضريبة</span><strong><?= e(format_money($vatAmount)) ?></strong></div><?php endif; ?>
  <div class="grand"><span>الإجمالي النهائي</span><strong><?= e(format_money($grandTotal)) ?></strong></div>
</div>
  <?php elseif ($sectionKey === 'notes' && $notes !== ''): ?>
<div class="receipt-note-box"><div class="receipt-note-title"><?= e($section['title']) ?></div><div><?= e($notes) ?></div></div>
  <?php endif; ?>
<?php endforeach; ?>
<?php return; endif; ?>

<?php
$customerName = trim((string)($inv['party_name'] ?? $inv['customer_name'] ?? $inv['customer'] ?? '')) ?: 'عميل غير محدد';
$customerCode = trim((string)($inv['customer_code'] ?? $inv['party_code'] ?? ''));
$warehouseName = trim((string)($inv['warehouse_name'] ?? ''));
$invoiceNo = trim((string)($inv['invoice_no'] ?? ''));
$invoiceDate = trim((string)substr((string)($inv['invoice_date'] ?? ''), 0, 10));
$notes = trim((string)($inv['notes'] ?? ''));
$subtotal = (float)($inv['subtotal'] ?? $inv['total'] ?? 0);
$discount = (float)($inv['discount_amount'] ?? 0);
$netAfterDiscount = $subtotal - $discount;
$vatEnabled = (int)($inv['vat_enabled'] ?? 0) === 1;
$vatRate = (float)($inv['vat_rate'] ?? 0);
$vatAmount = (float)($inv['vat_amount'] ?? 0);
$grandTotal = (float)($inv['grand_total'] ?? $inv['total'] ?? ($netAfterDiscount + ($vatEnabled ? $vatAmount : 0)));
$totalQty = 0.0;
foreach (($lines ?? []) as $ln) { $totalQty += (float)($ln['qty'] ?? 0); }
?>
<?php $pairedHeaderRendered = false; ?>
<?php $bottomSectionsRendered = false; ?>
<?php foreach ($bodySections as $sectionKey => $section): if (empty($section['enabled'])) continue; ?>
  <?php if ($sectionKey === 'party_block' || $sectionKey === 'hero_totals'): ?>
    <?php if ($pairedHeaderRendered) { continue; } $pairedHeaderRendered = true; ?>
    <?php if (print_section_visible($printOptions, 'body', 'party_block', true) || print_section_visible($printOptions, 'body', 'hero_totals', true)): ?>
  <section class="pi-hero">
    <?php if (print_section_visible($printOptions, 'body', 'party_block', true)): ?>
    <div class="pi-title-wrap">
      <h1 class="pi-title"><?= e(print_section_title($printOptions, 'body', 'party_block', 'فاتورة مبيعات')) ?></h1>
      <div class="pi-title-en">SALES INVOICE</div>
    </div>
    <?php endif; ?>
  </section>
  <section class="pi-party-summary-grid">
    <?php if (print_section_visible($printOptions, 'body', 'party_block', true)): ?>
    <div class="pi-party-card">
      <div class="pi-card-head"><?= e(print_section_title($printOptions, 'body', 'party_block', 'بيانات العميل والفاتورة')) ?></div>
      <div class="pi-party-name"><?= e($customerName) ?></div>
      <div class="pi-party-meta-grid">
        <div><span>كود العميل</span><strong><?= e($customerCode !== '' ? $customerCode : '-') ?></strong></div>
        <div><span>عدد البنود</span><strong><?= e((string)count($lines ?? [])) ?></strong></div>
        <div><span>إجمالي الكمية</span><strong><?= e(format_qty($totalQty)) ?></strong></div>
      </div>
    </div>
    <?php endif; ?>
    <?php if (print_section_visible($printOptions, 'body', 'hero_totals', true)): ?>
    <div class="pi-summary-card">
      <div class="pi-card-head"><?= e(print_section_title($printOptions, 'body', 'hero_totals', 'ملخص سريع')) ?></div>
      <div class="pi-summary-stats">
        <div class="pi-stat-box"><span>الإجمالي قبل الخصم</span><strong><?= e(format_money($subtotal)) ?></strong></div>
        <div class="pi-stat-box is-accent"><span>الإجمالي النهائي</span><strong><?= e(format_money($grandTotal)) ?></strong></div>
      </div>
    </div>
    <?php endif; ?>
  </section>
    <?php endif; ?>
  <?php elseif ($sectionKey === 'items_table'): ?>
  <section class="pi-table-section">
    <div class="pi-section-title"><?= e($section['title']) ?></div>
    <div class="pi-table-wrap">
      <table class="pi-table">
        <thead>
          <tr>
            <th class="col-no">#</th>
            <th>الصنف / البيان</th>
            <th class="col-qty">الكمية</th>
            <th class="col-price">سعر الوحدة</th>
            <th class="col-total">الإجمالي</th>
          </tr>
        </thead>
        <tbody>
          <?php $i = 0; foreach (($lines ?? []) as $ln): $i++; ?>
            <tr>
              <td class="text-center"><?= $i ?></td>
              <td><div class="pi-item-name"><?= e((string)($ln['name'] ?? $ln['item_name'] ?? '')) ?></div><?php if (!empty($ln['barcode'] ?? '')): ?><div class="muted">Barcode: <?= e((string)$ln['barcode']) ?></div><?php endif; ?></td>
              <td class="text-center"><?= e(format_qty($ln['qty'] ?? 0)) ?></td>
              <td class="text-left"><?= e(format_money($ln['price'] ?? $ln['unit_price'] ?? 0)) ?></td>
              <td class="text-left is-strong"><?= e(format_money($ln['line_total'] ?? 0)) ?></td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </section>
  <?php elseif ($sectionKey === 'notes' || $sectionKey === 'totals'): ?>
    <?php if ($bottomSectionsRendered) { continue; } $bottomSectionsRendered = true; ?>
    <?php $notesVisible = print_section_visible($printOptions, 'body', 'notes', true); ?>
    <?php $totalsVisible = print_section_visible($printOptions, 'body', 'totals', true); ?>
  <section class="pi-bottom-grid keep-together">
    <?php if ($notesVisible): ?>
    <div class="pi-terms-card">
      <div class="pi-card-head"><?= e(print_section_title($printOptions, 'body', 'notes', 'ملاحظات')) ?></div>
      <div class="pi-notes-box"><?= e($notes !== '' ? $notes : 'لا توجد ملاحظات إضافية على هذه الفاتورة.') ?></div>
    </div>
    <?php else: ?>
    <div></div>
    <?php endif; ?>
    <?php if ($totalsVisible): ?>
    <div class="pi-total-card">
      <div class="pi-card-head"><?= e(print_section_title($printOptions, 'body', 'totals', 'الملخص المالي')) ?></div>
      <table class="pi-total-table">
        <tr><td>الإجمالي قبل الخصم</td><td><?= e(format_money($subtotal)) ?></td></tr>
        <?php if ($discount != 0.0): ?><tr><td>الخصم</td><td><?= e(format_money($discount)) ?></td></tr><tr><td>الصافي بعد الخصم</td><td><?= e(format_money($netAfterDiscount)) ?></td></tr><?php endif; ?>
        <?php if ($vatEnabled): ?><tr><td>ضريبة القيمة المضافة (<?= e(format_qty($vatRate, 2)) ?>%)</td><td><?= e(format_money($vatAmount)) ?></td></tr><?php endif; ?>
        <tr class="is-grand"><td>الإجمالي النهائي</td><td><?= e(format_money($grandTotal)) ?></td></tr>
      </table>
    </div>
    <?php else: ?>
    <div></div>
    <?php endif; ?>
  </section>
  <?php endif; ?>
<?php endforeach; ?>
