<?php
use App\Shared\Support\Format;
// view: pages/stock/stock_voucher
$warehouses = $warehouses ?? [];
$items = $items ?? [];
$units = $units ?? [];
$doc_type = $doc_type ?? 'RECEIPT';
$warehouse_id = (int)($warehouse_id ?? 0);
$to_warehouse_id = (int)($to_warehouse_id ?? 0);
$doc_date = $doc_date ?? date('Y-m-d');
$notes = $notes ?? '';
$lines = $lines ?? [];
$items_map = $items_map ?? [];
?>

<div class="row g-3">
  <!-- 1) بيانات الإذن (Stacked) -->
  <div class="col-12">
    <div class="card shadow-sm">
      <div class="card-header"><strong>بيانات الإذن</strong></div>
      <div class="card-body">
        <form method="post" class="row g-2">
          <?= csrf_input() ?>
          <input type="hidden" name="action" value="noop">

          <div class="col-lg-4">
            <label class="form-label">نوع الإذن</label>
            <select class="form-select" name="doc_type" onchange="this.form.submit()">
              <?php
                $types = [
                  'RECEIPT'=>'إضافة (دخول)',
                  'ISSUE'=>'صرف (خروج)',
                  'TRANSFER'=>'تحويل بين مخازن',
                  'SCRAP'=>'هالك / تالف',
                  'ADJUST'=>'تسوية (فرق +/-)'
                ];
                foreach ($types as $k=>$v):
              ?>
                <option value="<?= e($k) ?>" <?= $doc_type===$k?'selected':'' ?>><?= e($v) ?></option>
              <?php endforeach; ?>
            </select>
          </div>

          <div class="col-lg-4 col-md-6">
            <label class="form-label"><?= $doc_type==='TRANSFER' ? 'من مخزن' : 'المخزن' ?></label>
            <select class="form-select" name="warehouse_id" onchange="this.form.submit()">
              <?php foreach ($warehouses as $w): ?>
                <option value="<?= (int)$w['id'] ?>" <?= ((int)$w['id']===$warehouse_id)?'selected':'' ?>>
                  <?= e($w['name']) ?><?= ((int)$w['is_main']===1) ? ' (رئيسي)' : '' ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>

          <div class="col-lg-4 col-md-6 <?= $doc_type==='TRANSFER' ? '' : 'd-none' ?>" id="toWhWrap">
            <label class="form-label">إلى مخزن</label>
            <select class="form-select" name="to_warehouse_id" onchange="this.form.submit()">
              <option value="0">اختر...</option>
              <?php foreach ($warehouses as $w): ?>
                <option value="<?= (int)$w['id'] ?>" <?= ((int)$w['id']===$to_warehouse_id)?'selected':'' ?>>
                  <?= e($w['name']) ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>

          <div class="col-lg-3 col-md-6">
            <label class="form-label">تاريخ</label>
            <input class="form-control" type="date" name="doc_date" value="<?= e($doc_date) ?>" onchange="this.form.submit()">
          </div>

          <div class="col-lg-9 col-md-6">
            <label class="form-label">ملاحظات</label>
            <input class="form-control" name="notes" value="<?= e($notes) ?>" onchange="this.form.submit()">
          </div>
        </form>
      </div>
      <div class="card-footer text-muted small">
        ملاحظة: الإذن يُرحّل مباشرة (POSTED) في هذه النسخة.
      </div>
    </div>
  </div>

  <!-- 2) إضافة بند -->
  <div class="col-12">
    <div class="card shadow-sm">
      <div class="card-header"><strong>إضافة بند</strong></div>
      <div class="card-body">
        <form method="post" class="row g-2 align-items-end">
          <?= csrf_input() ?>
          <input type="hidden" name="action" value="add_line">

          <div class="col-lg-6">
            <label class="form-label">الصنف</label>
            <div class="position-relative item-picker-shell">
              <input type="text" id="voucher_item_query" class="form-control" placeholder="ابحث بالاسم أو الباركود... ثم Enter" autocomplete="off" required>
              <input type="hidden" name="item_id" id="voucher_item_id" value="" required>
              <div id="voucher_item_suggest" class="suggest-box" style="display:none;"></div>
            </div>
          </div>

          <div class="col-lg-2 col-md-4">
            <label class="form-label">الوحدة (اختياري)</label>
            <select class="form-select" name="unit_id">
              <option value="">-</option>
              <?php foreach ($units as $u): ?>
                <option value="<?= (int)$u['id'] ?>"><?= e($u['name']) ?><?= $u['symbol'] ? ' (' . e($u['symbol']) . ')' : '' ?></option>
              <?php endforeach; ?>
            </select>
          </div>

          <div class="col-lg-3 col-md-4">
            <label class="form-label">الكمية</label>
            <input class="form-control js-decimal-input" type="number" step="0.001" name="qty" value="1" required data-decimals="3">
          </div>

          <div class="col-lg-1">
            <button class="btn btn-primary w-100"><i class="fa-solid fa-plus"></i></button>
          </div>
        </form>
        <div class="text-muted small mt-2">التكلفة تُسحب تلقائيًا من تعريف الصنف ولا يمكن تعديلها من الإذن.</div>
      </div>
    </div>
  </div>

  <!-- 3) بنود الإذن (Editable داخل الجدول) -->
  <div class="col-12">
    <div class="card shadow-sm">
      <div class="card-header d-flex align-items-center justify-content-between">
        <strong>بنود الإذن</strong>
        <div class="d-flex gap-2">
          <form method="post" class="m-0">
            <?= csrf_input() ?>
            <input type="hidden" name="action" value="clear">
            <button class="btn btn-sm btn-outline-secondary"><i class="fa-solid fa-broom me-1"></i>تفريغ</button>
          </form>
          <form method="post" class="m-0">
            <?= csrf_input() ?>
            <input type="hidden" name="action" value="post">
            <button class="btn btn-sm btn-success" <?= $lines ? '' : 'disabled' ?>><i class="fa-solid fa-check me-1"></i>ترحيل</button>
          </form>
        </div>
      </div>

      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table table-hover table-striped table-bordered align-middle mb-0">
            <thead class="table-light">
              <tr>
                <th>الصنف</th>
                <th style="width:220px;">الوحدة</th>
                <th class="text-center" style="width:160px;">الكمية</th>
                <th class="text-end" style="width:160px;">التكلفة</th>
                <th class="text-center" style="width:90px;">حفظ</th>
                <th class="text-center" style="width:90px;">حذف</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($lines as $i=>$ln):
                $it = $items_map[(int)$ln['item_id']] ?? ['name'=>'#'.$ln['item_id']];
                $ln_unit_id = (int)($ln['unit_id'] ?? 0);
              ?>
                <tr>
                  <td class="fw-semibold"><?= e($it['name']) ?></td>

                  <td>
                      <select class="form-select form-select-sm" name="unit_id" form="lineForm<?= (int)$i ?>">
                        <option value="0">- افتراضي -</option>
                        <?php foreach ($units as $u): ?>
                          <option value="<?= (int)$u['id'] ?>" <?= ((int)$u['id']===$ln_unit_id)?'selected':'' ?>>
                            <?= e($u['name']) ?><?= $u['symbol'] ? ' (' . e($u['symbol']) . ')' : '' ?>
                          </option>
                        <?php endforeach; ?>
                      </select>
                  </td>

                  <td class="text-center">
                      <input class="form-control form-control-sm text-center js-decimal-input" type="number" step="0.001" name="qty" value="<?= e(Format::qty((float)$ln['qty'], 3)) ?>" form="lineForm<?= (int)$i ?>" data-decimals="3">
                  </td>

                  <td class="text-end">
                      <span class="fw-semibold"><?= e(Format::qty((float)($ln['unit_cost'] ?? 0), 2)) ?></span>
                  </td>

                  <td class="text-center">
                      <form method="post" action="<?= e(url('/inventory/stock-voucher')) ?>" class="m-0" id="lineForm<?= (int)$i ?>">
                        <?= csrf_input() ?>
                        <input type="hidden" name="action" value="update_line">
                        <input type="hidden" name="i" value="<?= (int)$i ?>">
                        <button class="btn btn-sm btn-outline-success" title="حفظ"><i class="fa-solid fa-floppy-disk"></i></button>
                      </form>
                  </td>

                  <td class="text-center">
                    <form method="post" action="<?= e(url('/inventory/stock-voucher')) ?>" class="m-0" onsubmit="return confirm('حذف السطر؟')">
                      <?= csrf_input() ?>
                      <input type="hidden" name="action" value="remove_line">
                      <input type="hidden" name="i" value="<?= (int)$i ?>">
                      <button class="btn btn-sm btn-outline-danger"><i class="fa-solid fa-trash"></i></button>
                    </form>
                  </td>
                </tr>
              <?php endforeach; ?>
              <?php if (!$lines): ?>
                <tr><td colspan="6" class="text-center text-muted py-5">لا توجد بنود — ابدأ بإضافة بند من الأعلى</td></tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>

      <div class="card-footer text-muted small">
        ملاحظة: الصرف/الهالك/التحويل يتحقق من الرصيد قبل الترحيل.
      </div>
    </div>
  </div>
