<?php
// view: pages/suppliers/stock_report
?>
<?php
  $rows = $rows ?? [];
  $warehouses = $warehouses ?? [];
  $warehouse_id = (int)($warehouse_id ?? 0);
  $supplier_id = (int)($supplier_id ?? 0);
  $supplier_name = $supplier_name ?? '';
  $supplier_query = $supplier_query ?? '';
  $only_nonzero = (int)($only_nonzero ?? 0);
?>

<div class="card border-0 shadow-sm mb-3" style="border-radius: 16px;">
  <div class="card-body py-3 px-3">
    <div class="d-flex flex-wrap justify-content-between align-items-center gap-3">
      <div>
        <h4 class="mb-0">تقرير مخزون المورد</h4>
        <div class="text-muted small">
          <?= $supplier_id > 0 ? ('المورد: ' . e($supplier_name)) : 'اختر مورد لعرض التقرير' ?>
        </div>
      </div>

      <div class="d-flex flex-wrap align-items-center gap-2">
        <form method="get" class="d-flex flex-wrap align-items-end gap-2 mb-0" style="min-width: 520px;">
          <div class="position-relative" style="min-width: 280px; flex: 1;">
            <label class="small text-muted mb-1">اختر المورد</label>
            <input id="supplier_query" class="form-control form-control-sm" placeholder="ابحث بالاسم أو الهاتف أو الكود" value="<?= e((string)$supplier_query) ?>">
            <input type="hidden" name="supplier_id" id="supplier_id" value="<?= (int)$supplier_id ?>">
            <div id="supplier_suggest" class="suggest-box" style="display:none;"></div>
          </div>

          <div style="min-width: 240px;">
            <label class="small text-muted mb-1">المخزن</label>
            <select name="warehouse_id" class="form-select form-select-sm">
              <option value="0" <?= $warehouse_id===0?'selected':'' ?>>كل المخازن</option>
              <?php foreach ($warehouses as $w): ?>
                <option value="<?= (int)$w['id'] ?>" <?= ((int)$w['id'] === $warehouse_id) ? 'selected' : '' ?>><?= e($w['name']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>

          <div class="form-check" style="margin-bottom: 6px;">
            <input class="form-check-input" type="checkbox" id="only_nonzero" name="only_nonzero" value="1" <?= $only_nonzero? 'checked':'' ?>>
            <label class="form-check-label small" for="only_nonzero">إظهار الأرصدة غير الصفرية فقط</label>
          </div>

          <button class="btn btn-sm btn-dark" style="border-radius: 12px; padding: 8px 14px; font-weight: 800;">عرض</button>
        </form>

        <?php if ($supplier_id > 0): ?>
          <div class="btn-group">
            <a class="btn btn-sm btn-primary" target="_blank" href="<?= e(url('/reports/purchases/supplier-stock/print?party_id='.(int)$supplier_id.'&warehouse_id='.(int)$warehouse_id.'&only_nonzero='.(int)$only_nonzero.'&format=a4')) ?>">🖨 طباعة</a>
            <a class="btn btn-sm btn-outline-danger" href="<?= e(url('/reports/purchases/supplier-stock/pdf?party_id='.(int)$supplier_id.'&warehouse_id='.(int)$warehouse_id.'&only_nonzero='.(int)$only_nonzero)) ?>">PDF</a>
            <a class="btn btn-sm btn-outline-success" href="<?= e(url('/reports/purchases/supplier-stock/export?party_id='.(int)$supplier_id.'&warehouse_id='.(int)$warehouse_id.'&only_nonzero='.(int)$only_nonzero)) ?>">Excel</a>
          </div>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>

<?php if ($supplier_id > 0): ?>
<div class="card p-3">
  <div class="table-responsive">
    <table class="table table-bordered table-hover table-striped align-middle table-sm mb-0" style="table-layout: fixed;">
      <thead class="table-light">
        <tr>
          <th style="width:60px">#</th>
          <th>الصنف</th>
          <th style="width:150px">باركود</th>
          <th class="text-end" style="width:95px">رصيد</th>
          <th class="text-end" style="width:95px">تكلفة</th>
          <th class="text-end" style="width:120px">قيمة تكلفة</th>
        </tr>
      </thead>
      <tbody>
        <?php
          $total_cost_value = 0;
          foreach ($rows as $r):
            $cost_value = (float)$r['qty'] * (float)$r['cost'];
            $total_cost_value += $cost_value;
        ?>
        <tr>
          <td><?= (int)$r['id'] ?></td>
          <td><?= e($r['name']) ?></td>
          <td><?= e($r['barcode'] ?? '-') ?></td>
          <td class="text-end"><?= format_qty($r['qty']) ?></td>
          <td class="text-end"><?= format_money($r['cost']) ?></td>
          <td class="text-end"><?= format_money($cost_value) ?></td>
        </tr>
        <?php endforeach; ?>
        <?php if (!$rows): ?>
          <tr><td colspan="6" class="text-center text-muted py-4">لا توجد بيانات</td></tr>
        <?php endif; ?>
      </tbody>
      <tfoot class="table-light">
        <tr>
          <th colspan="5" class="text-end">إجمالي قيمة التكلفة</th>
          <th class="text-end"><?= format_money($total_cost_value) ?></th>
        </tr>
      </tfoot>
    </table>
  </div>
</div>
<?php endif; ?>

<style>
  .suggest-box{
    position:absolute; z-index: 9999; background:#fff; border:1px solid #e5e7eb; border-radius: 12px;
    width:100%; margin-top: 6px; box-shadow: 0 10px 28px rgba(0,0,0,.08);
    max-height: 260px; overflow:auto;
  }
  .suggest-item{ padding: 10px 12px; cursor:pointer; border-bottom: 1px solid #f1f5f9; }
  .suggest-item:last-child{ border-bottom:none; }
  .suggest-item:hover{ background:#f8fafc; }
</style>

<script>
(function(){
  const q = document.getElementById('supplier_query');
  const id = document.getElementById('supplier_id');
  const box = document.getElementById('supplier_suggest');
  if (!q || !id || !box) return;
  let t = null;

  function hide(){ box.style.display='none'; box.innerHTML=''; }
  function show(){ box.style.display='block'; }

  q.addEventListener('input', function(){
    clearTimeout(t);
    const val = q.value.trim();
    id.value = '';
    if (val.length < 1) { hide(); return; }

    t = setTimeout(async () => {
      try{
        const res = await fetch(<?= json_encode(url('/ajax/parties/search?type=supplier')) ?> + '&q=' + encodeURIComponent(val));
        const rows = await res.json();
        if (!rows.length) { hide(); return; }
        box.innerHTML = rows.map(s => {
          const label = [s.name, s.code, s.phone].filter(Boolean).join(' - ');
          return `<div class="suggest-item" data-id="${s.id}">${label}</div>`;
        }).join('');
        show();
      } catch(e){ hide(); }
    }, 250);
  });

  box.addEventListener('click', function(e){
    const el = e.target.closest('.suggest-item');
    if (!el) return;
    id.value = el.getAttribute('data-id');
    q.value = el.textContent.trim();
    hide();
  });

  document.addEventListener('click', function(e){
    if (!box.contains(e.target) && e.target !== q) hide();
  });
})();
</script>
