<?php
// view: pages/purchases/invoice_form
$invoice = $invoice ?? [];
$lines = $lines ?? [];
$warehouses = $warehouses ?? [];
$units = $units ?? [];
$supplier = $supplier ?? null;
$isEdit = (bool)($isEdit ?? false);
$id = (int)($id ?? 0);

$supplier_id = (int)($invoice['party_id'] ?? 0); // party_id (supplier)
$supplier_query = (string)($invoice['supplier_label'] ?? ($supplier ? ($supplier['name'] . ' (' . $supplier['code'] . ')') : ''));

function sel($a,$b){ return ((string)$a === (string)$b) ? 'selected' : ''; }
?>
<style>
  #purchaseForm .card,
  #purchaseForm .card-body,
  #purchaseForm .purchase-lines-wrap,
  #purchaseForm .purchase-lines-wrap .table-responsive,
  #purchaseForm .purchase-lines-wrap .table,
  #purchaseForm .purchase-lines-wrap td,
  #purchaseForm .purchase-lines-wrap th { overflow: visible !important; }
  #purchaseForm .position-relative { overflow: visible !important; }
  #purchaseForm .item-box {
    z-index: 2000 !important;
    background: #fff;
  }
</style>
<div class="page-actions-bar">
  <a class="btn btn-outline-secondary btn-back" data-shortcut="back" href="<?= e($purchase_invoices_url ?? url('/purchases/invoices')) ?>"><i class="fa-solid fa-arrow-right me-1"></i>رجوع</a>
</div>

