<?php
// Variables: date_from,date_to,supplier_id,warehouse_id,warehouses,supplier,rows,summary
?>

<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-4">
            <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 class="form-text">اتركه فارغًا لعرض كل الموردين</div>
          </div>
          <div class="col-md-3">
            <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-1 d-grid">
            <button class="btn btn-primary">عرض</button>
          </div>
        </form>
      </div>
    </div>

    <div class="row">
      <div class="col-lg-12">
        <div class="card">
          <div class="card-header d-flex align-items-center justify-content-between">
            <div>
              <strong>ملخص</strong>
              <span class="text-muted ms-2">(<?= e((string)($summary['count'] ?? 0)) ?> فاتورة)</span>
            </div>
            <a class="btn btn-outline-secondary btn-sm" target="_blank" href="<?= e(url('/reports/purchases/period/print?' . http_build_query(array_merge($_GET, ['format'=>'a4'])))) ?>">
              طباعة
            </a>
            <a class="btn btn-outline-danger btn-sm" href="<?= e(url('/reports/purchases/period/pdf?' . http_build_query($_GET))) ?>">PDF</a>
            <a class="btn btn-outline-success btn-sm" href="<?= e(url('/reports/purchases/period/export?' . http_build_query($_GET))) ?>">Excel</a>
          </div>
          <div class="card-body">
            <div class="row g-3">
              <div class="col-md-2"><div class="small text-muted">الإجمالي قبل الخصم</div><div class="fw-bold"><?= e(format_money($summary['subtotal'] ?? 0)) ?></div></div>
              <div class="col-md-2"><div class="small text-muted">الخصم</div><div class="fw-bold"><?= e(format_money($summary['discount'] ?? 0)) ?></div></div>
              <div class="col-md-2"><div class="small text-muted">الصافي بعد الخصم</div><div class="fw-bold"><?= e(format_money($summary['net'] ?? 0)) ?></div></div>
              <div class="col-md-2"><div class="small text-muted">ض.ق.م</div><div class="fw-bold"><?= e(format_money($summary['vat'] ?? 0)) ?></div></div>
              <div class="col-md-2"><div class="small text-muted">ضريبة ص/ت</div><div class="fw-bold"><?= e(format_money($summary['wht'] ?? 0)) ?></div></div>
              <div class="col-md-2"><div class="small text-muted">الإجمالي النهائي</div><div class="fw-bold"><?= e(format_money($summary['total'] ?? 0)) ?></div></div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="card">
      <div class="card-header"><strong>تفاصيل الفواتير</strong></div>
      <div class="card-body table-responsive">
        <table class="table table-bordered table-sm align-middle">
          <thead>
            <tr>
              <th>رقم</th>
              <th>التاريخ</th>
              <th>المورد</th>
              <th>المخزن</th>
              <th class="text-end">قبل الخصم</th>
              <th class="text-end">الخصم</th>
              <th class="text-end">VAT</th>
              <th class="text-end">ص/ت</th>
              <th class="text-end">الإجمالي</th>
            </tr>
          </thead>
          <tbody>
            <?php if (empty($rows)): ?>
              <tr><td colspan="9" class="text-center text-muted">لا يوجد بيانات</td></tr>
            <?php else: foreach ($rows as $r): ?>
              <tr>
                <td><a href="<?= e(url('/purchases/invoices/view?id=' . (int)$r['id'])) ?>" target="_blank"><?= e($r['inv_no']) ?></a></td>
                <td><?= e(substr((string)$r['inv_date'],0,10)) ?></td>
                <td><?= e($r['supplier_name']) ?></td>
                <td><?= e($r['warehouse_name']) ?></td>
                <td class="text-end"><?= e(format_money($r['subtotal'])) ?></td>
                <td class="text-end"><?= e(format_money($r['discount_amount'])) ?></td>
                <td class="text-end"><?= e(format_money($r['tax_amount'])) ?></td>
                <td class="text-end"><?= e(format_money($r['wht_amount'] ?? 0)) ?></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(){
  const inp = document.getElementById('supplier_search');
  const hid = document.getElementById('supplier_id');
  const box = document.getElementById('supplier_suggest');
  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(<?= json_encode(url('/ajax/parties/search?type=supplier')) ?> + '&q=' + encodeURIComponent(v));
      const data = await res.json();
      show(data || []);
    }, 200);
  });
  document.addEventListener('click', (e)=>{ if(!box.contains(e.target) && e.target!==inp) hide(); });
})();
</script>
