<?php /** @var array $quotation */ /** @var array $lines */ ?>
<?php
$printOptions = is_array($print_options ?? null) ? $print_options : [];
$customerName = trim((string)($quotation['party_name'] ?? '')) ?: '-';
$customerPhone = trim((string)($quotation['party_phone'] ?? ''));
$customerEmail = trim((string)($quotation['party_email'] ?? ''));
$quotationNo = trim((string)($quotation['quotation_no'] ?? ''));
$quotationDate = (string)substr((string)($quotation['quotation_date'] ?? ''), 0, 10);
$validUntil = (string)substr((string)($quotation['valid_until'] ?? ''), 0, 10);
$subtotal = (float)($quotation['subtotal'] ?? 0);
$discountAmount = (float)($quotation['discount_amount'] ?? 0);
$taxAmount = (float)($quotation['tax_amount'] ?? 0);
$totalAmount = (float)($quotation['total_amount'] ?? 0);
$isExpired = function_exists('quotation_is_expired') ? quotation_is_expired($quotation) : false;
$paymentText = trim((string)($quotation['payment_terms'] ?? ''));
$deliveryText = trim((string)($quotation['delivery_terms'] ?? ''));
$termsText = trim((string)($quotation['terms_conditions'] ?? ''));
$notesText = trim((string)($quotation['notes'] ?? ''));
$currency = trim((string)($quotation['currency_code'] ?? ''));
$hasTotalsBreakdown = abs($subtotal) > 0.00001 || abs($discountAmount) > 0.00001 || abs($taxAmount) > 0.00001;
$showTerms = (!array_key_exists('show_terms', $printOptions) || !empty($printOptions['show_terms']))
    && print_section_visible($printOptions, 'body', 'terms', true);
$bodySections = print_sections_ordered([
  'party_block' => ['enabled' => true, 'title' => 'مقدم إلى', 'order' => 10],
  'items_table' => ['enabled' => true, 'title' => 'بنود العرض', 'order' => 20],
  'totals' => ['enabled' => true, 'title' => 'ملخص الأسعار', 'order' => 30],
  'terms' => ['enabled' => $showTerms, 'title' => 'الشروط والأحكام', 'order' => 40],
], $printOptions, 'body');
?>

<?php if ($isExpired): ?>
  <div class="quotation-expired-banner keep-together">هذا العرض منتهي الصلاحية ويُعرض كمرجع فقط.</div>
<?php endif; ?>