<form method="post" class="needs-validation" novalidate id="purchaseForm">
  <?= csrf_field() ?>
  <input type="hidden" name="save_action" id="save_action" value="draft">
  <div class="card mb-3">
    <div class="card-body">
      <div class="row g-3">
        <div class="col-md-5 position-relative">
          <label class="form-label">الطرف / المورد</label>
          <input type="hidden" name="party_id" id="party_id" value="<?= (int)$supplier_id ?>">
          <input type="text" class="form-control" id="supplier_query" value="<?= e($supplier_query) ?>" placeholder="اكتب اسم المورد / كود..." autocomplete="off" required>
          <div id="supplier_box" class="list-group position-absolute w-100 shadow-sm" style="z-index:50; display:none; max-height: 240px; overflow:auto;"></div>
        </div>

        <div class="col-md-3">
          <label class="form-label">المخزن</label>
          <select name="warehouse_id" class="form-select" required>
            <?php foreach ($warehouses as $w): ?>
              <option value="<?= (int)$w['id'] ?>" <?= sel((int)$invoice['warehouse_id'], (int)$w['id']) ?>><?= e((string)$w['name']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="col-md-2">
          <label class="form-label">تاريخ الفاتورة</label>
          <input type="date" name="inv_date" class="form-control" value="<?= e(substr((string)$invoice['inv_date'],0,10)) ?>" required>
        </div>

        <div class="col-md-2">
          <label class="form-label">حالة</label>
          <input class="form-control" value="DRAFT" disabled>
        </div>

        <div class="col-12">
          <label class="form-label">ملاحظات</label>
          <input name="notes" class="form-control" value="<?= e((string)($invoice['notes'] ?? '')) ?>" placeholder="اختياري">
        </div>
      </div>
    </div>
  </div>

  <div class="card mb-3 purchase-lines-wrap">
    <div class="card-header d-flex justify-content-between align-items-center">
      <div class="fw-bold">بنود الفاتورة</div>
      <button type="button" id="addLine" class="btn btn-sm btn-outline-primary" data-shortcut="add-line"><i class="fa-solid fa-plus me-1"></i>إضافة سطر</button>
    </div>
    <div class="card-body p-0">
      <div class="table-responsive">
        <table class="table table-bordered align-middle mb-0" id="linesTable">
          <thead class="table-light">
            <tr>
              <th style="width:50px">م</th>
              <th style="width:250px">الصنف</th>
              <th style="width:160px">الوحدة</th>
              <th style="width:130px">الكمية</th>
              <th style="width:160px">سعر الشراء</th>
              <th style="width:160px">الإجمالي</th>
              <th style="width:50px"></th>
            </tr>
          </thead>
          <tbody id="linesBody">
            <?php if (!$lines): ?>
              <?php $lines = [[ 'item_id'=>0,'unit_id'=>0,'qty'=>1,'unit_price'=>0,'line_total'=>0 ]]; ?>
            <?php endif; ?>

            <?php $n=1; foreach ($lines as $ln): ?>
              <tr>
                <td class="text-center line-no"><?= $n++ ?></td>
                <td class="position-relative">
                  <input type="hidden" name="item_id[]" class="item-id" value="<?= (int)$ln['item_id'] ?>">
                  <?php
                    $itemName = '';
                    if ((int)$ln['item_id']>0) {
                      // Best-effort: controller already joined name when edit; fallback
                      $itemName = (string)($ln['item_name'] ?? '');
                    }
                  ?>
                  <input type="text" name="item_name[]" class="form-control item-query" value="<?= e((string)$itemName) ?>" placeholder="اكتب اسم/باركود..." autocomplete="off">
                  <div class="list-group position-absolute w-100 shadow-sm item-box" style="z-index:40; display:none; max-height: 240px; overflow:auto;"></div>
                </td>
                <td>
                  <select name="unit_id[]" class="form-select unit-id">
                    <option value="">—</option>
                    <?php foreach ($units as $u): ?>
                      <option value="<?= (int)$u['id'] ?>" <?= sel((int)($ln['unit_id'] ?? 0), (int)$u['id']) ?>><?= e((string)$u['name']) ?></option>
                    <?php endforeach; ?>
                  </select>
                </td>
                <td><input type="number" step="0.001" min="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"><?= e(format_money((float)($ln['line_total'] ?? 0))) ?></span></td>
                <td class="text-center">
                  <button type="button" class="btn btn-sm btn-outline-danger removeLine" title="حذف"><i class="fa-solid fa-xmark"></i></button>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
          <tfoot class="table-light">
            <tr>
              <th colspan="5" class="text-end">الإجمالي قبل الخصم</th>
              <th class="text-center"><span id="subtotal">0.00</span></th>
              <th></th>
            </tr>
          </tfoot>
        </table>
      </div>
    </div>
  </div>

  <div class="row g-3">
    <div class="col-md-4">
      <div class="card h-100">
        <div class="card-header fw-bold">السداد</div>
        <div class="card-body">
          <div class="row g-2">
            <div class="col-md-4">
              <label class="form-label">نوع السداد</label>
              <select name="payment_mode" id="payment_mode" class="form-select">
                <option value="cash" <?= sel((string)($invoice['payment_mode'] ?? 'credit'), 'cash') ?>>نقدي</option>
                <option value="credit" <?= sel((string)($invoice['payment_mode'] ?? 'credit'), 'credit') ?>>آجل</option>
                <option value="partial" <?= sel((string)($invoice['payment_mode'] ?? 'credit'), 'partial') ?>>جزئي</option>
              </select>
            </div>
            <div class="col-md-4" id="paid_amount_group">
              <label class="form-label">المدفوع الآن</label>
              <input type="number" step="0.01" min="0" name="paid_amount" id="paid_amount" class="form-control" value="<?= e((string)($invoice['paid_amount'] ?? 0)) ?>">
            </div>
            <div class="col-md-4" id="cashbox_group">
              <label class="form-label">الخزنة</label>
              <select name="cashbox_id" id="cashbox_id" class="form-select">
                <option value="0">-- بدون --</option>
                <?php foreach (($cashboxes ?? []) as $cb): ?>
                  <option value="<?= (int)$cb['id'] ?>" <?= ((int)($invoice['cashbox_id'] ?? 0)===(int)$cb['id'])?'selected':'' ?>><?= e((string)$cb['name']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-12">
              <label class="form-label">ملاحظة السداد</label>
              <input type="text" name="payment_note" id="payment_note" class="form-control" value="<?= e((string)($invoice['payment_note'] ?? '')) ?>" placeholder="تظهر في قيد السداد وحركة الخزنة">
            </div>
            <div class="col-12 small text-muted">
              النقدي = كامل الفاتورة، الآجل = بدون سداد الآن، الجزئي = جزء يتم صرفه من الخزنة والباقي مستحق للمورد.
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="col-md-4">
      <div class="card">
        <div class="card-header fw-bold">الخصم والضرائب</div>
        <div class="card-body">
          <!-- 1) خصم اختياري -->
          <div class="border rounded p-2 mb-2">
            <div class="fw-bold mb-2">خصم اختياري</div>
            <div class="row g-2 align-items-end">
              <div class="col-md-4">
                <label class="form-label">نوع الخصم</label>
                <select name="discount_type" class="form-select" id="discount_type">
                  <option value="PERCENT" <?= sel(strtoupper((string)($invoice['discount_type'] ?? 'PERCENT')), 'PERCENT') ?>>%</option>
                  <option value="AMOUNT" <?= sel(strtoupper((string)($invoice['discount_type'] ?? 'PERCENT')), 'AMOUNT') ?>>مبلغ</option>
                </select>
              </div>
              <div class="col-md-4">
                <label class="form-label">قيمة الخصم</label>
                <input type="number" step="0.01" min="0" name="discount_value" id="discount_value" class="form-control" value="<?= e((string)($invoice['discount_value'] ?? 0)) ?>">
              </div>
              <div class="col-md-4">
                <label class="form-label">ملاحظة الخصم</label>
                <input name="discount_note" class="form-control" value="<?= e((string)($invoice['discount_note'] ?? '')) ?>" placeholder="اختياري">
              </div>
            </div>
          </div>

          <!-- 2) ض.ق.مضافة (VAT) -->
          <div class="border rounded p-2 mb-2">
            <div class="d-flex justify-content-between align-items-center mb-2">
              <div class="fw-bold">ض.ق.مضافة</div>
              <div class="form-check m-0">
                <input class="form-check-input" type="checkbox" name="tax_enabled" id="tax_enabled" <?= ((int)($invoice['tax_enabled'] ?? 0)===1)?'checked':'' ?>>
                <label class="form-check-label" for="tax_enabled">تفعيل</label>
              </div>
            </div>

            <div class="row g-2 align-items-end">
              <div class="col-md-4" id="tax_rate_wrap" style="display:none;">
                <label class="form-label">نسبة الضريبة %</label>
                <input type="number" step="0.01" min="0" name="tax_rate" id="tax_rate" class="form-control" value="<?= e((string)($invoice['tax_rate'] ?? 14)) ?>">
                <input type="hidden" name="tax_amount" id="tax_amount_hidden" value="<?= e((string)($invoice['tax_amount'] ?? 0)) ?>">
              </div>
              <div class="col-md-8">
                <label class="form-label">رقم الفاتورة الضريبية</label>
                <input name="tax_invoice_no" class="form-control" value="<?= e((string)($invoice['tax_invoice_no'] ?? '')) ?>" placeholder="اختياري">
              </div>
            </div>
          </div>

          <!-- 3) ضريبة ص/ت (1% أو 3%) -->
          <div class="border rounded p-2">
            <div class="d-flex justify-content-between align-items-center mb-2">
              <div class="fw-bold">ضريبة ص/ت</div>
              <div class="form-check m-0">
                <input class="form-check-input" type="checkbox" name="wht_enabled" id="wht_enabled" <?= ((int)($invoice['wht_enabled'] ?? 0)===1)?'checked':'' ?>>
                <label class="form-check-label" for="wht_enabled">تفعيل</label>
              </div>
            </div>
            <div class="row g-2 align-items-end">
              <div class="col-md-4">
                <label class="form-label">النسبة</label>
                <select name="wht_rate" id="wht_rate" class="form-select">
                  <option value="1" <?= sel((string)($invoice['wht_rate'] ?? '1'), '1') ?>>1%</option>
                  <option value="3" <?= sel((string)($invoice['wht_rate'] ?? '1'), '3') ?>>3%</option>
                </select>
              </div>
              <div class="col-md-4">
                <label class="form-label">رقم إشعار الخصم</label>
                <input type="text" name="wht_notice_no" id="wht_notice_no" class="form-control" value="<?= e((string)($invoice['wht_notice_no'] ?? '')) ?>" placeholder="اختياري">
                <input type="hidden" name="wht_amount" id="wht_amount_manual" value="<?= e((string)($invoice['wht_amount'] ?? 0)) ?>">
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="col-md-4">
      <div class="card h-100">
        <div class="card-header fw-bold">مصاريف إضافية وإجماليات</div>
        <div class="card-body">
          <div class="row g-2">
            <div class="col-md-4">
              <label class="form-label">القيمة</label>
              <input type="number" step="0.01" min="0" name="extra_charges" id="extra_charges" class="form-control" value="<?= e((string)($invoice['extra_charges'] ?? 0)) ?>">
            </div>
            <div class="col-md-8">
              <label class="form-label">ملاحظة</label>
              <input name="charges_note" class="form-control" value="<?= e((string)($invoice['charges_note'] ?? '')) ?>" placeholder="اختياري">
            </div>

            <div class="col-12">
              <div class="alert alert-light mb-0">
                <div class="d-flex justify-content-between">
                  <span>قيمة الخصم</span>
                  <strong id="discount_amount">0.00</strong>
                </div>
                <div class="d-flex justify-content-between">
                  <span>ض.ق.مضافة</span>
                  <strong id="tax_amount">0.00</strong>
                </div>
                <div class="d-flex justify-content-between">
                  <span>ضريبة ص/ت</span>
                  <strong id="wht_amount">0.00</strong>
                </div>
                <div class="d-flex justify-content-between">
                  <span>الصافي</span>
                  <strong id="net_total">0.00</strong>
                </div>
                <div class="d-flex justify-content-between">
                  <span>المدفوع الآن</span>
                  <strong id="paid_preview">0.00</strong>
                </div>
                <div class="d-flex justify-content-between">
                  <span>المتبقي</span>
                  <strong id="due_preview">0.00</strong>
                </div>
              </div>
            </div>

          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="d-flex justify-content-end gap-2 mt-3">
    <button type="submit" class="btn btn-success px-4" onclick="document.getElementById('save_action').value='draft'">
      <i class="fa-solid fa-floppy-disk me-1"></i>حفظ كمسودة
    </button>
    <button type="submit" class="btn btn-primary px-4" onclick="document.getElementById('save_action').value='post'">
      <i class="fa-solid fa-circle-check me-1"></i>حفظ وترحيل
    </button>
    <?php if ($isEdit): ?>
      <a class="btn btn-outline-secondary" href="<?= e($purchase_invoice_view_url ?? url('/purchases/invoices/view?id=' . $id)) ?>">عرض الفاتورة</a>
    <?php endif; ?>
  </div>
