<?php
$printOptions = is_array($print_options ?? null) ? $print_options : [];
$showLogo = !array_key_exists('show_logo', $printOptions) || !empty($printOptions['show_logo']);
$showTaxNo = !array_key_exists('show_tax_no', $printOptions) || !empty($printOptions['show_tax_no']);
$companyName = trim((string)($company['name'] ?? '')) ?: 'اسم الشركة';
$companySub = trim((string)($company['subtitle'] ?? ($company['sub'] ?? '')));
$logoPath = $showLogo ? trim((string)($company['logo_path'] ?? '')) : '';
$logoUrl = '';
if ($logoPath !== '') {
    $logoUrl = preg_match('~^(?:data:|https?://|/)~i', $logoPath) ? $logoPath : asset(ltrim($logoPath, '/'));
}
$docNo = (string)($meta['no'] ?? '');
$docDate = (string)($meta['date'] ?? '');
$titleEn = trim((string)($meta['title_en'] ?? ''));
$validUntil = (string)($meta['valid_until'] ?? '');
$contactBits = [];
if (!empty($company['phone'])) $contactBits[] = (string)$company['phone'];
if (!empty($company['email'])) $contactBits[] = (string)$company['email'];
if (!empty($company['website'])) $contactBits[] = (string)$company['website'];
if ($showTaxNo && !empty($company['tax_no'])) $contactBits[] = 'الرقم الضريبي: ' . (string)$company['tax_no'];
$companyAddress = trim((string)($company['address'] ?? ''));
$headerSections = print_sections_ordered([
    'company_block' => ['enabled' => true, 'title' => 'بيانات الشركة', 'order' => 10],
    'document_meta' => ['enabled' => true, 'title' => 'بيانات المستند', 'order' => 20],
], $printOptions, 'header');

$renderReceiptCompany = static function () use ($logoUrl, $companyName, $companySub, $companyAddress, $contactBits): void {
    ?>
    <div class="receipt-company">
      <div class="receipt-company-name"><?= e($companyName) ?></div>
      <?php if ($companySub !== ''): ?><div class="receipt-company-sub"><?= e($companySub) ?></div><?php endif; ?>
      <?php if ($companyAddress !== ''): ?><div class="receipt-company-sub"><?= e($companyAddress) ?></div><?php endif; ?>
      <?php if ($contactBits): ?><div class="receipt-company-contact"><?= e(implode(' | ', $contactBits)) ?></div><?php endif; ?>
    </div>
    <?php
};
$renderReceiptMeta = static function () use ($docNo, $docDate, $validUntil): void {
    ?>
    <div class="receipt-meta">
      <?php if ($docNo !== ''): ?><div class="receipt-meta-row"><span>رقم المستند</span><strong><?= e($docNo) ?></strong></div><?php endif; ?>
      <?php if ($docDate !== ''): ?><div class="receipt-meta-row"><span>التاريخ</span><strong><?= e(substr($docDate, 0, 10)) ?></strong></div><?php endif; ?>
      <?php if ($validUntil !== ''): ?><div class="receipt-meta-row"><span>ساري حتى</span><strong><?= e(substr($validUntil, 0, 10)) ?></strong></div><?php endif; ?>
    </div>
    <?php
};
?>
<?php $isReportPrint = !empty($report_mode) || !empty(($print_options['report_mode'] ?? false)); ?>
<?php if ($isReportPrint): ?>
<?php
  $reportTitle = trim((string)($title ?? 'تقرير'));
  $reportDateValue = trim((string)($reportDate ?? $docDate ?? date('Y-m-d')));
  $generatedBy = trim((string)($userName ?? ''));
  $periodFrom = trim((string)($filters['from'] ?? ''));
  $periodTo = trim((string)($filters['to'] ?? ''));
  $reportPeriod = trim(($periodFrom !== '' || $periodTo !== '') ? (($periodFrom !== '' ? $periodFrom : '...') . ' - ' . ($periodTo !== '' ? $periodTo : '...')) : (string)($meta['period'] ?? ''));