<?php $bottomSectionsRendered = false; ?>
<?php foreach ($bodySections as $sectionKey => $section): if (empty($section['enabled'])) { continue; } ?>
  <?php if ($sectionKey === 'party_block'): ?>
    <section class="quotation-client-strip keep-together">
      <div class="quotation-client-card">
        <div class="quotation-section-label"><?= e($section['title']) ?></div>
        <div class="quotation-client-name"><?= e($customerName) ?></div>
        <div class="quotation-client-meta">
          <?php if ($customerPhone !== ''): ?><span>الهاتف: <?= e($customerPhone) ?></span><?php endif; ?>
          <?php if ($customerEmail !== ''): ?><span>البريد: <?= e($customerEmail) ?></span><?php endif; ?>
        </div>
      </div>
      <div class="quotation-info-card">
        <div class="quotation-info-grid">
          <div><span>رقم العرض</span><strong><?= e($quotationNo !== '' ? $quotationNo : '-') ?></strong></div>
          <div><span>التاريخ</span><strong><?= e($quotationDate !== '' ? $quotationDate : '-') ?></strong></div>
          <div><span>صالح حتى</span><strong><?= e($validUntil !== '' ? $validUntil : '-') ?></strong></div>
          <div><span>العملة</span><strong><?= e($currency !== '' ? $currency : 'EGP') ?></strong></div>
        </div>
      </div>
    </section>
  <?php elseif ($sectionKey === 'items_table'): ?>
    <section class="quotation-table-section print-section">
      <div class="section-heading"><?= e($section['title']) ?></div>
      <table class="quotation-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 foreach (($lines ?? []) as $i => $ln): ?>
            <tr>
              <td class="text-center"><?= $i + 1 ?></td>
              <td><div class="quotation-item-name"><?= e((string)($ln['item_name'] ?: ('#' . ($ln['item_id'] ?? '')))) ?></div><?php if (!empty($ln['notes'])): ?><div class="quotation-item-note"><?= e((string)$ln['notes']) ?></div><?php endif; ?></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 quotation-line-total"><?= e(format_money($ln['line_total'] ?? 0)) ?></td>
            </tr>
          <?php endforeach; ?>
          <?php if (empty($lines)): ?><tr><td colspan="5" class="text-center">لا توجد بنود في عرض السعر.</td></tr><?php endif; ?>
        </tbody>
      </table>
    </section>
  <?php elseif ($sectionKey === 'terms' || $sectionKey === 'totals'): ?>
    <?php if ($bottomSectionsRendered) { continue; } $bottomSectionsRendered = true; ?>
    <?php $termsVisible = $showTerms && print_section_visible($printOptions, 'body', 'terms', true); ?>
    <?php $totalsVisible = print_section_visible($printOptions, 'body', 'totals', true); ?>
    <section class="quotation-summary-area keep-together">
      <?php if ($termsVisible): ?>
      <div class="quotation-terms-block">
        <div class="quotation-subtitle"><?= e(print_section_title($printOptions, 'body', 'terms', 'الشروط والأحكام')) ?></div>
        <ul class="quotation-terms-list">
          <?php if ($paymentText !== ''): ?><li><strong>طريقة الدفع:</strong> <?= e($paymentText) ?></li><?php endif; ?>
          <?php if ($deliveryText !== ''): ?><li><strong>مدة التوريد:</strong> <?= e($deliveryText) ?></li><?php endif; ?>
          <?php if ($validUntil !== ''): ?><li><strong>مدة الصلاحية:</strong> <?= e($validUntil) ?></li><?php endif; ?>
          <?php if ($termsText !== ''): ?><li><strong>الشروط:</strong> <?= e($termsText) ?></li><?php endif; ?>
          <?php if ($notesText !== ''): ?><li><strong>ملاحظات:</strong> <?= e($notesText) ?></li><?php endif; ?>
          <?php if ($paymentText === '' && $deliveryText === '' && $termsText === '' && $notesText === ''): ?><li>هذا العرض صالح حسب التاريخ الموضح أعلاه ويخضع للتأكيد النهائي عند الاعتماد.</li><?php endif; ?>
        </ul>
      </div>
      <?php else: ?>
      <div></div>
      <?php endif; ?>
      <?php if ($totalsVisible): ?>
      <div class="quotation-total-box">
        <div class="quotation-subtitle"><?= e(print_section_title($printOptions, 'body', 'totals', 'ملخص الأسعار')) ?></div>
        <table class="quotation-total-table">
          <?php if ($hasTotalsBreakdown): ?><tr><td>الإجمالي قبل الخصم والضريبة</td><td><?= e(format_money($subtotal)) ?></td></tr><?php endif; ?>
          <?php if (abs($discountAmount) > 0.00001): ?><tr><td>الخصم</td><td><?= e(format_money($discountAmount)) ?></td></tr><?php endif; ?>
          <?php if (abs($taxAmount) > 0.00001): ?><tr><td>الضريبة</td><td><?= e(format_money($taxAmount)) ?></td></tr><?php endif; ?>
          <tr class="is-grand"><td>الإجمالي النهائي</td><td><?= e(format_money($totalAmount)) ?></td></tr>
        </table>
      </div>
      <?php else: ?>
      <div></div>
      <?php endif; ?>
    </section>
  <?php endif; ?>
<?php endforeach; ?>