</form>

<script>
(function(){
  const ajaxPartySearchUrl = <?= json_encode(url('/ajax/parties/search')) ?>;
  const ajaxItemSearchUrl = <?= json_encode(url('/ajax/items/search')) ?>;
  const ajaxItemInfoUrl = <?= json_encode(url('/ajax/items/info')) ?>;
  const supQ = document.getElementById('supplier_query');
  const supId = document.getElementById('party_id');
  const supBox = document.getElementById('supplier_box');
  const form = document.getElementById('purchaseForm');
  let st = null;

  function hideSup(){ supBox.style.display='none'; supBox.innerHTML=''; }
  function showSup(){ supBox.style.display='block'; }

  supQ.addEventListener('input', () => {
    clearTimeout(st);
    const val = supQ.value.trim();
    if (!supQ.dataset.selectedLabel || supQ.dataset.selectedLabel !== val) supId.value = '';
    if (val.length < 1) { hideSup(); return; }
    st = setTimeout(async () => {
      try {
        const res = await fetch(ajaxPartySearchUrl + '?type=supplier&q=' + encodeURIComponent(val));
        const items = await res.json();
        if (!items || !items.length) { hideSup(); return; }
        supBox.innerHTML = items.map(it => `
          <button type="button" class="list-group-item list-group-item-action" data-id="${it.id}" data-label="${it.name} (${it.code || ''})">
            <div class="fw-bold">${it.name}</div>
            <div class="small text-muted">${it.code || ''}</div>
          </button>`).join('');
        showSup();
      } catch(e){ hideSup(); }
    }, 200);
  });

  supBox.addEventListener('click', (e) => {
    const btn = e.target.closest('button[data-id]');
    if(!btn) return;
    supId.value = btn.getAttribute('data-id');
    supQ.value = btn.getAttribute('data-label');
    supQ.dataset.selectedLabel = supQ.value;
    hideSup();
  });

  document.addEventListener('click', (e) => {
    if (!supBox.contains(e.target) && e.target !== supQ) hideSup();
  });

  const tbody = document.getElementById('linesBody');
  const addBtn = document.getElementById('addLine');

  function renumber(){
    [...tbody.querySelectorAll('tr')].forEach((tr, idx) => {
      tr.querySelector('.line-no').textContent = (idx+1);
    });
  }

  function getSelectedItemIds(exceptRow = null){
    return Array.from(tbody.querySelectorAll('tr')).filter(r => r !== exceptRow).map(r => Number(r.querySelector('.item-id')?.value || 0)).filter(Boolean);
  }

  function recalc(){
    let subtotal = 0;
    [...tbody.querySelectorAll('tr')].forEach(tr => {
      const qty = parseFloat(tr.querySelector('.qty').value || '0') || 0;
      const price = parseFloat(tr.querySelector('.price').value || '0') || 0;
      const total = qty * price;
      subtotal += total;
      tr.querySelector('.line-total').textContent = total.toFixed(2);
    });
    document.getElementById('subtotal').textContent = subtotal.toFixed(2);

    const dtype = (document.getElementById('discount_type').value || 'PERCENT').toUpperCase();
    const dval = parseFloat(document.getElementById('discount_value').value || '0') || 0;
    let disc = 0;
    if (dtype === 'PERCENT') disc = subtotal * (dval/100);
    else disc = dval;
    if (disc > subtotal) disc = subtotal;

    const net = subtotal - disc;
    const vatEnabled = document.getElementById('tax_enabled').checked;
    const vatRate = parseFloat((document.getElementById('tax_rate')||{}).value || '0') || 0;
    const vat = vatEnabled ? Math.max(0, net * (vatRate/100)) : 0;
    const vatHidden = document.getElementById('tax_amount_hidden');
    if (vatHidden) vatHidden.value = vat.toFixed(2);

    const whtEnabled = document.getElementById('wht_enabled').checked;
    const whtRate = parseFloat((document.getElementById('wht_rate')||{}).value || '0') || 0;
    let wht = 0;
    if (whtEnabled) {
      wht = net * (whtRate/100);
      if (wht < 0) wht = 0;
    }
    const whtHidden = document.getElementById('wht_amount_manual');
    if (whtHidden) whtHidden.value = wht.toFixed(2);

    const extra = parseFloat(document.getElementById('extra_charges').value || '0') || 0;
    const grand = net + (extra>0?extra:0) + vat - wht;

    const paymentMode = (document.getElementById('payment_mode')?.value || 'credit').toLowerCase();
    const paidInput = document.getElementById('paid_amount');
    const paidGroup = document.getElementById('paid_amount_group');
    const cashbox = document.getElementById('cashbox_id');
    const cashboxGroup = document.getElementById('cashbox_group');
    const custodyGroup = document.getElementById('custody_group');
    let paid = parseFloat(paidInput?.value || '0') || 0;
    if (paymentMode === 'cash') {
      if (cashboxGroup) cashboxGroup.classList.remove('d-none');
      if (custodyGroup) custodyGroup.classList.add('d-none');
      paid = grand;
      if (paidInput) {
        paidInput.value = paid.toFixed(2);
        paidInput.readOnly = true;
        paidInput.setAttribute('tabindex', '-1');
      }
      if (paidGroup) paidGroup.classList.add('d-none');
      if (cashbox && Number(cashbox.value||0)===0 && cashbox.options.length>1) cashbox.selectedIndex = 1;
    } else if (paymentMode === 'credit') {
      if (cashboxGroup) cashboxGroup.classList.remove('d-none');
      if (custodyGroup) custodyGroup.classList.add('d-none');
      paid = 0;
      if (paidInput) {
        paidInput.value = paid.toFixed(2);
        paidInput.readOnly = true;
        paidInput.setAttribute('tabindex', '-1');
      }
      if (paidGroup) paidGroup.classList.add('d-none');
    } else if (paymentMode === 'custody') {
      if (cashboxGroup) cashboxGroup.classList.add('d-none');
      if (custodyGroup) custodyGroup.classList.remove('d-none');
      paid = grand;
      if (paidInput) { paidInput.value = paid.toFixed(2); paidInput.readOnly = true; paidInput.setAttribute('tabindex','-1'); }
      if (paidGroup) paidGroup.classList.add('d-none');
    } else {
      if (cashboxGroup) cashboxGroup.classList.remove('d-none');
      if (custodyGroup) custodyGroup.classList.add('d-none');
      if (paidGroup) paidGroup.classList.remove('d-none');
      if (paidInput) {
        paidInput.readOnly = false;
        paidInput.disabled = false;
        paidInput.removeAttribute('readonly');
        paidInput.removeAttribute('disabled');
        paidInput.removeAttribute('tabindex');
        paidInput.style.pointerEvents = '';
      }
      if (paid < 0) {
        paid = 0;
        if (paidInput) paidInput.value = paid.toFixed(2);
      }
    }
    const due = Math.max(0, grand - paid);

    document.getElementById('discount_amount').textContent = disc.toFixed(2);
    document.getElementById('tax_amount').textContent = vat.toFixed(2);
    const whtEl = document.getElementById('wht_amount');
    if (whtEl) whtEl.textContent = wht.toFixed(2);
    document.getElementById('net_total').textContent = grand.toFixed(2);
    document.getElementById('paid_preview').textContent = paid.toFixed(2);
    document.getElementById('due_preview').textContent = due.toFixed(2);

    const taxRateWrap = document.getElementById('tax_rate_wrap');
    if (taxRateWrap) taxRateWrap.style.display = vatEnabled ? '' : 'none';
  }

  document.addEventListener('keydown', (e) => {
    if (e.key === 'F2') {
      e.preventDefault();
      addBtn?.click();
    }
  });

  function hideItemBox(box){ box.style.display='none'; box.innerHTML=''; }

  function bindRow(tr){
    const q = tr.querySelector('.item-query');
    const hid = tr.querySelector('.item-id');
    const box = tr.querySelector('.item-box');
    if (hid && Number(hid.value||0) > 0 && q.value.trim()) q.dataset.selectedLabel = q.value.trim();

    q.addEventListener('input', () => {
      const val = q.value.trim();
      if (!q.dataset.selectedLabel || q.dataset.selectedLabel !== val) hid.value = '';
      if (val.length < 1) { hideItemBox(box); return; }
      clearTimeout(q._t);
      q._t = setTimeout(async () => {
        try {
          const res = await fetch(ajaxItemSearchUrl + '?q=' + encodeURIComponent(val));
          const items = await res.json();
          if (!items || !items.length) { hideItemBox(box); return; }
          box.innerHTML = items.map(it => `
            <button type="button" class="list-group-item list-group-item-action" data-id="${it.id}">
              <div class="fw-bold">${it.name}</div>
              <div class="small text-muted">${it.barcode || ''}</div>
            </button>`).join('');
          box.style.display='block';
        } catch(err){ hideItemBox(box); }
      }, 180);
    });

    q.addEventListener('change', ()=>{ if ((q.value||'').trim() === '') hid.value=''; });
    tr.querySelectorAll('.qty,.price').forEach(inp=> inp.addEventListener('input', recalc));
  }

  function newRow(){
    const tr = document.createElement('tr');
    tr.innerHTML = `
      <td class="text-center line-no"></td>
      <td class="position-relative">
        <input type="hidden" name="item_id[]" class="item-id" value="">
        <input type="text" name="item_name[]" class="form-control item-query" value="" placeholder="اكتب اسم/باركود..." autocomplete="off">
        <div class="list-group position-absolute w-100 shadow-sm item-box" style="z-index:40; display:none; max-height: 240px; overflow:auto;"></div>
      </td>
      <td>
        <select name="unit_id[]" class="form-select unit-id">
          <option value="">—</option>
          <?php foreach ($units as $u): ?>
            <option value="<?= (int)$u['id'] ?>"><?= e((string)$u['name']) ?></option>
          <?php endforeach; ?>
        </select>
      </td>
      <td><input type="number" step="0.001" min="0" name="qty[]" class="form-control qty" value="1"></td>
      <td><input type="number" step="0.01" min="0" name="unit_price[]" class="form-control price" value="0"></td>
      <td class="text-center"><span class="line-total">0.00</span></td>
      <td class="text-center">
        <button type="button" class="btn btn-sm btn-outline-danger removeLine" title="حذف"><i class="fa-solid fa-xmark"></i></button>
      </td>
    `;
    tbody.appendChild(tr);
    bindRow(tr);
    renumber();
    recalc();
    tr.querySelector('.item-query')?.focus();
  }

  addBtn.addEventListener('click', newRow);

  tbody.addEventListener('click', async (e) => {
    const rm = e.target.closest('.removeLine');
    if (rm) {
      const tr = rm.closest('tr');
      tr.remove();
      if (!tbody.querySelector('tr')) newRow();
      renumber();
      recalc();
      return;
    }

    const btn = e.target.closest('.item-box button[data-id]');
    if (!btn) return;
    const tr = btn.closest('tr');
    const box = tr.querySelector('.item-box');
    const q = tr.querySelector('.item-query');
    const hid = tr.querySelector('.item-id');
    const id = Number(btn.getAttribute('data-id') || 0);
    if (getSelectedItemIds(tr).includes(id)) {
      alert('هذا الصنف موجود بالفعل داخل الفاتورة. عدّل الكمية في السطر الحالي بدل تكراره.');
      hideItemBox(box);
      q.focus();
      return;
    }
    hid.value = String(id);
    q.value = btn.querySelector('.fw-bold').textContent.trim();
    q.dataset.selectedLabel = q.value;
    hideItemBox(box);

    try{
      const res = await fetch(ajaxItemInfoUrl + '?id=' + encodeURIComponent(id));
      const info = await res.json();
      if (info && info.ok) {
        const unitSel = tr.querySelector('.unit-id');
        if (unitSel && info.default_unit_id) unitSel.value = String(info.default_unit_id);
        const price = tr.querySelector('.price');
        if (price && (!price.value || parseFloat(price.value||'0') === 0) && info.cost) price.value = String(info.cost);
        recalc();
      }
    }catch(err){}
  });

  document.addEventListener('click', (e) => {
    [...tbody.querySelectorAll('.item-box')].forEach(box => {
      const q = box.closest('tr')?.querySelector('.item-query');
      if (q && e.target !== q && !box.contains(e.target)) hideItemBox(box);
    });
  });

  tbody.addEventListener('input', (e) => {
    if (e.target.classList.contains('qty') || e.target.classList.contains('price')) recalc();
  });
  document.getElementById('discount_type').addEventListener('change', recalc);
  document.getElementById('discount_value').addEventListener('input', recalc);
  document.getElementById('tax_rate').addEventListener('input', recalc);
  document.getElementById('tax_enabled').addEventListener('change', recalc);
  document.getElementById('wht_enabled').addEventListener('change', recalc);
  document.getElementById('wht_rate').addEventListener('change', recalc);
  document.getElementById('extra_charges').addEventListener('input', recalc);
  document.getElementById('payment_mode').addEventListener('change', ()=>{
    recalc();
    const mode = (document.getElementById('payment_mode')?.value || '').toLowerCase();
    const paidInput = document.getElementById('paid_amount');
    if (mode === 'partial' && paidInput) {
      paidInput.readOnly = false;
      paidInput.disabled = false;
      paidInput.removeAttribute('readonly');
      paidInput.removeAttribute('disabled');
      paidInput.removeAttribute('tabindex');
      paidInput.style.pointerEvents = '';
      if (Number(paidInput.value || 0) === 0) paidInput.value = '';
      setTimeout(()=> { paidInput.focus(); }, 50);
    }
  });
  document.getElementById('paid_amount').addEventListener('input', recalc);
  document.getElementById('paid_amount').addEventListener('blur', ()=>{
    const mode = (document.getElementById('payment_mode')?.value || 'credit').toLowerCase();
    const paidInput = document.getElementById('paid_amount');
    if (!paidInput || mode !== 'partial') return;
    const grand = Number((document.getElementById('net_total')?.textContent || '0').replace(/,/g,''));
    let paid = Number(paidInput.value || 0);
    if (paid < 0) paid = 0;
    if (grand > 0 && paid > grand) paid = grand;
    paidInput.value = paid ? paid.toFixed(2) : '';
    recalc();
  });

  form.addEventListener('submit', (e)=>{
    const rows = Array.from(tbody.querySelectorAll('tr'));
    const invalidRow = rows.find(r => {
      const label = (r.querySelector('.item-query')?.value || '').trim();
      const idVal = Number(r.querySelector('.item-id')?.value || 0);
      return label !== '' && idVal <= 0;
    });
    if (invalidRow) {
      e.preventDefault();
      alert('يوجد سطر به صنف غير صحيح أو لم يتم اختياره من القائمة. اختر الصنف الصحيح ثم أعد المحاولة.');
      invalidRow.querySelector('.item-query')?.focus();
      return false;
    }
    const ids = rows.map(r => Number(r.querySelector('.item-id')?.value || 0)).filter(Boolean);
    const unique = new Set(ids);
    if (ids.length !== unique.size) {
      e.preventDefault();
      alert('لا يمكن تكرار نفس الصنف أكثر من مرة داخل نفس الفاتورة. احذف السطر المكرر أو عدّل الكمية في السطر الحالي.');
      return false;
    }
    const mode = (document.getElementById('payment_mode')?.value || 'credit').toLowerCase();
    const paid = Number(document.getElementById('paid_amount')?.value || 0);
    const grand = Number((document.getElementById('net_total')?.textContent || '0').replace(/,/g,''));
    if (mode === 'partial' && (paid <= 0 || paid >= grand)) {
      e.preventDefault();
      alert('في الدفع الجزئي أدخل مبلغًا أكبر من صفر وأقل من إجمالي الفاتورة.');
      document.getElementById('paid_amount')?.focus();
      return false;
    }
  });

  document.querySelectorAll('#linesBody tr').forEach(bindRow);
  renumber();
  recalc();
})();
</script>