?>
<div class="report-print-header">
  <div class="report-header-bar"></div>
  <div class="report-header-main">
    <div class="report-brand">
      <?php if ($logoUrl !== ''): ?><div class="report-logo"><img src="<?= e($logoUrl) ?>" alt="logo"></div><?php endif; ?>
      <div class="report-company">
        <div class="report-company-name"><?= e($companyName) ?></div>
        <?php if ($companySub !== ''): ?><div><?= e($companySub) ?></div><?php endif; ?>
        <?php if ($companyAddress !== ''): ?><div><?= e($companyAddress) ?></div><?php endif; ?>
        <?php if ($contactBits): ?><div class="report-company-meta"><?= e(implode(' | ', $contactBits)) ?></div><?php endif; ?>
      </div>
    </div>
    <div class="report-doc-meta">
      <div><span>نوع المستند</span><strong>تقرير</strong></div>
      <div><span>اسم التقرير</span><strong><?= e($reportTitle) ?></strong></div>
      <div><span>التاريخ</span><strong><?= e(substr($reportDateValue, 0, 10)) ?></strong></div>
      <?php if ($reportPeriod !== ''): ?><div><span>الفترة</span><strong><?= e($reportPeriod) ?></strong></div><?php endif; ?>
      <?php if ($generatedBy !== ''): ?><div><span>المستخدم</span><strong><?= e($generatedBy) ?></strong></div><?php endif; ?>
    </div>
  </div>
</div>
<?php elseif (($print_format ?? '') === 'receipt'): ?>
<?php
  $receiptHeaderNoLabel = 'رقم المستند';
  $receiptTitle = trim((string)($title ?? ''));
  if (mb_strpos($receiptTitle, 'فاتورة') !== false) {
      $receiptHeaderNoLabel = 'رقم الفاتورة';
  } elseif (mb_strpos($receiptTitle, 'مرتجع') !== false) {
      $receiptHeaderNoLabel = 'رقم المرتجع';
  } elseif (mb_strpos($receiptTitle, 'سند') !== false) {
      $receiptHeaderNoLabel = 'رقم السند';
  } elseif (mb_strpos($receiptTitle, 'شيك') !== false) {
      $receiptHeaderNoLabel = 'رقم الشيك';
  } elseif (mb_strpos($receiptTitle, 'عرض') !== false) {
      $receiptHeaderNoLabel = 'رقم العرض';
  }
?>
<div class="receipt-header">
  <?php if ($logoUrl !== ''): ?>
    <div class="receipt-logo"><img src="<?= e($logoUrl) ?>" alt="logo"></div>
  <?php endif; ?>
  <div class="receipt-company-name"><?= e($companyName) ?></div>
  <?php if ($companySub !== ''): ?><div class="receipt-company-sub"><?= e($companySub) ?></div><?php endif; ?>
  <?php if ($companyAddress !== ''): ?><div class="receipt-company-sub"><?= e($companyAddress) ?></div><?php endif; ?>
  <?php if ($contactBits): ?><div class="receipt-company-contact"><?= e(implode(' | ', $contactBits)) ?></div><?php endif; ?>

  <div class="receipt-doc-title"><?= e($title ?? '') ?></div>
  <?php if ($docNo !== '' || $docDate !== '' || $validUntil !== ''): ?>
  <div class="receipt-head-chips">
    <?php if ($docNo !== ''): ?><div class="receipt-head-chip"><span><?= e($receiptHeaderNoLabel) ?></span><strong><?= e($docNo) ?></strong></div><?php endif; ?>
    <?php if ($docDate !== ''): ?><div class="receipt-head-chip"><span>التاريخ</span><strong><?= e(substr($docDate, 0, 10)) ?></strong></div><?php endif; ?>
    <?php if ($validUntil !== ''): ?><div class="receipt-head-chip"><span>ساري حتى</span><strong><?= e(substr($validUntil, 0, 10)) ?></strong></div><?php endif; ?>
  </div>
  <?php endif; ?>
