<?php
// Variables: date_from,date_to,supplier_id,warehouse_id,item_id,warehouses,supplier,item,rows,totals
?>

<div class="content-header">
  <div class="container-fluid">
    <div class="row mb-2">
      <div class="col-sm-6">
        <h1 class="m-0">تقرير الأصناف المشتراة</h1>
      </div>
      <div class="col-sm-6">
        <ol class="breadcrumb float-sm-right">
          <li class="breadcrumb-item"><a href="<?= e(url('/admin/dashboard')) ?>">الرئيسية</a></li>
          <li class="breadcrumb-item active">تقارير المشتريات</li>
        </ol>
      </div>
    </div>
  </div>
</div>

<section class="content">
  <div class="container-fluid">
    <div class="card">
      <div class="card-body">
        <form method="get" class="row g-2 align-items-end">
          <div class="col-md-2">
            <label class="form-label">من</label>
            <input type="date" name="from" class="form-control" value="<?= e($date_from) ?>">
          </div>
          <div class="col-md-2">
            <label class="form-label">إلى</label>
            <input type="date" name="to" class="form-control" value="<?= e($date_to) ?>">
          </div>

          <div class="col-md-3">
            <label class="form-label">المورد</label>
            <div class="position-relative">
              <input type="text" id="supplier_search" class="form-control" placeholder="ابحث عن مورد..." value="<?= e($supplier['name'] ?? '') ?>" autocomplete="off">
              <input type="hidden" name="supplier_id" id="supplier_id" value="<?= e((string)$supplier_id) ?>">
              <div id="supplier_suggest" class="list-group position-absolute w-100" style="z-index:1050; display:none;"></div>
            </div>
          </div>

          <div class="col-md-3">
            <label class="form-label">الصنف</label>
            <div class="position-relative">
              <input type="text" id="item_search" class="form-control" placeholder="ابحث عن صنف..." value="<?= e($item['name'] ?? '') ?>" autocomplete="off">
              <input type="hidden" name="item_id" id="item_id" value="<?= e((string)$item_id) ?>">
              <div id="item_suggest" class="list-group position-absolute w-100" style="z-index:1050; display:none;"></div>
            </div>
          </div>

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

          <div class="col-md-12"></div>
          <div class="col-md-2 d-grid">
            <button class="btn btn-primary">عرض</button>
          </div>
          <div class="col-md-2">
            <a class="btn btn-outline-secondary w-100" target="_blank" href="<?= e(url('/reports/purchases/items/print?' . http_build_query(array_merge($_GET, ['format'=>'a4'])))) ?>">طباعة</a> <a class="btn btn-outline-danger btn-sm" href="<?= e(url('/reports/purchases/items/pdf?' . http_build_query($_GET))) ?>">PDF</a> <a class="btn btn-outline-success btn-sm" href="<?= e(url('/reports/purchases/items/export?' . http_build_query($_GET))) ?>">Excel</a>
          </div>
          <div class="col-md-8 text-muted small d-flex align-items-center">
            يعرض إجمالي الكميات والقيمة ومتوسط سعر الشراء (محسوب = إجمالي القيمة / إجمالي الكمية).
          </div>
        </form>
      </div>
    </div>

    <div class="card">
      <div class="card-header d-flex justify-content-between">
        <strong>النتائج</strong>
        <div class="text-muted small">إجمالي الكمية: <strong><?= e(number_format((float)($totals['qty'] ?? 0), 3)) ?></strong> | إجمالي القيمة: <strong><?= e(format_money($totals['total'] ?? 0)) ?></strong></div>
      </div>
      <div class="card-body table-responsive">
        <table class="table table-bordered table-sm align-middle">
          <thead>
            <tr>
              <th>الصنف</th>
              <th class="text-end">الكمية</th>
              <th class="text-end">متوسط السعر</th>
              <th class="text-end">إجمالي القيمة</th>
            </tr>
          </thead>
          <tbody>
            <?php if (empty($rows)): ?>
              <tr><td colspan="4" class="text-center text-muted">لا يوجد بيانات</td></tr>
            <?php else: foreach ($rows as $r): ?>
              <tr>
                <td><?= e($r['item_name']) ?></td>
                <td class="text-end"><?= e(number_format((float)$r['qty'], 3)) ?></td>
                <td class="text-end"><?= e(format_money($r['avg_price'])) ?></td>
                <td class="text-end fw-bold"><?= e(format_money($r['total'])) ?></td>
              </tr>
            <?php endforeach; endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</section>

<script>
(function(){
  function bindSuggest(inpId, hidId, boxId, url){
    const inp = document.getElementById(inpId);
    const hid = document.getElementById(hidId);
    const box = document.getElementById(boxId);
    if(!inp) return;
    let t=null;
    function hide(){ box.style.display='none'; box.innerHTML=''; }
    function show(items){
      box.innerHTML='';
      if(!items.length){ hide(); return; }
      items.forEach(it=>{
        const a=document.createElement('a');
        a.href='#';
        a.className='list-group-item list-group-item-action';
        a.textContent=it.name;
        a.onclick=(e)=>{ e.preventDefault(); inp.value=it.name; hid.value=it.id; hide(); };
        box.appendChild(a);
      });
      box.style.display='block';
    }
    inp.addEventListener('input', ()=>{
      clearTimeout(t);
      const v=inp.value.trim();
      if(v.length<1){ hid.value='0'; hide(); return; }
      t=setTimeout(async ()=>{
        const res = await fetch(url + encodeURIComponent(v));
        const data = await res.json();
        show(data || []);
      }, 200);
    });
    document.addEventListener('click', (e)=>{ if(!box.contains(e.target) && e.target!==inp) hide(); });
  }
  bindSuggest('supplier_search','supplier_id','supplier_suggest',<?= json_encode(url('/ajax/parties/search?type=supplier')) ?> + '&q=');
  bindSuggest('item_search','item_id','item_suggest',<?= json_encode(url('/ajax/items/search')) ?> + '?q=');
})();
</script>
