<?php
use App\Shared\Support\Format;
$items = $items ?? [];
$q = $q ?? '';
$page = $page ?? 1;
$per_page = $per_page ?? 25;
$total_items = $total_items ?? count($items);
$total_pages = $total_pages ?? 1;
$hasSupplierCol = $hasSupplierCol ?? false;
$mode = $mode ?? 'search';
$isCreate = $mode === 'create';
?>
<div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3">
  <div>
    <h3 class="mb-1"><?= $isCreate ? 'إضافة صنف' : 'بحث عن صنف' ?></h3>
  </div>
  <div class="d-flex gap-2">
    <a class="btn <?= $isCreate ? 'btn-dark' : 'btn-outline-dark' ?>" href="<?= e(url('/inventory/items/create')) ?>">إضافة صنف</a>
    <a class="btn <?= !$isCreate ? 'btn-dark' : 'btn-outline-dark' ?>" href="<?= e(url('/inventory/items')) ?>">بحث عن صنف</a>
  </div>
</div>

<?php if ($isCreate): ?>
<div class="card shadow-sm">
  <div class="card-header"><strong>بيانات الصنف</strong></div>
  <div class="card-body">
    <form method="post" class="row g-3">
      <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>">
      <input type="hidden" name="action" value="create">

      <div class="col-lg-6">
        <label class="form-label">اسم الصنف</label>
        <input class="form-control" name="name" required>
      </div>
      <div class="col-lg-6">
        <label class="form-label">الباركود (اختياري)</label>
        <input class="form-control" name="barcode">
      </div>
      <div class="col-lg-6">
        <label class="form-label">الفئة</label>
        <select class="form-select" name="category_id">
          <option value="0">- بدون -</option>
          <?php foreach ($categories as $c): ?>
            <option value="<?= (int)$c['id'] ?>"><?= e($c['name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-lg-6">
        <label class="form-label">الوحدة الأساسية</label>
        <select class="form-select" name="default_unit_id">
          <option value="0">- اختر -</option>
          <?php foreach ($units as $u): ?>
            <option value="<?= (int)$u['id'] ?>"><?= e($u['name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <?php if ($hasSupplierCol): ?>
      <div class="col-lg-6">
        <label class="form-label">المورد الافتراضي <span class="text-muted small">(اختياري)</span></label>
        <input type="hidden" name="default_supplier_id" value="" data-supplier-id-input>
        <div class="app-searchable-select" data-ajax-supplier-wrapper>
          <input class="form-control app-searchable-select__input" type="text" autocomplete="off" data-supplier-search-input placeholder="اكتب أول حرفين من اسم أو كود المورد...">
          <div class="app-searchable-select__results d-none" data-supplier-results></div>
        </div>
        <div class="form-text">اتركه فارغًا إذا لم يكن للصنف مورد افتراضي.</div>
      </div>
      <?php endif; ?>
      <div class="col-lg-3">
        <label class="form-label">حد إعادة الطلب</label>
        <input class="form-control js-decimal-input" data-decimals="3" type="number" step="0.001" name="reorder_point" value="0">
      </div>
      <div class="col-lg-3">
        <label class="form-label">تنبيه انخفاض المخزون</label>
        <input class="form-control js-decimal-input" data-decimals="3" type="number" step="0.001" name="low_stock_level" value="0">
      </div>
      <div class="col-lg-3">
        <label class="form-label">التكلفة</label>
        <input class="form-control js-decimal-input" data-decimals="2" name="cost" type="number" step="0.01" value="0">
      </div>
      <div class="col-lg-3">
        <label class="form-label">سعر البيع</label>
        <input class="form-control js-decimal-input" data-decimals="2" name="price" type="number" step="0.01" value="0">
      </div>
      <div class="col-lg-6">
        <label class="form-label">الماركة (اختياري)</label>
        <input class="form-control" name="brand">
      </div>
      <div class="col-lg-6">
        <label class="form-label">ملاحظات</label>
        <input class="form-control" name="notes">
      </div>
      <div class="col-12">
        <button class="btn btn-primary">حفظ الصنف</button>
      </div>
    </form>
  </div>
</div>
<?php else: ?>
<?php if (!empty($edit_item)): ?>
<div class="card shadow-sm border-0 mb-3">
  <div class="card-header bg-white d-flex justify-content-between align-items-center flex-wrap gap-2">
    <strong>تعديل الصنف #<?= (int)$edit_item['id'] ?></strong>
    <a class="btn btn-sm btn-outline-secondary" href="<?= e(url('/inventory/items')) ?>?q=<?= urlencode((string)$q) ?>&page=<?= (int)$page ?>">إغلاق التعديل</a>
  </div>
  <div class="card-body">
    <form method="post" class="row g-3">
      <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>">
      <input type="hidden" name="action" value="update">
      <input type="hidden" name="id" value="<?= (int)$edit_item['id'] ?>">

      <div class="col-lg-6">
        <label class="form-label">اسم الصنف</label>
        <input class="form-control" name="name" required value="<?= e((string)$edit_item['name']) ?>">
      </div>
      <div class="col-lg-6">
        <label class="form-label">الباركود (اختياري)</label>
        <input class="form-control" name="barcode" value="<?= e((string)($edit_item['barcode'] ?? '')) ?>">
      </div>
      <div class="col-lg-6">
        <label class="form-label">الفئة</label>
        <select class="form-select" name="category_id">
          <option value="0">- بدون -</option>
          <?php foreach ($categories as $c): ?>
            <option value="<?= (int)$c['id'] ?>" <?= (int)($edit_item['category_id'] ?? 0) === (int)$c['id'] ? 'selected' : '' ?>><?= e($c['name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-lg-6">
        <label class="form-label">الوحدة الأساسية</label>
        <select class="form-select" name="default_unit_id">
          <option value="0">- اختر -</option>
          <?php foreach ($units as $u): ?>
            <option value="<?= (int)$u['id'] ?>" <?= (int)($edit_item['default_unit_id'] ?? 0) === (int)$u['id'] ? 'selected' : '' ?>><?= e($u['name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <?php if ($hasSupplierCol): ?>
      <div class="col-lg-6">
        <label class="form-label">المورد الافتراضي <span class="text-muted small">(اختياري)</span></label>
        <input type="hidden" name="default_supplier_id" value="<?= (int)($edit_item['default_supplier_id'] ?? 0) ?>" data-supplier-id-input>
        <div class="app-searchable-select" data-ajax-supplier-wrapper>
          <input class="form-control app-searchable-select__input" type="text" autocomplete="off" data-supplier-search-input placeholder="اكتب أول حرفين من اسم أو كود المورد..." value="<?= e((string)($edit_item['supplier_name'] ?? '')) ?>">
          <div class="app-searchable-select__results d-none" data-supplier-results></div>
        </div>
        <div class="form-text">اتركه فارغًا إذا لم يكن للصنف مورد افتراضي.</div>
      </div>
      <?php endif; ?>
      <div class="col-lg-3">
        <label class="form-label">حد إعادة الطلب</label>
        <input class="form-control js-decimal-input" data-decimals="3" type="number" step="0.001" name="reorder_point" value="<?= e(Format::qty((float)($edit_item['reorder_point'] ?? 0), 3)) ?>">
      </div>
      <div class="col-lg-3">
        <label class="form-label">تنبيه انخفاض المخزون</label>
        <input class="form-control js-decimal-input" data-decimals="3" type="number" step="0.001" name="low_stock_level" value="<?= e(Format::qty((float)($edit_item['low_stock_level'] ?? 0), 3)) ?>">
      </div>
      <div class="col-lg-3">
        <label class="form-label">التكلفة</label>
        <input class="form-control js-decimal-input" data-decimals="2" name="cost" type="number" step="0.01" value="<?= e(Format::qty((float)($edit_item['cost'] ?? 0), 2)) ?>">
      </div>
      <div class="col-lg-3">
        <label class="form-label">سعر البيع</label>
        <input class="form-control js-decimal-input" data-decimals="2" name="price" type="number" step="0.01" value="<?= e(Format::qty((float)($edit_item['price'] ?? 0), 2)) ?>">
      </div>
      <div class="col-lg-6">
        <label class="form-label">الماركة (اختياري)</label>
        <input class="form-control" name="brand" value="<?= e((string)($edit_item['brand'] ?? '')) ?>">
      </div>
      <div class="col-lg-6">
        <label class="form-label">ملاحظات</label>
        <input class="form-control" name="notes" value="<?= e((string)($edit_item['notes'] ?? '')) ?>">
      </div>
      <div class="col-lg-6">
        <label class="form-label">وحدة إضافية / عبوة</label>
        <select class="form-select" name="pack_unit_id">
          <option value="0">- بدون -</option>
          <?php foreach ($units as $u): ?>
            <option value="<?= (int)$u['id'] ?>" <?= (int)($pack_info['unit_id'] ?? 0) === (int)$u['id'] ? 'selected' : '' ?>><?= e($u['name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-lg-6">
        <label class="form-label">عدد الوحدات الأساسية داخل العبوة</label>
        <input class="form-control js-decimal-input" data-decimals="3" type="number" step="0.001" name="pack_factor" value="<?= e(Format::qty((float)($pack_info['factor_to_base'] ?? 0), 3)) ?>">
      </div>
      <div class="col-12">
        <div class="form-check">
          <input class="form-check-input" type="checkbox" value="1" name="is_active" id="item-is-active" <?= (int)($edit_item['is_active'] ?? 1) === 1 ? 'checked' : '' ?>>
          <label class="form-check-label" for="item-is-active">الصنف نشط</label>
        </div>
      </div>
      <div class="col-12 d-flex gap-2">
        <button class="btn btn-primary">حفظ التعديلات</button>
        <a class="btn btn-outline-secondary" href="<?= e(url('/inventory/items')) ?>?q=<?= urlencode((string)$q) ?>&page=<?= (int)$page ?>">إلغاء</a>
      </div>
    </form>
  </div>
</div>
<?php endif; ?>

<div class="card shadow-sm border-0 mb-3">
  <div class="card-header bg-white"><strong>بحث وتصفية الأصناف</strong></div>
  <div class="card-body">
    <form class="row g-2" method="get">
      <div class="col-lg-10">
        <label class="form-label">بحث</label>
        <div class="position-relative" data-item-page-search-wrapper>
          <input class="form-control" name="q" data-item-page-search placeholder="ابحث باسم الصنف أو الباركود" value="<?= e($q) ?>" autocomplete="off">
          <div class="list-group position-absolute w-100 shadow-sm d-none" data-item-page-search-results style="z-index:20; max-height:260px; overflow:auto;"></div>
        </div>
      </div>
      <div class="col-lg-2 d-flex gap-2 align-items-end">
        <button class="btn btn-primary flex-fill">بحث</button>
        <a class="btn btn-outline-secondary" href="<?= e(url('/inventory/items')) ?>">إلغاء</a>
      </div>
    </form>
  </div>
</div>

<div class="card shadow-sm">
  <div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2"><strong>قائمة الأصناف</strong><span class="text-muted small">عرض <?= (int)$per_page ?> صنف في الصفحة — إجمالي النتائج <?= (int)$total_items ?></span></div>
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table table-bordered table-hover table-striped align-middle table-sm mb-0">
        <thead class="table-light">
          <tr>
            <th>#</th>
            <th>الصنف</th>
            <?php if ($hasSupplierCol): ?><th>المورد</th><?php endif; ?>
            <th>باركود</th>
            <th class="text-end">تكلفة</th>
            <th class="text-end">سعر</th>
            <th class="text-end">رصيد</th>
            <th>حالة</th>
            <th class="text-end">الإجراءات</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($items as $it): ?>
            <tr>
              <td><?= (int)$it['id'] ?></td>
              <td><?= e($it['name']) ?></td>
              <?php if ($hasSupplierCol): ?><td><?= e((string)($it['supplier_name'] ?? '-')) ?></td><?php endif; ?>
              <td><?= e($it['barcode'] ?? '-') ?></td>
              <td class="text-end"><?= format_money($it['cost']) ?></td>
              <td class="text-end"><?= format_money($it['price']) ?></td>
              <td class="text-end"><?= format_qty($it['qty']) ?></td>
              <td><?php if ((int)$it['is_active'] === 1): ?><span class="badge text-bg-success">نشط</span><?php else: ?><span class="badge text-bg-secondary">موقوف</span><?php endif; ?></td>
              <td class="text-end text-nowrap">
                <a class="btn btn-sm btn-outline-dark" href="<?= e(url('/inventory/items')) ?>?edit=<?= (int)$it['id'] ?>&q=<?= urlencode((string)$q) ?>&page=<?= (int)$page ?>">تعديل</a>
                <form method="post" class="d-inline" onsubmit="return confirm('تأكيد حذف الصنف؟')">
                  <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>">
                  <input type="hidden" name="action" value="delete">
                  <input type="hidden" name="id" value="<?= (int)$it['id'] ?>">
                  <button class="btn btn-sm btn-outline-danger" type="submit">حذف</button>
                </form>
              </td>
            </tr>
          <?php endforeach; ?>
          <?php if (!$items): ?>
            <tr><td colspan="<?= $hasSupplierCol ? 9 : 8 ?>" class="text-center text-muted py-4">لا توجد بيانات</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
  <?php if ($total_pages > 1): ?>
  <div class="card-footer">
    <nav>
      <ul class="pagination pagination-sm justify-content-center mb-0 flex-wrap gap-1">
        <?php $base = url('/inventory/items') . '?q=' . urlencode((string)$q) . (!empty($edit_item) ? '&edit=' . (int)$edit_item['id'] : '') . '&page='; ?>
        <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>"><a class="page-link" href="<?= e($base . max(1, $page - 1)) ?>">السابق</a></li>
        <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
          <li class="page-item <?= $i === $page ? 'active' : '' ?>"><a class="page-link" href="<?= e($base . $i) ?>"><?= (int)$i ?></a></li>
        <?php endfor; ?>
        <li class="page-item <?= $page >= $total_pages ? 'disabled' : '' ?>"><a class="page-link" href="<?= e($base . min($total_pages, $page + 1)) ?>">التالي</a></li>
      </ul>
    </nav>
  </div>
  <?php endif; ?>
</div>
<?php endif; ?>

<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>
<!-- Item page autocomplete -->

<script>
(function(){
  const wrapper = document.querySelector('[data-item-page-search-wrapper]');
  if (!wrapper || wrapper.dataset.ready === '1') return;
  wrapper.dataset.ready = '1';
  const input = wrapper.querySelector('[data-item-page-search]');
  const results = wrapper.querySelector('[data-item-page-search-results]');
  const form = wrapper.closest('form');
  const endpoint = <?= json_encode(url('/ajax/items/search'), JSON_UNESCAPED_UNICODE) ?>;
  let timer = null;

  function escapeHtml(value){
    return String(value || '').replace(/[&<>"']/g, function(ch){
      return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[ch] || ch;
    });
  }
  function close(){ results.classList.add('d-none'); results.innerHTML = ''; }
  function showMessage(message){
    results.innerHTML = '<div class="list-group-item text-muted">' + escapeHtml(message) + '</div>';
    results.classList.remove('d-none');
  }
  function render(rows){
    if (!Array.isArray(rows) || rows.length === 0) { showMessage('لا توجد أصناف مطابقة'); return; }
    results.innerHTML = rows.map(function(row){
      const name = row.name || row.text || '';
      const code = row.barcode ? ' — ' + row.barcode : '';
      return '<button type="button" class="list-group-item list-group-item-action" data-name="' + escapeHtml(name) + '"><strong>' + escapeHtml(name) + '</strong><span class="text-muted small">' + escapeHtml(code) + '</span></button>';
    }).join('');
    results.classList.remove('d-none');
  }
  function search(){
    const q = input.value.trim();
    if (q.length < 1) { close(); return; }
    showMessage('جاري البحث...');
    fetch(endpoint + '?q=' + encodeURIComponent(q), {headers:{'Accept':'application/json','X-Requested-With':'XMLHttpRequest'}})
      .then(function(resp){ return resp.ok ? resp.json() : []; })
      .then(render)
      .catch(function(){ showMessage('تعذر تحميل نتائج البحث'); });
  }

  input.addEventListener('input', function(){ clearTimeout(timer); timer = setTimeout(search, 220); });
  input.addEventListener('focus', function(){ if (input.value.trim().length >= 1) search(); });
  input.addEventListener('keydown', function(e){ if (e.key === 'Escape') close(); });
  results.addEventListener('click', function(e){
    const btn = e.target.closest('[data-name]');
    if (!btn) return;
    input.value = btn.getAttribute('data-name') || '';
    close();
    if (form) form.submit();
  });
  document.addEventListener('click', function(e){ if (!wrapper.contains(e.target)) close(); });
})();
</script>

<script>
(function(){
  const endpoint = <?= json_encode(url('/ajax/suppliers/search'), JSON_UNESCAPED_UNICODE) ?>;
  const minChars = 2;
  function escapeHtml(value){
    return String(value || '').replace(/[&<>"]/g, function(ch){
      return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[ch] || ch;
    });
  }
  function label(row){
    const code = row.code ? String(row.code) + ' - ' : '';
    const phone = row.phone ? ' | ' + String(row.phone) : '';
    return code + String(row.name || '') + phone;
  }
  function setup(wrapper){
    const input = wrapper.querySelector('[data-supplier-search-input]');
    const hidden = wrapper.closest('form')?.querySelector('[data-supplier-id-input]');
    const results = wrapper.querySelector('[data-supplier-results]');
    if (!input || !hidden || !results || wrapper.dataset.ajaxReady === '1') return;
    wrapper.dataset.ajaxReady = '1';
    let timer = null;
    let lastSelectedText = input.value || '';

    function close(){ results.classList.add('d-none'); results.innerHTML = ''; }
    function renderEmpty(message){
      results.innerHTML = '<button type="button" class="app-searchable-select__item is-empty" disabled>' + escapeHtml(message) + '</button>';
      results.classList.remove('d-none');
    }
    function renderRows(rows){
      if (!rows.length) { renderEmpty('لا توجد نتائج مطابقة'); return; }
      results.innerHTML = rows.map(function(row){
        return '<button type="button" class="app-searchable-select__item" data-id="' + escapeHtml(row.id) + '" data-label="' + escapeHtml(label(row)) + '">' + escapeHtml(label(row)) + '</button>';
      }).join('');
      results.classList.remove('d-none');
    }
    function search(){
      const q = input.value.trim();
      if (q.length < minChars) { close(); return; }
      renderEmpty('جاري البحث...');
      fetch(endpoint + '?q=' + encodeURIComponent(q), {headers: {'Accept': 'application/json'}})
        .then(function(resp){ return resp.ok ? resp.json() : []; })
        .then(function(rows){ renderRows(Array.isArray(rows) ? rows : []); })
        .catch(function(){ renderEmpty('تعذر تحميل الموردين'); });
    }

    input.addEventListener('input', function(){
      if (input.value !== lastSelectedText) hidden.value = '';
      clearTimeout(timer);
      timer = setTimeout(search, 250);
    });
    input.addEventListener('focus', function(){ if (input.value.trim().length >= minChars) search(); });
    input.addEventListener('keydown', function(e){ if (e.key === 'Escape') close(); });
    results.addEventListener('click', function(e){
      const btn = e.target.closest('.app-searchable-select__item[data-id]');
      if (!btn) return;
      hidden.value = btn.getAttribute('data-id') || '';
      lastSelectedText = btn.getAttribute('data-label') || '';
      input.value = lastSelectedText;
      close();
    });
    document.addEventListener('click', function(e){ if (!wrapper.contains(e.target)) close(); });
  }
  document.querySelectorAll('[data-ajax-supplier-wrapper]').forEach(setup);
})();
</script>