</div>

<script>
(function(){
  // show/hide to warehouse select
  var docType = <?= json_encode($doc_type) ?>;
  var wrap = document.getElementById('toWhWrap');
  if(wrap){
    if(docType === 'TRANSFER') wrap.classList.remove('d-none');
    else wrap.classList.add('d-none');
  }
})();
</script>

<script>
(function(){
  function normalize(el){
    const decimals = Math.max(0, parseInt(el.dataset.decimals || '3', 10));
    const raw = String(el.value ?? '').trim();
    if (raw === '') return;
    const num = Number(raw);
    if (!Number.isFinite(num)) return;
    const fixed = num.toFixed(decimals);
    el.value = fixed.replace(/\.0+$/, '').replace(/(\.\d*?[1-9])0+$/, '$1');
  }
  document.querySelectorAll('.js-decimal-input').forEach(function(el){
    el.addEventListener('focus', function(){ normalize(el); });
    el.addEventListener('change', function(){ normalize(el); });
    el.addEventListener('blur', function(){ normalize(el); });
    normalize(el);
  });
})();
</script>

<style>
  .suggest-box{
    position:absolute; inset-inline-start:0; inset-inline-end:0; top:100%;
    z-index:9999; background:#fff; border:1px solid #e5e7eb; border-radius:12px;
    box-shadow:0 10px 30px rgba(0,0,0,.10); max-height:260px; overflow:auto; margin-top:6px;
  }
  .suggest-item{ padding:10px 12px; cursor:pointer; border-bottom:1px solid #f1f5f9; }
  .suggest-item:hover,.suggest-item.active{ background:#f8fafc; }
  .suggest-item .meta{ display:block; font-size:.82rem; color:#6b7280; margin-top:2px; }
</style>

<script>
(function(){
  const input = document.getElementById('voucher_item_query');
  const hidden = document.getElementById('voucher_item_id');
  const box = document.getElementById('voucher_item_suggest');
  const qty = document.querySelector('form input[name="qty"]');
  const items = <?= json_encode(array_values(array_map(static function($it){ return [
    'id' => (int)($it['id'] ?? 0),
    'name' => (string)($it['name'] ?? ''),
    'barcode' => (string)($it['barcode'] ?? ''),
    'text' => trim((string)($it['name'] ?? '') . (!empty($it['barcode']) ? ' - ' . (string)$it['barcode'] : '')),
  ]; }, $items)), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
  let timer = null;

  function norm(v){ return String(v || '').toLowerCase().replace(/[%\s\-_]+/g, ''); }
  function tokens(v){ return String(v || '').toLowerCase().split(/[%\s\-_]+/).map(s => s.trim()).filter(Boolean); }
  function orderedContains(haystack, queryTokens){
    if (!queryTokens.length) return true;
    haystack = norm(haystack);
    let offset = 0;
    for (const t of queryTokens) {
      const token = norm(t);
      const idx = haystack.indexOf(token, offset);
      if (idx === -1) return false;
      offset = idx + token.length;
    }
    return true;
  }
  function localMatch(name, barcode, query){
    if (!query) return true;
    const qNorm = norm(query);
    const tks = tokens(query);
    const n = norm(name);
    const b = norm(barcode);
    return n.includes(qNorm) || b.includes(qNorm) || orderedContains(n, tks) || orderedContains(b, tks);
  }
  function escapeHtml(v){
    return String(v ?? '').replace(/[&<>"']/g, function(ch){
      return ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'})[ch];
    });
  }
  function hide(){ if (box) { box.style.display='none'; box.innerHTML=''; box.dataset.activeIndex='-1'; } }
  function pick(item){
    if (!item) return;
    hidden.value = String(item.id || '');
    input.value = item.name || item.text || '';
    hide();
    qty?.focus();
    qty?.select?.();
  }
  function render(rows){
    if (!box) return;
    if (!Array.isArray(rows) || !rows.length) { hide(); return; }
    box.innerHTML = rows.map(function(it, idx){
      const barcode = it.barcode ? '<span class="meta">' + escapeHtml(it.barcode) + '</span>' : '';
      return '<div class="suggest-item' + (idx === 0 ? ' active' : '') + '" data-id="' + escapeHtml(it.id) + '" data-name="' + escapeHtml(it.name || it.text || '') + '"><span>' + escapeHtml(it.name || it.text || '') + '</span>' + barcode + '</div>';
    }).join('');
    box.style.display = 'block';
    box.dataset.activeIndex = '0';
  }
  function setActive(next){
    const nodes = Array.from(box.querySelectorAll('.suggest-item'));
    if (!nodes.length) return;
    let idx = parseInt(box.dataset.activeIndex || '0', 10);
    idx = Math.max(0, Math.min(nodes.length - 1, next));
    nodes.forEach((node, i) => node.classList.toggle('active', i === idx));
    nodes[idx].scrollIntoView({block:'nearest'});
    box.dataset.activeIndex = String(idx);
  }
  function localRows(query){
    return items.filter(it => localMatch(it.name, it.barcode, query)).slice(0, 12);
  }
  async function remoteRows(query){
    const res = await fetch(<?= json_encode(url('/ajax/items/search')) ?> + '?q=' + encodeURIComponent(query), {headers:{'X-Requested-With':'XMLHttpRequest'}});
    const rows = await res.json();
    if (!Array.isArray(rows)) return [];
    return rows.map(r => ({id:r.id, name:r.name || r.text || '', barcode:r.barcode || '', text:r.text || r.name || ''}));
  }
  if (!input || !hidden || !box) return;

  input.addEventListener('input', function(){
    clearTimeout(timer);
    const q = input.value.trim();
    hidden.value = '';
    if (!q) { hide(); return; }
    const local = localRows(q);
    render(local);
    timer = setTimeout(async function(){
      try {
        const remote = await remoteRows(q);
        if (remote.length) render(remote);
      } catch (e) {}
    }, 180);
  });

  input.addEventListener('keydown', function(e){
    const nodes = Array.from(box.querySelectorAll('.suggest-item'));
    if (e.key === 'ArrowDown' && nodes.length) { e.preventDefault(); setActive(parseInt(box.dataset.activeIndex || '0', 10) + 1); return; }
    if (e.key === 'ArrowUp' && nodes.length) { e.preventDefault(); setActive(parseInt(box.dataset.activeIndex || '0', 10) - 1); return; }
    if (e.key === 'Enter') {
      if (nodes.length) {
        e.preventDefault();
        const idx = parseInt(box.dataset.activeIndex || '0', 10);
        const node = nodes[Math.max(0, Math.min(nodes.length - 1, idx))];
        pick({id: node.dataset.id, name: node.dataset.name});
      }
    }
  });

  box.addEventListener('click', function(e){
    const el = e.target.closest('.suggest-item');
    if (!el) return;
    pick({id: el.dataset.id, name: el.dataset.name});
  });

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