<?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');
$customer = trim((string)($ret['customer_name'] ?? '-')) ?: '-';
$customerCode = trim((string)($ret['customer_code'] ?? ''));
$warehouse = trim((string)($ret['warehouse_name'] ?? ''));
$sourceInv = trim((string)($ret['source_inv_no'] ?? ''));
$settlementType = (string)($ret['settlement_type'] ?? '');
$settlement = ($settlementType === 'cash_refund') ? 'رد نقدي' : 'رصيد للعميل';
$cashbox = trim((string)($ret['cashbox_name'] ?? ''));
$reason = trim((string)($ret['reason'] ?? ''));
$notes = trim((string)($ret['notes'] ?? ''));
$returnNo = trim((string)($ret['return_no'] ?? $meta['no'] ?? ''));
$returnDate = trim((string)substr((string)($ret['return_date'] ?? $meta['date'] ?? ''), 0, 10));
$total = (float)($ret['total_amount'] ?? 0);
$totalQty = 0.0;
foreach (($lines ?? []) as $ln) { $totalQty += (float)($ln['qty'] ?? 0); }
$noteParts = [];
if ($reason !== '') { $noteParts[] = 'السبب: ' . $reason; }
if ($notes !== '') { $noteParts[] = 'ملاحظات: ' . $notes; }
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($customer) ?></strong></div>
  <?php if ($customerCode !== ''): ?><div><span>كود العميل</span><strong><?= e($customerCode) ?></strong></div><?php endif; ?>
  <div><span>فاتورة المصدر</span><strong><?= e($sourceInv !== '' ? $sourceInv : '-') ?></strong></div>
  <div><span>نوع التسوية</span><strong><?= e($settlement) ?></strong></div>
  <?php if ($settlementType === 'cash_refund'): ?><div><span>الخزنة</span><strong><?= e($cashbox !== '' ? $cashbox : '-') ?></strong></div><?php endif; ?>
  <?php if ($warehouse !== ''): ?><div><span>المخزن</span><strong><?= e($warehouse) ?></strong></div><?php endif; ?>
</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['item_name'] ?? '')) ?><div class="receipt-line-meta"><?= e(format_money($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 === 'notes' && $noteParts !== []): ?>
<div class="receipt-note-box"><div class="receipt-note-title"><?= e($section['title']) ?></div><?php foreach ($noteParts as $line): ?><div><?= e($line) ?></div><?php endforeach; ?></div>
  <?php elseif ($sectionKey === 'totals'): ?>
<div class="receipt-summary">
  <div><span>إجمالي الكمية</span><strong><?= e(format_qty($totalQty)) ?></strong></div>
  <div class="grand"><span><?= e($section['title']) ?></span><strong><?= e(format_money($total)) ?></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">
    <?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 RETURN</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($customer) ?></div>
      <div class="pi-party-meta-grid">
        <div><span>كود العميل</span><strong><?= e($customerCode !== '' ? $customerCode : '-') ?></strong></div>
        <div><span>فاتورة المصدر</span><strong><?= e($sourceInv !== '' ? $sourceInv : '-') ?></strong></div>
        <div><span>نوع التسوية</span><strong><?= e($settlement) ?></strong></div>
        <div><span>المخزن</span><strong><?= e($warehouse !== '' ? $warehouse : '-') ?></strong></div>
        <div><span>عدد البنود</span><strong><?= e((string)count($lines ?? [])) ?></strong></div>
        <div><span>إجمالي الكمية</span><strong><?= e(format_qty($totalQty)) ?></strong></div>
        <?php if ($settlementType === 'cash_refund'): ?><div><span>الخزنة</span><strong><?= e($cashbox !== '' ? $cashbox : '-') ?></strong></div><?php endif; ?>
      </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_qty($totalQty)) ?></strong></div>
        <div class="pi-stat-box is-accent"><span>إجمالي المرتجع</span><strong><?= e(format_money($total)) ?></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['item_name'] ?? '')) ?></div></td>
              <td class="text-center"><?= e(format_qty($ln['qty'] ?? 0)) ?></td>
              <td class="text-left"><?= e(format_money($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; ?>
  <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"><?php if ($noteParts !== []): ?><?php foreach ($noteParts as $idx => $line): ?><?= $idx > 0 ? "\n\n" : '' ?><?= e($line) ?><?php endforeach; ?><?php else: ?>لا توجد ملاحظات إضافية على هذا المرتجع.<?php endif; ?></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_qty($totalQty)) ?></td></tr>
        <tr class="is-grand"><td>إجمالي المرتجع</td><td><?= e(format_money($total)) ?></td></tr>
      </table>
    </div>
    <?php else: ?>
    <div></div>
    <?php endif; ?>
  </section>
  <?php endif; ?>
<?php endforeach; ?>
