<?php
$return = $return ?? [];
$invoice = $invoice ?? [];
$lines = $lines ?? [];
$cashboxes = $cashboxes ?? [];
$isEdit = $isEdit ?? false;
$errors = $errors ?? [];
$isCashCustomer = $isCashCustomer ?? false;
?>
<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['invoice_no'] ?? '')) ?> — العميل: <?= e((string)($invoice['customer_name'] ?? '')) ?></div>
  </div>
  <div class="d-flex gap-2">
    <a class="btn btn-outline-secondary" href="<?= e((url($sales_invoice_view_base_url ?? '/sales/invoices/view')) . '?id='.(int)($invoice['id'] ?? 0)) ?>">رجوع للفاتورة</a>
  </div>
</div>

<?php if ($errors): ?>
  <div class="alert alert-danger">
    <div class="fw-bold mb-2">يرجى مراجعة الآتي:</div>
    <ul class="mb-0">
      <?php foreach ($errors as $er): ?><li><?= e($er) ?></li><?php endforeach; ?>
    </ul>
  </div>
<?php endif; ?>

<form method="post">
  <?= csrf_field() ?>
  <div class="row g-3 mb-3">
    <div class="col-md-3">
      <label class="form-label">التاريخ</label>
      <input type="date" name="return_date" class="form-control" value="<?= e(substr((string)($return['return_date'] ?? ''),0,10)) ?>">
    </div>
    <div class="col-md-3">
      <label class="form-label">نوع التسوية</label>
      <?php if ($isCashCustomer): ?>
        <input type="hidden" name="settlement_type" value="cash_refund">
        <input class="form-control" value="رد نقدي (إجباري للعميل النقدي)" readonly>
      <?php else: ?>
        <select name="settlement_type" class="form-select" id="settlement-type">
          <option value="credit_note" <?= ($return['settlement_type'] ?? '')==='credit_note'?'selected':'' ?>>رصيد للعميل</option>
          <option value="cash_refund" <?= ($return['settlement_type'] ?? '')==='cash_refund'?'selected':'' ?>>رد نقدي</option>
        </select>
      <?php endif; ?>
    </div>
    <div class="col-md-3" id="cashbox-wrap">
      <label class="form-label">الخزنة</label>
      <select name="cashbox_id" class="form-select">
        <option value="">— اختر —</option>
        <?php foreach ($cashboxes as $cb): ?>
          <option value="<?= (int)$cb['id'] ?>" <?= (int)($return['cashbox_id'] ?? 0)===(int)$cb['id']?'selected':'' ?>><?= e((string)$cb['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="col-md-3">
      <label class="form-label">السبب</label>
      <input name="reason" class="form-control" value="<?= e((string)($return['reason'] ?? '')) ?>" placeholder="سبب المرتجع">
    </div>
    <div class="col-md-12">
      <label class="form-label">ملاحظات</label>
      <textarea name="notes" class="form-control" rows="2"><?= e((string)($return['notes'] ?? '')) ?></textarea>
    </div>
  </div>

  <div class="card mb-3">
    <div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
      <span class="fw-bold">بنود الفاتورة المتاحة للارتجاع</span>
      <button type="button" class="btn btn-sm btn-outline-primary" id="fill-max-qty">ملء الكميات الأصلية المتاحة</button>
    </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>#</th>
              <th>الصنف</th>
              <th class="text-center">المباع</th>
              <th class="text-center">مرتجع سابق</th>
              <th class="text-center">المتاح</th>
              <th class="text-center">كمية المرتجع الآن</th>
              <th class="text-center">السعر</th>
              <th class="text-center">الإجمالي</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($lines as $i => $ln): ?>
              <tr>
                <td><?= $i+1 ?></td>
                <td>
                  <?= e((string)$ln['item_name']) ?>
                </td>
                <td class="text-center"><?= e(format_qty((float)$ln['sold_qty'])) ?></td>
                <td class="text-center"><?= e(format_qty((float)$ln['returned_qty'])) ?></td>
                <td class="text-center"><?= e(format_qty((float)$ln['max_qty'])) ?></td>
                <td>
                  <input type="number" min="0" step="0.01" max="<?= e((string)$ln['max_qty']) ?>" data-max-qty="<?= e((string)$ln['max_qty']) ?>" name="qty[]" value="<?= e((string)$ln['qty']) ?>" class="form-control text-center ret-qty">
                </td>
                <td>
                  <input type="number" min="0" step="0.01" name="unit_price[]" value="<?= e((string)$ln['unit_price']) ?>" class="form-control text-center ret-price">
                </td>
                <td class="text-center ret-line-total"><?= e(format_money((float)$ln['qty'] * (float)$ln['unit_price'])) ?></td>
              </tr>
            <?php endforeach; ?>
            <?php if (!$lines): ?>
              <tr><td colspan="8" class="text-center text-muted py-4">لا توجد بنود</td></tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <div class="card mb-3">
    <div class="card-body d-flex justify-content-between align-items-center flex-wrap gap-3">
      <div class="text-muted">للعميل النقدي يكون رد القيمة من الخزنة إلزاميًا.</div>
      <div class="fw-bold fs-5">الإجمالي: <span id="ret-total"><?= e(format_money((float)($return['total_amount'] ?? 0))) ?></span></div>
    </div>
  </div>

  <div class="d-flex gap-2">
    <button class="btn btn-primary">حفظ كمسودة</button>
    <a class="btn btn-outline-secondary" href="<?= e((url($sales_invoice_view_base_url ?? '/sales/invoices/view')) . '?id='.(int)($invoice['id'] ?? 0)) ?>">إلغاء</a>
  </div>
</form>

<script>
(function(){
  function updateTotals(){
    let total = 0;
    document.querySelectorAll('tbody tr').forEach(function(row){
      const qty = parseFloat(row.querySelector('.ret-qty')?.value || '0') || 0;
      const price = parseFloat(row.querySelector('.ret-price')?.value || '0') || 0;
      const line = qty * price;
      const td = row.querySelector('.ret-line-total');
      if(td) td.textContent = line.toFixed(2);
      total += line;
    });
    const out = document.getElementById('ret-total');
    if (out) out.textContent = total.toFixed(2);
  }
  document.querySelectorAll('.ret-qty,.ret-price').forEach(el => el.addEventListener('input', updateTotals));
  const sel = document.getElementById('settlement-type');
  const wrap = document.getElementById('cashbox-wrap');
  function toggleCashbox(){
    if (!sel || !wrap) return;
    wrap.style.display = sel.value === 'cash_refund' ? '' : 'none';
  }
  if (sel) { sel.addEventListener('change', toggleCashbox); toggleCashbox(); }

  const fillBtn = document.getElementById('fill-max-qty');
  if (fillBtn) {
    fillBtn.addEventListener('click', function(){
      document.querySelectorAll('.ret-qty').forEach(function(input){
        input.value = input.dataset.maxQty || input.getAttribute('max') || '0';
      });
      updateTotals();
    });
  }

  updateTotals();
})();
</script>
