<?php
use App\Shared\Support\Format;
$doc = $doc ?? null;
$lines = $lines ?? [];
$items = $items ?? [];
$units = $units ?? [];
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h5 class="mb-1">مستند افتتاحي: <?= e($doc['doc_no']) ?></h5>
    <div class="text-muted small">
      المخزن: <b><?= e($doc['warehouse_name']) ?></b> — التاريخ: <b><?= e($doc['doc_date']) ?></b>
    </div>
  </div>
  <div class="d-flex gap-2">
    <?php if (($doc['status'] ?? '') === 'POSTED'): ?>
      <a class="btn btn-success" target="_blank" href="<?= e(url('/inventory/opening-stock/print?id=' . (int)$doc['id'])) ?>"><i class="fa-solid fa-print me-1"></i>طباعة</a>
    <?php endif; ?>
    <a class="btn btn-outline-secondary" href="<?= e(url('/inventory/opening-stock')) ?>"><i class="fa-solid fa-arrow-right me-1"></i>رجوع</a>
  </div>
</div>

<div class="row g-3">
  <div class="col-12">
    <div class="card shadow-sm">
      <div class="card-header"><strong>إضافة سطر</strong></div>
      <div class="card-body">
        <?php if ($doc['status'] !== 'DRAFT'): ?>
          <div class="alert alert-success mb-0">تم الترحيل — المستند للعرض فقط.</div>
        <?php else: ?>
          <form method="post" action="<?= e(url('/inventory/opening-stock')) ?>" class="vstack gap-2">
            <?= csrf_input() ?>
            <input type="hidden" name="action" value="add_line">
            <input type="hidden" name="doc_id" value="<?= (int)$doc['id'] ?>">
            <div>
              <label class="form-label">الصنف</label>
              <div class="position-relative item-picker-shell">
                <input type="text" id="item_query" class="form-control" placeholder="ابحث بالاسم أو الباركود... ثم Enter" autocomplete="off" required>
                <input type="hidden" name="item_id" id="item_id" value="" required>
                <div id="item_suggest" class="suggest-box" style="display:none;"></div>
              </div>
            </div>

            <div>
              <label class="form-label">الوحدة (اختياري)</label>
              <select class="form-select" name="unit_id">
                <option value="0">- افتراضي (وحدة الصنف الأساسية) -</option>
                <?php foreach ($units as $u): ?>
                  <option value="<?= (int)$u['id'] ?>"><?= e($u['name']) ?></option>
                <?php endforeach; ?>
              </select>
              <div class="form-text">لو اخترت كرتونة/دستة هيتم التحويل تلقائيًا للخصم/التخزين بالوحدة الأساسية.</div>
            </div>

            <div class="row g-2">
              <div class="col-6">
                <label class="form-label">الكمية</label>
                <input class="form-control js-decimal-input" type="number" step="0.001" min="0.001" name="qty" required data-decimals="3" value="0">
              </div>
              <div class="col-6">
                <label class="form-label">التكلفة (اختياري)</label>
                <input class="form-control js-decimal-input" type="number" step="0.01" min="0" name="cost" value="0" data-decimals="2">
              </div>
            </div>

            <button class="btn btn-primary"><i class="fa-solid fa-plus me-2"></i>إضافة</button>
          </form>

          <form method="post" action="<?= e(url('/inventory/opening-stock')) ?>" class="mt-3" onsubmit="return confirm('تأكيد ترحيل الافتتاحي؟ لا يمكن التعديل بعد الترحيل.')">
            <?= csrf_input() ?>
            <input type="hidden" name="action" value="post">
            <input type="hidden" name="doc_id" value="<?= (int)$doc['id'] ?>">
            <button class="btn btn-success w-100"><i class="fa-solid fa-check me-2"></i>ترحيل</button>
          </form>
        <?php endif; ?>
      </div>
    </div>
  </div>

  <div class="col-12">
    <div class="card shadow-sm">
      <div class="card-header d-flex justify-content-between align-items-center">
        <strong>أسطر المستند</strong>
        <span class="badge bg-<?= $doc['status']==='POSTED' ? 'success' : 'secondary' ?>"><?= e($doc['status']) ?></span>
      </div>
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table table-striped table-bordered align-middle mb-0">
            <thead class="table-light">
              <tr>
                <th>الصنف</th>
                <th style="width:120px;">الوحدة</th>
                <th class="text-end" style="width:140px;">الكمية</th>
                <th class="text-end" style="width:140px;">التكلفة</th>
                <th class="text-center" style="width:90px;">حفظ</th>
                <th class="text-center" style="width:90px;">حذف</th>
              </tr>
            </thead>
            <tbody>
              <?php $is_draft = ($doc['status'] === 'DRAFT'); ?>
              <?php foreach ($lines as $ln): $lid=(int)$ln['id']; ?>
                <tr>
                  <td class="fw-semibold"><?= e($ln['item_name']) ?></td>

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

                  <td class="text-end">
                    <input class="form-control form-control-sm text-end js-decimal-input" type="number" step="0.001" min="0.001"
                           name="qty" value="<?= e(Format::qty((float)($ln['qty'] ?? 0), 3)) ?>" data-decimals="3" form="upd-<?= $lid ?>" <?= $is_draft ? '' : 'readonly' ?>>
                  </td>

                  <td class="text-end">
                    <input class="form-control form-control-sm text-end js-decimal-input" type="number" step="0.01" min="0"
                           name="cost" value="<?= e(Format::qty((float)($ln['cost'] ?? 0), 2)) ?>" data-decimals="2" form="upd-<?= $lid ?>" <?= $is_draft ? '' : 'readonly' ?>>
                  </td>

                  <td class="text-center">
                    <?php if (!$is_draft): ?>
                      -
                    <?php else: ?>
                      <form id="upd-<?= $lid ?>" method="post" action="<?= e(url('/inventory/opening-stock')) ?>" class="m-0">
                        <?= csrf_input() ?>
                        <input type="hidden" name="action" value="update_line">
                        <input type="hidden" name="doc_id" value="<?= (int)$doc['id'] ?>">
                        <input type="hidden" name="line_id" value="<?= $lid ?>">
                        <button class="btn btn-sm btn-outline-success" type="submit" title="حفظ">
                          <i class="fa-solid fa-floppy-disk"></i>
                        </button>
                      </form>
                    <?php endif; ?>
                  </td>

                  <td class="text-center">
                    <?php if (!$is_draft): ?>
                      -
                    <?php else: ?>
                      <form method="post" action="<?= e(url('/inventory/opening-stock')) ?>" class="m-0" onsubmit="return confirm('حذف السطر؟')">
                        <?= csrf_input() ?>
                        <input type="hidden" name="action" value="delete_line">
                        <input type="hidden" name="doc_id" value="<?= (int)$doc['id'] ?>">
                        <input type="hidden" name="line_id" value="<?= $lid ?>">
                        <button class="btn btn-sm btn-outline-danger" type="submit" title="حذف">
                          <i class="fa-solid fa-trash"></i>
                        </button>
                      </form>
                    <?php endif; ?>
                  </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">
        الافتتاحي يُضاف كحركة <b>OPENING</b> ويؤثر مباشرة على رصيد المخزن.
      </div>
    </div>
  </div>
</div>



<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('item_query');
  const hidden = document.getElementById('item_id');
  const box = document.getElementById('item_suggest');
  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();
  }
  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>
