<?php
$invoices = $invoices ?? [];
$from = $from ?? date('Y-m-01');
$to = $to ?? date('Y-m-d');
$q = $q ?? '';
$status = $status ?? '';
$warehouseId = (int)($warehouse_id ?? 0);
$partyId = (int)($party_id ?? 0);
$warehouses = $warehouses ?? [];
$selectedCustomer = $selectedCustomer ?? null;
$customerLabel = $selectedCustomer ? ((string)$selectedCustomer['name'] . ' (' . (string)$selectedCustomer['code'] . ')') : '';
?>

<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
  <h4 class="mb-0">فواتير المبيعات</h4>
  <?php if (can('sales.invoices.create')): ?>
    <a class="btn btn-primary" href="<?= e(url($sales_invoice_form_url ?? '/sales/invoices/form')) ?>">إنشاء فاتورة</a>
  <?php endif; ?>
</div>

<div class="card p-3 mb-3">
  <form class="row g-2 align-items-end" method="get" autocomplete="off">
    <div class="col-lg-3 col-md-6">
      <label class="form-label">بحث عام</label>
      <input class="form-control" name="q" value="<?= e($q) ?>" placeholder="رقم فاتورة / اسم عميل / كود / موبايل">
    </div>
    <div class="col-lg-3 col-md-6 position-relative">
      <label class="form-label">العميل</label>
      <input type="hidden" name="party_id" id="filter_party_id" value="<?= $partyId ?>">
      <input type="text" class="form-control" id="filter_customer_search" value="<?= e($customerLabel) ?>" placeholder="اختر عميلًا محددًا">
      <div class="list-group position-absolute w-100 shadow-sm" id="filter_customer_results" style="z-index:20; display:none"></div>
    </div>
    <div class="col-lg-2 col-md-4">
      <label class="form-label">المخزن</label>
      <select class="form-select" name="warehouse_id">
        <option value="0">كل المخازن</option>
        <?php foreach ($warehouses as $w): ?>
          <option value="<?= (int)$w['id'] ?>" <?= $warehouseId === (int)$w['id'] ? 'selected' : '' ?>><?= e((string)$w['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="col-lg-2 col-md-4">
      <label class="form-label">الحالة</label>
      <select class="form-select" name="status">
        <option value="" <?= $status === '' ? 'selected' : '' ?>>كل الحالات</option>
        <option value="POSTED" <?= strtoupper((string)$status) === 'POSTED' ? 'selected' : '' ?>>مرحّلة</option>
        <option value="DRAFT" <?= strtoupper((string)$status) === 'DRAFT' ? 'selected' : '' ?>>مسودة</option>
      </select>
    </div>
    <div class="col-lg-1 col-md-2">
      <label class="form-label">من</label>
      <input class="form-control" type="date" name="from" value="<?= e($from) ?>">
    </div>
    <div class="col-lg-1 col-md-2">
      <label class="form-label">إلى</label>
      <input class="form-control" type="date" name="to" value="<?= e($to) ?>">
    </div>
    <div class="col-12 d-flex flex-wrap gap-2 mt-2">
      <button class="btn btn-outline-dark"><i class="fa-solid fa-magnifying-glass me-1"></i>عرض</button>
      <?php if ($q !== '' || $status !== '' || $warehouseId > 0 || $partyId > 0): ?>
        <a class="btn btn-outline-secondary" href="<?= e(url($sales_invoices_url ?? '/sales/invoices')) ?>?from=<?= e($from) ?>&to=<?= e($to) ?>"><i class="fa-solid fa-xmark me-1"></i>مسح</a>
      <?php endif; ?>
    </div>
  </form>
</div>

<div class="card p-3">
  <div class="table-responsive">
    <table class="table table-bordered table-hover table-striped table-sm align-middle mb-0">
      <thead class="table-light">
        <tr>
          <th>#</th>
          <th>رقم الفاتورة</th>
          <th>التاريخ</th>
          <th>العميل</th>
          <th>المخزن</th>
          <th class="text-end">الإجمالي</th>
          <th class="text-end">المدفوع</th>
          <th class="text-end">المتبقي</th>
          <th>الحالة</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($invoices as $inv): ?>
          <tr>
            <td><?= (int)$inv['id'] ?></td>
            <td><?= e((string)$inv['invoice_no']) ?></td>
            <td><?= e(substr((string)$inv['invoice_date'], 0, 10)) ?></td>
            <td><?= e((string)($inv['customer_name'] ?? '-')) ?></td>
            <td><?= e((string)($inv['warehouse_name'] ?? '-')) ?></td>
            <td class="text-end"><?= format_money((float)($inv['grand_total'] ?? 0)) ?></td>
            <td class="text-end"><?= format_money((float)($inv['paid_amount'] ?? 0)) ?></td>
            <td class="text-end"><?= format_money((float)($inv['due_amount'] ?? 0)) ?></td>
            <td>
              <?php if (strtoupper((string)($inv['status'] ?? '')) === 'POSTED'): ?>
                <span class="badge bg-success">مرحّلة</span>
              <?php else: ?>
                <span class="badge bg-secondary">مسودة</span>
              <?php endif; ?>
            </td>
            <td class="text-end">
              <a class="btn btn-sm btn-outline-dark" href="<?= e(url($sales_invoice_view_base_url ?? '/sales/invoices/view')) ?>?id=<?= (int)$inv['id'] ?>">عرض</a>
            </td>
          </tr>
        <?php endforeach; ?>
        <?php if (!$invoices): ?>
          <tr><td colspan="10" class="text-center text-muted py-4">لا توجد فواتير</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>

</div>

<script>
(function(){
  const search = document.getElementById('filter_customer_search');
  const results = document.getElementById('filter_customer_results');
  const hidden = document.getElementById('filter_party_id');
  if (!search || !results || !hidden) return;

  let timer = null;
  let currentItems = [];
  let activeIndex = -1;

  function closeBox(){
    results.style.display = 'none';
    results.innerHTML = '';
    currentItems = [];
    activeIndex = -1;
  }

  function highlight(){
    Array.from(results.children).forEach((node, idx) => node.classList.toggle('active', idx === activeIndex));
  }

  function choose(row){
    hidden.value = row.id;
    search.value = `${row.name} (${row.code})`;
    closeBox();
  }

  function render(items){
    currentItems = items;
    activeIndex = items.length ? 0 : -1;
    results.innerHTML = '';
    items.forEach((row, idx) => {
      const a = document.createElement('a');
      a.href = '#';
      a.className = 'list-group-item list-group-item-action' + (idx === 0 ? ' active' : '');
      a.textContent = `${row.name} (${row.code})`;
      a.addEventListener('mousedown', (e) => {
        e.preventDefault();
        choose(row);
      });
      results.appendChild(a);
    });
    results.style.display = items.length ? 'block' : 'none';
  }

  search.addEventListener('input', () => {
    clearTimeout(timer);
    const q = search.value.trim();
    if (!q) {
      hidden.value = '0';
      closeBox();
      return;
    }
    hidden.value = '0';
    timer = setTimeout(async () => {
      try {
        const response = await fetch(<?= json_encode(url('/ajax/customers/search')) ?> + '?q=' + encodeURIComponent(q));
        const data = await response.json();
        render(Array.isArray(data) ? data.slice(0, 12) : []);
      } catch (_) {
        closeBox();
      }
    }, 200);
  });

  search.addEventListener('keydown', (e) => {
    if (results.style.display !== 'block' || !currentItems.length) {
      if (e.key === 'Enter' && hidden.value === '0' && search.value.trim() !== '') {
        e.preventDefault();
      }
      return;
    }
    if (e.key === 'ArrowDown') {
      e.preventDefault();
      activeIndex = (activeIndex + 1) % currentItems.length;
      highlight();
    } else if (e.key === 'ArrowUp') {
      e.preventDefault();
      activeIndex = (activeIndex - 1 + currentItems.length) % currentItems.length;
      highlight();
    } else if (e.key === 'Enter') {
      e.preventDefault();
      if (activeIndex >= 0 && currentItems[activeIndex]) choose(currentItems[activeIndex]);
    } else if (e.key === 'Escape') {
      closeBox();
    }
  });

  document.addEventListener('click', (e) => {
    if (!results.contains(e.target) && e.target !== search) closeBox();
  });
})();
</script>