</div>
<?php elseif (false && ($print_template ?? '') === 'quotation_v2'): ?>
<div class="quotation-print-header">
  <div class="qph-topbar"></div>
  <div class="qph-main">
    <?php foreach ($headerSections as $sectionKey => $section): if (empty($section['enabled'])) { continue; } ?>
      <?php if ($sectionKey === 'company_block'): ?>
        <div class="qph-brand-block">
          <div class="qph-brand-head">
            <?php if ($logoUrl !== ''): ?>
              <div class="qph-logo"><img src="<?= e($logoUrl) ?>" alt="logo"></div>
            <?php endif; ?>
            <div class="qph-company-copy">
              <div class="qph-company-name"><?= e($companyName) ?></div>
              <?php if ($companySub !== ''): ?><div class="qph-company-sub"><?= e($companySub) ?></div><?php endif; ?>
              <?php if ($companyAddress !== ''): ?><div class="qph-company-sub"><?= e($companyAddress) ?></div><?php endif; ?>
              <?php if ($contactBits): ?><div class="qph-company-meta"><?= e(implode(' | ', $contactBits)) ?></div><?php endif; ?>
            </div>
          </div>
        </div>
      <?php elseif ($sectionKey === 'document_meta'): ?>
        <div class="qph-doc-block">
          <div class="qph-doc-title"><?= e($title ?? '') ?></div>
          <?php if ($titleEn !== ''): ?><div class="qph-doc-title-en"><?= e($titleEn) ?></div><?php endif; ?>
          <?php if (!empty($printOptions['active_template_label'])): ?><div class="qph-doc-title-en"><?= e((string)$printOptions['active_template_label']) ?></div><?php endif; ?>
          <div class="qph-doc-meta">
            <?php if ($docNo !== ''): ?><div class="qph-meta-row"><span><?= e(print_section_title($printOptions, 'header', 'document_meta', 'بيانات العرض')) ?></span><strong><?= e($docNo) ?></strong></div><?php endif; ?>
            <?php if ($docDate !== ''): ?><div class="qph-meta-row"><span>التاريخ</span><strong><?= e(substr($docDate, 0, 10)) ?></strong></div><?php endif; ?>
            <?php if ($validUntil !== ''): ?><div class="qph-meta-row"><span>ساري حتى</span><strong><?= e(substr($validUntil, 0, 10)) ?></strong></div><?php endif; ?>
          </div>
        </div>
      <?php endif; ?>
    <?php endforeach; ?>
  </div>
</div>
<?php elseif (($print_format ?? $format ?? '') === 'a4'): ?>
<?php
  $invoiceHeaderNo = trim((string)(
      $inv['invoice_no'] ?? $inv['inv_no'] ??
      $ret['ret_no'] ?? $ret['return_no'] ??
      $receipt['receipt_no'] ??
      $payment['pay_no'] ?? $payment['payment_no'] ??
      $row['voucher_no'] ?? $row['doc_no'] ??
      $quotation['quotation_no'] ??
      $party['code'] ??
      $docNo ?? ''
  ));
  $invoiceHeaderDate = trim((string)(
      $inv['invoice_date'] ?? $inv['inv_date'] ??
      $ret['ret_date'] ?? $ret['return_date'] ??
      $receipt['receipt_date'] ??
      $payment['pay_date'] ?? $payment['payment_date'] ??
      $row['voucher_date'] ?? $row['doc_date'] ??
      $quotation['quotation_date'] ??
      $docDate ?? ''
  ));
  $invoiceHeaderWarehouse = trim((string)($inv['warehouse_name'] ?? $ret['warehouse_name'] ?? $row['warehouse_name'] ?? ''));
  $invoiceHeaderStatus = trim((string)($meta['status'] ?? ''));
  $invoiceHeaderPeriod = trim((string)($meta['period'] ?? ''));
  $invoiceHeaderTitle = trim((string)($title ?? ''));
  $invoiceNoLabel = (mb_strpos($invoiceHeaderTitle, 'فاتورة') !== false) ? 'رقم الفاتورة' : 'رقم المستند';
  if (mb_strpos($invoiceHeaderTitle, 'عرض') !== false) {
      $invoiceNoLabel = 'رقم العرض';
  } elseif (mb_strpos($invoiceHeaderTitle, 'سند') !== false) {
      $invoiceNoLabel = 'رقم السند';
  } elseif (mb_strpos($invoiceHeaderTitle, 'مرتجع') !== false) {
      $invoiceNoLabel = 'رقم المرتجع';
  } elseif (mb_strpos($invoiceHeaderTitle, 'شيك') !== false) {
      $invoiceNoLabel = 'رقم الشيك';
  } elseif (mb_strpos($invoiceHeaderTitle, 'كشف') !== false) {
      $invoiceNoLabel = 'كود الطرف';
  }
  $thirdHeaderLabel = '';
  $thirdHeaderValue = '';
  if ($invoiceHeaderWarehouse !== '') {
      $thirdHeaderLabel = 'المخزن';
      $thirdHeaderValue = $invoiceHeaderWarehouse;
  } elseif ($invoiceHeaderPeriod !== '') {
      $thirdHeaderLabel = 'الفترة';
      $thirdHeaderValue = $invoiceHeaderPeriod;
  } elseif ($validUntil !== '') {
      $thirdHeaderLabel = 'ساري حتى';
      $thirdHeaderValue = substr($validUntil, 0, 10);
  } elseif ($invoiceHeaderStatus !== '') {
      $thirdHeaderLabel = 'الحالة';
      $thirdHeaderValue = $invoiceHeaderStatus;
  }
  $showDocumentMeta = print_section_visible($printOptions, 'header', 'document_meta', true);
  $showCompanyBlock = print_section_visible($printOptions, 'header', 'company_block', true);
