<?php
$supplierName = trim((string)($inv['supplier_name'] ?? '')) ?: 'مورد غير محدد';
$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');
$supplierCode = trim((string)($inv['supplier_code'] ?? ''));
$warehouseName = trim((string)($inv['warehouse_name'] ?? ''));
$invoiceNo = trim((string)($inv['inv_no'] ?? ''));
$invoiceDate = trim((string)substr((string)($inv['inv_date'] ?? ''), 0, 10));
$notes = trim((string)($inv['notes'] ?? ''));
$subtotal = (float)($inv['subtotal'] ?? 0);
$discount = (float)($inv['discount_amount'] ?? 0);
$extraExpenses = (float)($inv['extra_expenses'] ?? 0);
$vatEnabled = (int)($inv['vat_enabled'] ?? 0) === 1;
$vatRate = (float)($inv['vat_rate'] ?? 0);
$vatAmount = (float)($inv['vat_amount'] ?? 0);
$whtEnabled = (int)($inv['wht_enabled'] ?? 0) === 1;
$whtRate = (float)($inv['wht_rate'] ?? 0);
$whtAmount = (float)($inv['wht_amount'] ?? 0);
$whtNoticeNo = trim((string)($inv['wht_notice_no'] ?? ''));
$netAfterDiscount = $subtotal - $discount;
$grandTotal = (float)($inv['grand_total'] ?? ($netAfterDiscount + $extraExpenses + ($vatEnabled ? $vatAmount : 0) - ($whtEnabled ? $whtAmount : 0)));
$totalQty = 0.0;
foreach (($lines ?? []) as $line) {
    $totalQty += (float)($line['qty'] ?? 0);
}

if (($print_format ?? 'a4') === 'receipt'):
?>
<?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($supplierName) ?></strong></div>
  <div><span>المخزن</span><strong><?= e($warehouseName !== '' ? $warehouseName : '-') ?></strong></div>
  <?php if ($supplierCode !== ''): ?><div><span>كود المورد</span><strong><?= e($supplierCode) ?></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 $line): $i++; ?>
      <tr>
        <td><?= $i ?></td>
        <td><?= e((string)($line['item_name'] ?? '')) ?><?php $unitLabel = trim((string)($line['unit_name'] ?? $line['unit_symbol'] ?? '')); ?><?php if ($unitLabel !== ''): ?><div class="receipt-line-meta"><?= e($unitLabel) ?> × <?= e(format_money($line['unit_price'] ?? 0)) ?></div><?php endif; ?></td>
        <td><?= e(format_qty($line['qty'] ?? 0)) ?></td>
        <td><?= e(format_money($line['line_total'] ?? 0)) ?></td>
      </tr>
    <?php endforeach; ?>
  </tbody>
</table>
  <?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 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.0): ?><div><span>الخصم</span><strong><?= e(format_money($discount)) ?></strong></div><?php endif; ?>
  <?php if ($extraExpenses != 0.0): ?><div><span>مصاريف إضافية</span><strong><?= e(format_money($extraExpenses)) ?></strong></div><?php endif; ?>
  <?php if ($vatEnabled): ?><div><span>الضريبة <?= e(format_qty($vatRate, 2)) ?>%</span><strong><?= e(format_money($vatAmount)) ?></strong></div><?php endif; ?>
  <?php if ($whtEnabled): ?><div><span>خصم المنبع <?= e(format_qty($whtRate, 2)) ?>%<?= $whtNoticeNo !== '' ? ' - ' . e($whtNoticeNo) : '' ?></span><strong><?= e(format_money($whtAmount)) ?></strong></div><?php endif; ?>
  <div class="grand"><span><?= e($section['title']) ?></span><strong><?= e(format_money($grandTotal)) ?></strong></div>
</div>
  <?php endif; ?>
<?php endforeach; ?>
<?php return; endif; ?>

<?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<?= $sectionKey === 'party_block' ? '' : ' print-section' ?>">
    <?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">PURCHASE 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($supplierName) ?></div>
      <div class="pi-party-meta-grid">
        <div><span>كود المورد</span><strong><?= e($supplierCode !== '' ? $supplierCode : '-') ?></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 if ($sectionKey === 'party_block' && print_section_visible($printOptions, 'body', 'hero_totals', true)) continue; ?>
      <?php if ($sectionKey === 'hero_totals' && print_section_visible($printOptions, 'body', 'party_block', true)) continue; ?>
    <?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-unit">الوحدة</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 $line): $i++; ?>
            <tr>
              <td class="text-center"><?= $i ?></td>
              <td><div class="pi-item-name"><?= e((string)($line['item_name'] ?? '')) ?></div></td>
              <td class="text-center"><?= e((string)($line['unit_name'] ?? $line['unit_symbol'] ?? '-')) ?></td>
              <td class="text-center"><?= e(format_qty($line['qty'] ?? 0)) ?></td>
              <td class="text-left"><?= e(format_money($line['unit_price'] ?? 0)) ?></td>
              <td class="text-left is-strong"><?= e(format_money($line['line_total'] ?? 0)) ?></td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </section>
  <?php elseif ($sectionKey === 'notes' || $sectionKey === 'totals'): ?>
    <?php if ($bottomSectionsRendered) { continue; } $bottomSectionsRendered = true; ?>
  <section class="pi-bottom-grid keep-together">
    <?php if (print_section_visible($printOptions, 'body', 'notes', true)): ?>
    <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 (print_section_visible($printOptions, 'body', 'totals', true)): ?>
    <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 ($extraExpenses != 0.0): ?><tr><td>مصاريف إضافية</td><td><?= e(format_money($extraExpenses)) ?></td></tr><?php endif; ?>
        <?php if ($vatEnabled): ?><tr><td>ضريبة القيمة المضافة (<?= e(format_qty($vatRate, 2)) ?>%)</td><td><?= e(format_money($vatAmount)) ?></td></tr><?php endif; ?>
        <?php if ($whtEnabled): ?><tr><td>ضريبة خصم (<?= e(format_qty($whtRate, 2)) ?>%)<?= $whtNoticeNo !== '' ? ' - ' . e($whtNoticeNo) : '' ?></td><td><?= e(format_money($whtAmount)) ?></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; ?>
