<?php
// view: pages/purchases/supplier_aging_report
$as_of = $as_of ?? date('Y-m-d');
$supplier_id = (int)($supplier_id ?? 0);
$selected_supplier = $selected_supplier ?? null;
$supplier_query = '';
if (is_array($selected_supplier) && ($selected_supplier['name'] ?? '') !== '') {
  $supplier_query = (string)$selected_supplier['name'];
}
$buckets = $buckets ?? [];
$rows = $rows ?? [];
$totals = $totals ?? [];

$bucket_labels = array_map(fn($b) => is_array($b) ? ($b['label'] ?? '') : (string)$b, $buckets);
$bucket_labels = array_values(array_filter($bucket_labels, fn($x)=>$x!==''));
?>
<div class="d-flex align-items-center justify-content-between mb-3">
  <div>
    <h4 class="mb-1">تقرير أعمار ديون الموردين</h4>
    <div class="text-muted small">يتم احتساب المتبقي لكل فاتورة: (إجمالي الفاتورة - مرتجعاتها) - المدفوعات الموزعة عليها.</div>
  </div>
  <div class="d-flex gap-2">
    <?php
      $printQs = ['as_of' => $as_of];
      if ($supplier_id > 0) $printQs['supplier_id'] = $supplier_id;
      $printUrl = '/reports/parties/supplier-aging/print?' . http_build_query($printQs);
    ?>
    <a class="btn btn-outline-secondary" href="<?= e(url($printUrl . '&format=a4')) ?>" target="_blank">
      <i class="fa-solid fa-print"></i> طباعة
    </a>
    <a class="btn btn-outline-danger" href="<?= e(url('/reports/parties/supplier-aging/pdf?' . http_build_query($printQs))) ?>">PDF</a>
    <a class="btn btn-outline-success" href="<?= e(url('/reports/parties/supplier-aging/export?' . http_build_query($printQs))) ?>">Excel</a>
  </div>
</div>

<form class="card card-body mb-3" method="get" action="<?= e(url('/reports/parties/supplier-aging')) ?>">
  <div class="row g-2 align-items-end">
    <div class="col-md-4">
      <label class="form-label">حتى تاريخ</label>
      <input type="date" class="form-control" name="as_of" value="<?= e($as_of) ?>">
    </div>
    <div class="col-md-6">
      <label class="form-label">المورد (اختياري)</label>
      <input type="hidden" name="supplier_id" id="supplier_id" value="<?= e((string)$supplier_id) ?>">
      <div class="position-relative">
        <input type="text" class="form-control" id="supplier_query" value="<?= e($supplier_query) ?>" placeholder="اكتب اسم/كود المورد للبحث...">
        <div id="supplier_box" class="list-group position-absolute w-100" style="z-index: 9999; display:none; max-height:260px; overflow:auto;"></div>
      </div>
      <div class="form-text">لو سيبته فاضي: التقرير هيظهر لكل الموردين.</div>
    </div>
    <div class="col-md-2">
      <button class="btn btn-primary w-100" type="submit"><i class="fa-solid fa-magnifying-glass"></i> عرض</button>
    </div>
  </div>
</form>

<script>
(function(){
  const supQ = document.getElementById('supplier_query');
  const supId = document.getElementById('supplier_id');
  const box = document.getElementById('supplier_box');
  let t=null;

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

  supQ.addEventListener('input', ()=>{
    clearTimeout(t);
    const val = supQ.value.trim();
    supId.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 items = await res.json();
        if (!items || !items.length){ hide(); 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.code || ''}</div>
          </button>`).join('');
        show();
      }catch(e){ hide(); }
    }, 200);
  });

  box.addEventListener('click', (e)=>{
    const btn = e.target.closest('button[data-id]');
    if (!btn) return;
    supId.value = btn.getAttribute('data-id');
    supQ.value = btn.querySelector('.fw-bold').textContent.trim();
    hide();
  });

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

<div class="card">
  <div class="table-responsive">
    <table class="table table-striped mb-0">
      <thead>
        <tr>
          <th>المورد</th>
          <?php foreach ($bucket_labels as $lbl): ?>
            <th class="text-end"><?= e($lbl) ?></th>
          <?php endforeach; ?>
          <th class="text-end">الإجمالي</th>
        </tr>
      </thead>
      <tbody>
        <?php if (!$rows): ?>
          <tr><td colspan="<?= 2 + count($bucket_labels) ?>" class="text-center text-muted py-4">لا توجد بيانات</td></tr>
        <?php else: ?>
          <?php foreach ($rows as $r): ?>
            <?php
              $s = $r['supplier'] ?? [];
              $b = $r['buckets'] ?? [];
              $sid = (int)($s['id'] ?? 0);
              $sname = (string)($s['name'] ?? '');
              $scode = (string)($s['code'] ?? '');
              $total = (float)($b['total'] ?? 0);
            ?>
            <tr>
              <td>
                <div class="fw-bold"><?= e($sname) ?></div>
                <div class="small text-muted"><?= e($scode) ?></div>
              </td>
              <?php foreach ($bucket_labels as $lbl): ?>
                <td class="text-end"><?= e(format_money((float)($b[$lbl] ?? 0))) ?></td>
              <?php endforeach; ?>
              <td class="text-end fw-bold"><?= e(format_money($total)) ?></td>
            </tr>
          <?php endforeach; ?>
        <?php endif; ?>
      </tbody>
      <?php if ($rows): ?>
      <tfoot>
        <tr>
          <th>الإجمالي</th>
          <?php foreach ($bucket_labels as $lbl): ?>
            <th class="text-end"><?= e(format_money((float)($totals[$lbl] ?? 0))) ?></th>
          <?php endforeach; ?>
          <th class="text-end"><?= e(format_money((float)($totals['total'] ?? 0))) ?></th>
        </tr>
      </tfoot>
      <?php endif; ?>
    </table>
  </div>
</div>
