<?php
// view: pages/stock/wh_doc_view
$doc = $doc ?? null;
$lines = $lines ?? [];
if (!$doc) return;
?>

<div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3">
  <div>
    <h4 class="mb-1"><?= e($doc['doc_no']) ?> <span class="text-muted">—</span> <span class="text-muted"><?= e(doc_type_label($doc['doc_type'])) ?></span></h4>
    <div class="text-muted small">
      التاريخ: <?= e(substr((string)$doc['doc_date'],0,16)) ?>
      <span class="mx-2">•</span>
      من مخزن: <?= e($doc['warehouse_name']) ?>
      <?php if (!empty($doc['to_warehouse_name'])): ?>
        <span class="mx-2">•</span>
        إلى مخزن: <?= e($doc['to_warehouse_name']) ?>
      <?php endif; ?>
      <span class="mx-2">•</span>
      الحالة: <?= e(($doc['status']==='POSTED')?'مرحل':$doc['status']) ?>
    </div>
    <?php if (!empty($doc['notes'])): ?>
      <div class="mt-2">ملاحظات: <?= e($doc['notes']) ?></div>
    <?php endif; ?>
  </div>

  <div class="d-flex gap-2">
    <a class="btn btn-outline-secondary" href="<?= e(url($routeContext['index'])) ?>">رجوع</a>
    <?php if (($doc['status'] ?? '') === 'POSTED'): ?>
      <a class="btn btn-success" target="_blank" href="<?= e(url(($routeContext['print'])((int)$doc['id']))) ?>">
        <i class="fa-solid fa-print ms-1"></i> طباعة
      </a>
    <?php endif; ?>
  </div>
</div>

<div class="card p-3">
  <div class="table-responsive">
    <table class="table table-bordered table-striped table-hover align-middle table-sm mb-0">
      <thead class="table-light">
        <tr>
          <th style="width:60px">#</th>
          <th>الصنف</th>
          <th style="width:140px">الوحدة</th>
          <th class="text-end" style="width:140px">الكمية</th>
          <th class="text-end" style="width:140px">التكلفة</th>
          <th class="text-end" style="width:160px">الإجمالي</th>
        </tr>
      </thead>
      <tbody>
        <?php $sum=0; foreach ($lines as $idx=>$ln): $lineTotal = ((float)$ln['qty'])*((float)$ln['unit_cost']); $sum+=$lineTotal; ?>
          <tr>
            <td><?= (int)($idx+1) ?></td>
            <td><?= e($ln['item_name']) ?></td>
            <td><?= e(($ln['unit_name'] ?? '') !== '' ? ($ln['unit_name'] . (isset($ln['unit_symbol']) && $ln['unit_symbol'] ? ' (' . $ln['unit_symbol'] . ')' : '')) : '-') ?></td>
            <td class="text-end"><?= format_qty($ln['qty']) ?></td>
            <td class="text-end"><?= format_money($ln['unit_cost']) ?></td>
            <td class="text-end"><?= format_money($lineTotal) ?></td>
          </tr>
        <?php endforeach; ?>
        <?php if (!$lines): ?>
          <tr><td colspan="6" class="text-center text-muted py-4">لا توجد بنود</td></tr>
        <?php endif; ?>
      </tbody>
      <tfoot>
        <tr>
          <th colspan="5" class="text-end">إجمالي قيمة البنود</th>
          <th class="text-end"><?= format_money($sum) ?></th>
        </tr>
      </tfoot>
    </table>
  </div>
</div>
