<?php
// app/views/pages/item_movement_report.php
$print_url = url('/reports/inventory/item-movement/print') . '?warehouse_id=' . (int)$warehouse_id . '&item_id=' . (int)$item_id . '&from=' . urlencode($from) . '&to=' . urlencode($to) . '&format=a4';
$pdf_url = url('/reports/inventory/item-movement/pdf') . '?warehouse_id=' . (int)$warehouse_id . '&item_id=' . (int)$item_id . '&from=' . urlencode($from) . '&to=' . urlencode($to);
$excel_url = url('/reports/inventory/item-movement/export') . '?warehouse_id=' . (int)$warehouse_id . '&item_id=' . (int)$item_id . '&from=' . urlencode($from) . '&to=' . urlencode($to);
$prefill = '';
if (!empty($meta['item_name'])) {
  $prefill = $meta['item_name'];
  if (!empty($meta['item_barcode'])) $prefill .= ' — [' . $meta['item_barcode'] . ']';
}
?>
<div class="container-fluid">

  <div class="card shadow-sm mb-3">
    <div class="card-body">
      <div class="d-flex flex-column flex-lg-row align-items-lg-center justify-content-between gap-3">
        <div>
          <h4 class="mb-1 fw-bold">تقرير حركة صنف</h4>
          <div class="text-muted">اختر المخزن والصنف والفترة الزمنية ثم اضغط عرض التقرير</div>
        </div>

        <div class="d-flex gap-2">
          <a class="btn btn-outline-secondary" href="<?= e(url('/reports/inventory/item-movement')) ?>">
            <i class="fa-solid fa-rotate"></i> جديد
          </a>
          <a class="btn btn-primary<?= $item_id>0 ? '' : ' disabled' ?>" href="<?= e($print_url) ?>" target="_blank"><i class="fa-solid fa-print"></i> طباعة</a>
          <a class="btn btn-outline-danger<?= $item_id>0 ? '' : ' disabled' ?>" href="<?= e($pdf_url) ?>">PDF</a>
          <a class="btn btn-outline-success<?= $item_id>0 ? '' : ' disabled' ?>" href="<?= e($excel_url) ?>">Excel</a>
        </div>
      </div>

      <hr class="my-3"/>

      <form method="get" class="row g-3 align-items-end" autocomplete="off">
        <div class="col-12 col-lg-4">
          <label class="form-label">المخزن</label>
          <select name="warehouse_id" class="form-select">
            <?php foreach ($warehouses as $w): ?>
              <option value="<?= (int)$w['id'] ?>" <?= ((int)$w['id']===(int)$warehouse_id)?'selected':'' ?>>
                <?= e($w['name']) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="col-12 col-lg-4 position-relative">
          <label class="form-label">الصنف</label>
          <input type="text" id="item_query" class="form-control" placeholder="ابحث بالاسم أو الباركود" value="<?= e($prefill) ?>">
          <input type="hidden" name="item_id" id="item_id" value="<?= (int)$item_id ?>">
          <div id="item_suggest" class="suggest-box" style="display:none;"></div>
        </div>

        <div class="col-6 col-lg-2">
          <label class="form-label">من</label>
          <input type="date" name="from" class="form-control" value="<?= e($from) ?>">
        </div>

        <div class="col-6 col-lg-2">
          <label class="form-label">إلى</label>
          <input type="date" name="to" class="form-control" value="<?= e($to) ?>">
        </div>

        <div class="col-12">
          <button class="btn btn-success" onclick="return document.getElementById('item_id').value>0;">
            <i class="fa-solid fa-magnifying-glass"></i> عرض التقرير
          </button>
          <span class="text-muted small ms-2">(اختر صنف من نتائج البحث)</span>
        </div>
      </form>
    </div>
  </div>

  <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('item_query');
    const id = document.getElementById('item_id');
    const box = document.getElementById('item_suggest');
    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/items/search')) ?> + '?q=' + encodeURIComponent(val));
          const items = await res.json();
          if (!items.length) { hide(); return; }
          box.innerHTML = items.map(it => `<div class="suggest-item" data-id="${it.id}">${it.text}</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>

  <?php if ($item_id > 0): ?>
  <div class="card shadow-sm">
    <div class="card-body">
      <div class="row g-3 mb-3">
        <div class="col-12 col-lg-4">
          <div class="p-3 border rounded-3 h-100">
            <div class="text-muted mb-1">المخزن</div>
            <div class="fw-bold"><?= e($meta['warehouse_name'] ?: '-') ?></div>
          </div>
        </div>
        <div class="col-12 col-lg-4">
          <div class="p-3 border rounded-3 h-100">
            <div class="text-muted mb-1">الصنف</div>
            <div class="fw-bold"><?= e($meta['item_name'] ?: '-') ?></div>
            <?php if (!empty($meta['item_barcode'])): ?>
              <div class="text-muted small">باركود: <?= e($meta['item_barcode']) ?></div>
            <?php endif; ?>
          </div>
        </div>
        <div class="col-12 col-lg-4">
          <div class="p-3 border rounded-3 h-100">
            <div class="text-muted mb-1">الفترة</div>
            <div class="fw-bold"><?= e($from) ?> → <?= e($to) ?></div>
            <div class="text-muted small">رصيد افتتاحي قبل الفترة: <span class="fw-bold"><?= format_qty((float)$opening) ?></span></div>
          </div>
        </div>
      </div>

      <div class="table-responsive">
        <table class="table table-bordered align-middle">
          <thead class="table-light">
            <tr>
              <th style="width:60px">#</th>
              <th style="width:170px">التاريخ</th>
              <th style="width:120px">النوع</th>
              <th>المرجع</th>
              <th style="width:120px">وارد</th>
              <th style="width:120px">صادر</th>
              <th style="width:140px">الرصيد</th>
              <th style="width:140px">بواسطة</th>
            </tr>
          </thead>
          <tbody>
            <?php $bal = (float)$opening; $i = 0; ?>
            <?php foreach ($moves as $m): ?>
              <?php
                $i++;
                $in = (float)$m['qty_in'];
                $out = (float)$m['qty_out'];
                $bal += ($in - $out);
              ?>
              <tr>
                <td><?= (int)$i ?></td>
                <td><?= e(substr((string)$m['created_at'], 0, 16)) ?></td>
                <td><?= e(doc_type_label((string)$m['ref_type'])) ?></td>
                <td><?= e((string)($m['ref_label'] ?? human_reference_label((string)($m['ref_type'] ?? ''), (int)($m['ref_id'] ?? 0)))) ?></td>
                <td><?= $in > 0 ? format_qty($in) : '-' ?></td>
                <td><?= $out > 0 ? format_qty($out) : '-' ?></td>
                <td class="fw-bold"><?= format_qty($bal) ?></td>
                <td><?= e($m['username'] ?? '') ?></td>
              </tr>
            <?php endforeach; ?>

            <?php if (empty($moves)): ?>
              <tr><td colspan="8" class="text-center text-muted p-4">لا توجد حركات ضمن الفترة المحددة.</td></tr>
            <?php endif; ?>
          </tbody>
          <tfoot>
            <tr class="table-light">
              <th colspan="4" class="text-end">الإجمالي</th>
              <th><?= format_qty((float)$tot_in) ?></th>
              <th><?= format_qty((float)$tot_out) ?></th>
              <th colspan="2"></th>
            </tr>
          </tfoot>
        </table>
      </div>

    </div>
  </div>
  <?php endif; ?>

</div>
