<?php
$return = $return ?? [];
$lines = $lines ?? [];
$invoice = $invoice ?? null;
$isEdit = (bool)($isEdit ?? false);
$return_id = (int)($return_id ?? 0);
if (!$invoice) return;
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h4 class="mb-1"><?= $isEdit ? 'تعديل مرتجع شراء (مسودة)' : 'مرتجع شراء جديد' ?></h4>
    <div class="text-muted small">المصدر: فاتورة شراء <?= e((string)$invoice['inv_no']) ?> — المورد: <?= e((string)$invoice['supplier_name']) ?> — المخزن: <?= e((string)$invoice['warehouse_name']) ?></div>
  </div>
  <div class="d-flex gap-2">
    <a class="btn btn-outline-secondary" href="<?= e($purchase_invoice_view_url ?? url('/purchases/invoices/view?id='.(int)$invoice['id'])) ?>"><i class="fa-solid fa-arrow-right me-1"></i>رجوع</a>
  </div>
</div>

<form method="post">
  <?= csrf_field() ?>
  <div class="card mb-3">
    <div class="card-body">
      <div class="row g-3">
        <div class="col-md-3">
          <label class="form-label">تاريخ المرتجع</label>
          <input type="date" name="ret_date" class="form-control" value="<?= e(substr((string)($return['ret_date'] ?? date('Y-m-d')),0,10)) ?>" required>
        </div>
        <div class="col-md-9">
          <label class="form-label">ملاحظات</label>
          <input name="notes" class="form-control" value="<?= e((string)($return['notes'] ?? '')) ?>" placeholder="اختياري">
        </div>
      </div>
    </div>
  </div>

  <div class="card mb-3">
    <div class="card-header fw-bold">بنود المرتجع</div>
    <div class="card-body p-0">
      <div class="table-responsive">
        <table class="table table-bordered align-middle mb-0">
          <thead class="table-light">
            <tr>
              <th style="width:50px">م</th>
              <th>الصنف</th>
              <th style="width:140px">الوحدة</th>
              <th style="width:120px">المتاح للمرتجع</th>
              <th style="width:140px">كمية المرتجع</th>
              <th style="width:140px">السعر</th>
              <th style="width:140px">الإجمالي</th>
            </tr>
          </thead>
          <tbody id="rBody">
            <?php $i=1; foreach ($lines as $ln): ?>
              <tr>
                <td class="text-center"><?= $i++ ?></td>
                <td><?= e((string)$ln['item_name']) ?></td>
                <td class="text-center"><?= e((string)($ln['unit_name'] ?? '')) ?></td>
                <td class="text-center"><?= e(format_qty((float)($ln['max_qty'] ?? 0))) ?></td>

                <td>
                  <input type="hidden" name="item_id[]" value="<?= (int)$ln['item_id'] ?>">
                  <input type="hidden" name="unit_id[]" value="<?= (int)($ln['unit_id'] ?? 0) ?>">
                  <input type="hidden" name="max_qty[]" value="<?= e((string)($ln['max_qty'] ?? 0)) ?>">
                  <input type="number" step="0.001" min="0" max="<?= e((string)($ln['max_qty'] ?? 0)) ?>" name="qty[]" class="form-control qty" value="<?= e((string)($ln['qty'] ?? 0)) ?>">
                </td>

                <td>
                  <input type="number" step="0.01" min="0" name="unit_price[]" class="form-control price" value="<?= e((string)($ln['unit_price'] ?? 0)) ?>">
                </td>

                <td class="text-center">
                  <span class="line-total">0.00</span>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
          <tfoot class="table-light">
            <tr>
              <th colspan="6" class="text-end">الإجمالي</th>
              <th class="text-center"><span id="rtotal">0.00</span></th>
            </tr>
          </tfoot>
        </table>
      </div>
    </div>
  </div>

  <div class="d-flex justify-content-end gap-2">
    <button class="btn btn-success px-4"><i class="fa-solid fa-floppy-disk me-1"></i>حفظ كمسودة</button>
    <?php if ($isEdit): ?>
      <a class="btn btn-outline-secondary" href="<?= e($purchase_return_view_url ?? url('/purchases/returns/view?id=' . $return_id)) ?>">عرض المرتجع</a>
    <?php endif; ?>
  </div>
</form>

<script>
(function(){
  const body = document.getElementById('rBody');
  function recalc(){
    let total=0;
    [...body.querySelectorAll('tr')].forEach(tr=>{
      const qty = parseFloat(tr.querySelector('.qty').value||'0')||0;
      const price = parseFloat(tr.querySelector('.price').value||'0')||0;
      const lt = qty*price;
      total += lt;
      tr.querySelector('.line-total').textContent = lt.toFixed(2);
    });
    document.getElementById('rtotal').textContent = total.toFixed(2);
  }
  body.addEventListener('input', recalc);
  recalc();
})();
</script>