?>
<div class="print-header purchase-header">
  <div class="purchase-header-grid">
    <?php if ($showCompanyBlock): ?>
      <div class="purchase-brand-card">
        <div class="purchase-brand-wrap">
          <div class="purchase-company-copy">
            <div class="purchase-company-name"><?= e($companyName) ?></div>
            <?php if ($companySub !== ''): ?><div class="purchase-company-sub"><?= e($companySub) ?></div><?php endif; ?>
            <?php if ($companyAddress !== ''): ?><div class="purchase-company-sub"><?= e($companyAddress) ?></div><?php endif; ?>
            <?php if ($contactBits): ?><div class="purchase-company-meta"><?= e(implode(' | ', $contactBits)) ?></div><?php endif; ?>
          </div>
          <?php if ($logoUrl !== ''): ?>
            <div class="purchase-logo"><img src="<?= e($logoUrl) ?>" alt="logo"></div>
          <?php endif; ?>
        </div>
      </div>
    <?php endif; ?>
    <?php if ($showDocumentMeta): ?>
      <div class="purchase-doc-card purchase-doc-card--invoice">
        <?php if ($invoiceHeaderNo !== ''): ?>
          <div class="purchase-doc-row"><span><?= e($invoiceNoLabel) ?></span><strong><?= e($invoiceHeaderNo) ?></strong></div>
        <?php endif; ?>
        <?php if ($invoiceHeaderDate !== ''): ?>
          <div class="purchase-doc-row"><span>التاريخ</span><strong><?= e(substr($invoiceHeaderDate, 0, 10)) ?></strong></div>
        <?php endif; ?>
        <?php if ($thirdHeaderValue !== ''): ?>
          <div class="purchase-doc-row"><span><?= e($thirdHeaderLabel) ?></span><strong><?= e($thirdHeaderValue) ?></strong></div>
        <?php endif; ?>
      </div>
    <?php endif; ?>
  </div>
</div>
<?php else: ?>
<div class="print-header simple-header">
  <div class="ph-top simple-top">
    <?php foreach ($headerSections as $sectionKey => $section): if (empty($section['enabled'])) { continue; } ?>
      <?php if ($sectionKey === 'document_meta'): ?>
        <div class="ph-doc-card">
          <?php if ($docNo !== ''): ?>
            <div class="ph-doc-row">
              <span class="ph-doc-label">رقم المستند</span>
              <span class="ph-doc-value"><?= e($docNo) ?></span>
            </div>
          <?php endif; ?>
          <?php if ($docDate !== ''): ?>
            <div class="ph-doc-row">
              <span class="ph-doc-label">التاريخ</span>
              <span class="ph-doc-value"><?= e(substr($docDate, 0, 10)) ?></span>
            </div>
          <?php endif; ?>
          <?php if (!empty($printOptions['active_template_label'])): ?>
            <div class="ph-doc-row">
              <span class="ph-doc-label">القالب</span>
              <span class="ph-doc-value"><?= e((string)$printOptions['active_template_label']) ?></span>
            </div>
          <?php endif; ?>
        </div>
      <?php elseif ($sectionKey === 'company_block'): ?>
        <div class="ph-brand-card simple-brand-card">
          <div class="ph-brand">
            <?php if ($logoUrl !== ''): ?>
              <div class="ph-logo-img"><img src="<?= e($logoUrl) ?>" alt="logo"></div>
            <?php else: ?>
              <div class="ph-logo"><?= e(mb_strtoupper(mb_substr($companyName, 0, 2))) ?></div>
            <?php endif; ?>
            <div class="ph-company">
              <div class="ph-name"><?= e($companyName) ?></div>
              <?php if ($companySub !== ''): ?><div class="ph-sub"><?= e($companySub) ?></div><?php endif; ?>
              <?php if ($contactBits): ?><div class="ph-sub"><?= e(implode(' - ', $contactBits)) ?></div><?php endif; ?>
            </div>
          </div>
        </div>
      <?php endif; ?>
    <?php endforeach; ?>
  </div>

  <div class="ph-titleband simple-titleband">
    <div class="ph-title-stack simple-title-stack">
      <div class="ph-title"><?= e($title ?? '') ?></div>
      <?php if ($titleEn !== ''): ?><div class="ph-title-en"><?= e($titleEn) ?></div><?php endif; ?>
    </div>
  </div>
</div>
<?php endif; ?>
