<?php $title='القطع'; include __DIR__.'/../layout/header.php'; ?>
<style>
.items-page{display:grid;gap:18px}.items-hero{padding:18px;border-radius:26px;background:linear-gradient(135deg,#fff,#fbf7f2);border:1px solid #eadfd5;box-shadow:0 12px 30px rgba(17,24,39,.05)}.items-head{display:flex;justify-content:space-between;align-items:flex-start;gap:16px;flex-wrap:wrap;margin-bottom:16px}.items-title h2{margin:0;font-size:28px}.items-title p{margin:6px 0 0;color:#6b7280}.items-actions{display:flex;gap:10px;flex-wrap:wrap}.items-filters{display:grid;grid-template-columns:2fr 1fr 1fr auto;gap:12px}.items-stats{display:flex;gap:10px;flex-wrap:wrap;margin-top:16px}.items-chip{background:#fff;border:1px solid #eadfd5;border-radius:999px;padding:9px 14px;font-weight:700;color:#6b7280}.items-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:16px}.item-card{background:#fff;border:1px solid #eadfd5;border-radius:24px;box-shadow:0 10px 26px rgba(17,24,39,.05);overflow:hidden;display:flex;flex-direction:column}.item-media{position:relative;background:#f6efe8;aspect-ratio:4/3;display:flex;align-items:center;justify-content:center}.item-media img{width:100%;height:100%;object-fit:cover;display:block;cursor:pointer}.item-media .placeholder{font-weight:700;color:#8b6f56}.item-badge{position:absolute;top:12px;right:12px;border-radius:999px;padding:6px 10px;font-size:12px;font-weight:700;border:1px solid transparent}.status-available{background:#dcfce7;color:#166534;border-color:#86efac}.status-reserved{background:#fef3c7;color:#92400e;border-color:#fcd34d}.status-rented{background:#dbeafe;color:#1d4ed8;border-color:#93c5fd}.status-maintenance{background:#fee2e2;color:#991b1b;border-color:#fca5a5}.status-missing{background:#f3e8ff;color:#7e22ce;border-color:#d8b4fe}.status-sold{background:#e5e7eb;color:#374151;border-color:#cbd5e1}.item-content{padding:16px;display:grid;gap:12px}.item-top{display:flex;justify-content:space-between;gap:10px;align-items:flex-start}.item-code{font-size:24px;font-weight:800;line-height:1.1;color:#1f2937}.item-name{font-size:14px;color:#6b7280;margin-top:4px}.item-price{font-weight:800;color:#5e3b23;font-size:16px}.item-meta{display:grid;grid-template-columns:repeat(2,1fr);gap:10px}.meta-card{background:#faf7f4;border:1px solid #efe4da;border-radius:16px;padding:10px}.meta-card .labelx{font-size:12px;color:#8b7a6b;margin-bottom:4px}.meta-card .valuex{font-weight:800}.item-actions{display:grid;grid-template-columns:repeat(2,1fr);gap:10px}.item-actions .btn{justify-content:center}.items-empty{display:none;background:#fff;border:1px dashed #d6c4b4;border-radius:22px;padding:26px;text-align:center;color:#7a5d47}.pagination-wrap{display:flex;justify-content:center;align-items:center;gap:8px;flex-wrap:wrap}.pagination-wrap .page-indicator{padding:0 8px;font-weight:700;color:#6b7280}.gallery-modal{position:fixed;inset:0;background:rgba(15,23,42,.72);display:none;align-items:center;justify-content:center;padding:18px;z-index:1200}.gallery-modal.open{display:flex}.gallery-box{background:#fff;border-radius:24px;max-width:960px;width:min(100%,960px);padding:16px;position:relative}.gallery-main{width:100%;height:min(70vh,540px);object-fit:contain;background:#f8fafc;border-radius:18px;border:1px solid #e5e7eb}.gallery-thumbs{display:flex;gap:10px;overflow:auto;margin-top:12px;padding-bottom:6px}.gallery-thumbs img{width:88px;height:88px;border-radius:14px;object-fit:cover;border:2px solid transparent;cursor:pointer}.gallery-thumbs img.active{border-color:#5e3b23}.bulk-toolbar{display:flex;gap:10px;flex-wrap:wrap;align-items:center;margin-top:12px}.select-badge{font-weight:700;color:#6b7280}
@media (max-width:980px){.items-filters{grid-template-columns:1fr 1fr}}
@media (max-width:680px){.items-title h2{font-size:24px}.items-filters{grid-template-columns:1fr}.item-actions{grid-template-columns:1fr}}
</style>
<?php $statusMap=['available'=>'متاحة','reserved'=>'محجوزة','rented'=>'مؤجرة','maintenance'=>'صيانة','missing'=>'مفقودة','sold'=>'مباعة']; ?>
<div class="items-page">
  <div class="items-hero">
    <div class="items-head"><div class="items-title"><h2>القطع والباركود</h2><p>عرض متناسق للقطع مع الصور، الفلاتر، والطباعة الفردية أو الجماعية للباركود.</p></div><div class="items-actions"><a class="btn light" href="<?= e(base_url('?page=categories')) ?>">الفئات</a><a class="btn light" href="<?= e(base_url('?page=locations')) ?>">المواقع / الرفوف</a><a class="btn secondary" href="<?= e(base_url('?page=item_create')) ?>">+ إضافة قطعة جديدة</a></div></div>
    <form method="get" onsubmit="return false;" class="items-filters"><input type="hidden" name="page" value="items"><input class="input" id="liveSearch" name="q" value="<?= e($filters['q'] ?? '') ?>" placeholder="بحث برقم القطعة أو الاسم أو الفئة"><select class="select" id="liveCategory" name="category_id"><option value="">كل الفئات</option><?php foreach(($categories ?? []) as $c): ?><option value="<?= (int)$c['id'] ?>" <?= (($filters['category_id'] ?? '')==$c['id'])?'selected':'' ?>><?= e($c['name_ar']) ?></option><?php endforeach; ?></select><select class="select" id="liveStatus" name="status"><option value="">كل الحالات</option><?php foreach($statusMap as $k=>$v): ?><option value="<?= e($k) ?>" <?= (($filters['status'] ?? '')===$k)?'selected':'' ?>><?= e($v) ?></option><?php endforeach; ?></select><button type="button" class="btn light" id="clearFiltersBtn">إعادة التعيين</button></form>
    <div class="items-stats"><div class="items-chip">عدد النتائج: <span id="resultsCount"><?= count($items ?? []) ?></span></div><div class="items-chip">في الصفحة: 12 بطاقة</div><div class="items-chip">المحدد: <span id="selectedCount">0</span></div></div>
    <div class="bulk-toolbar"><button type="button" class="btn light" id="toggleSelectVisibleBtn">تحديد الظاهر</button><button type="button" class="btn secondary" id="printSelectedBtn">طباعة المحدد</button><button type="button" class="btn light" id="printVisibleBtn">طباعة الظاهر حسب الفلتر</button></div>
  </div>
  <div class="items-grid" id="itemCardGrid">
    <?php foreach(($items ?? []) as $row): $images=[]; if(!empty($row['images_json'])){$decoded=json_decode((string)$row['images_json'],true); if(is_array($decoded)) $images=$decoded;} if(!$images && !empty($row['primary_image'])) $images=[$row['primary_image']]; $imageUrls=array_values(array_map('file_url',$images)); $img=!empty($imageUrls[0]) ? $imageUrls[0] : ''; $catName=(string)($row['category_name'] ?? ''); $itemType=(string)($row['item_type'] ?? ''); $typeLabel=$itemType==='rental'?'إيجار فقط':($itemType==='sale'?'بيع فقط':'إيجار أو بيع'); $statusCode=(string)($row['item_status'] ?? ''); $statusLabel=$statusMap[$statusCode] ?? $statusCode; ?>
      <div class="item-card js-item-card" data-id="<?= (int)$row['id'] ?>" data-search="<?= e(mb_strtolower(trim(($row['item_code'] ?? '') . ' ' . ($row['item_name'] ?? '') . ' ' . $catName))) ?>" data-category="<?= e((string)($row['category_id'] ?? '')) ?>" data-status="<?= e($statusCode) ?>">
        <div class="item-media"><?php if($img): ?><img class="js-open-gallery" src="<?= e($img) ?>" alt="<?= e($row['item_code']) ?>" data-images='<?= e(json_encode($imageUrls, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES)) ?>' data-title="<?= e(trim(($row['item_code'] ?? '').' '.($row['item_name'] ?? ''))) ?>"><?php else: ?><div class="placeholder">بدون صورة</div><?php endif; ?><span class="item-badge status-<?= e($statusCode) ?>"><?= e($statusLabel) ?></span></div>
        <div class="item-content">
          <div class="item-top"><div><div style="display:flex;gap:8px;align-items:center"><input type="checkbox" class="item-select" value="<?= (int)$row['id'] ?>"><div class="item-code"><?= e($row['item_code']) ?></div></div><div class="item-name"><?= e($row['item_name'] ?: ($catName ?: 'بدون اسم')) ?></div></div><div class="item-price"><?= e(number_format((float)($row['default_price'] ?? 0),3)) ?></div></div>
          <div class="item-meta"><div class="meta-card"><div class="labelx">الفئة</div><div class="valuex"><?= e($catName ?: '-') ?></div></div><div class="meta-card"><div class="labelx">النوع</div><div class="valuex"><?= e($typeLabel) ?></div></div><div class="meta-card"><div class="labelx">الموقع</div><div class="valuex"><?= e($row['location_name'] ?: '-') ?></div></div><div class="meta-card"><div class="labelx">عدد الصور</div><div class="valuex"><?= count($imageUrls) ?></div></div></div>
          <div class="item-actions"><a class="btn light" href="<?= e(base_url('?page=item_edit&id='.(int)$row['id'])) ?>">تعديل</a><form method="post" action="<?= e(base_url('?page=item_delete')) ?>" onsubmit="return confirm('تأكيد حذف/تعطيل القطعة؟')"><input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>"><input type="hidden" name="id" value="<?= (int)$row['id'] ?>"><button class="btn danger" style="width:100%">حذف</button></form><a class="btn secondary" href="<?= e(base_url('?page=item_barcode&id='.(int)$row['id'])) ?>">طباعة QR</a><a class="btn light" href="<?= e(base_url('?page=item_public&id='.(int)$row['id'])) ?>">المواعيد</a></div>
        </div>
      </div>
    <?php endforeach; ?>
  </div>
  <div class="items-empty" id="itemsEmptyState">لا توجد نتائج مطابقة للفلاتر الحالية.</div>
  <div class="pagination-wrap" id="paginationWrap"><button type="button" class="btn light" id="prevPageBtn">السابق</button><span class="page-indicator" id="pageIndicator">1 / 1</span><button type="button" class="btn light" id="nextPageBtn">التالي</button></div>
</div>
<div class="gallery-modal" id="galleryModal"><div class="gallery-box"><button class="btn light" type="button" id="galleryClose" style="position:absolute;top:10px;left:10px">إغلاق</button><img src="" alt="" class="gallery-main" id="galleryMain"><div class="gallery-thumbs" id="galleryThumbs"></div></div></div>
<script>
(function(){const searchInput=document.getElementById('liveSearch'),catSelect=document.getElementById('liveCategory'),statusSelect=document.getElementById('liveStatus'),clearBtn=document.getElementById('clearFiltersBtn'),cards=Array.from(document.querySelectorAll('.js-item-card')),emptyState=document.getElementById('itemsEmptyState'),resultsCount=document.getElementById('resultsCount'),prevBtn=document.getElementById('prevPageBtn'),nextBtn=document.getElementById('nextPageBtn'),pageIndicator=document.getElementById('pageIndicator'),selectedCount=document.getElementById('selectedCount'),toggleSelectVisibleBtn=document.getElementById('toggleSelectVisibleBtn'),printSelectedBtn=document.getElementById('printSelectedBtn'),printVisibleBtn=document.getElementById('printVisibleBtn'); const perPage=12; let currentPage=1, filtered=cards.slice(); function visiblePageCards(){ return filtered.slice((currentPage-1)*perPage, (currentPage-1)*perPage+perPage); } function updateSelectedCount(){ selectedCount.textContent=String(document.querySelectorAll('.item-select:checked').length); } function applyFilters(resetPage=true){ if(resetPage) currentPage=1; const q=(searchInput.value||'').trim().toLowerCase(), c=catSelect.value||'', s=statusSelect.value||''; filtered=cards.filter(card=>{ const matchQ=!q || (card.dataset.search||'').toLowerCase().includes(q); const matchC=!c || (card.dataset.category||'')===c; const matchS=!s || (card.dataset.status||'')===s; return matchQ&&matchC&&matchS;}); renderPage(); } function renderPage(){ cards.forEach(c=>c.style.display='none'); const total=filtered.length, totalPages=Math.max(1, Math.ceil(total/perPage)); if(currentPage>totalPages) currentPage=totalPages; visiblePageCards().forEach(c=>c.style.display=''); emptyState.style.display=total===0?'block':'none'; resultsCount.textContent=String(total); pageIndicator.textContent=`${currentPage} / ${totalPages}`; prevBtn.disabled=currentPage<=1; nextBtn.disabled=currentPage>=totalPages; } searchInput.addEventListener('input',()=>applyFilters(true)); catSelect.addEventListener('change',()=>applyFilters(true)); statusSelect.addEventListener('change',()=>applyFilters(true)); clearBtn.addEventListener('click',()=>{searchInput.value='';catSelect.value='';statusSelect.value='';applyFilters(true);}); prevBtn.addEventListener('click',()=>{if(currentPage>1){currentPage--;renderPage();}}); nextBtn.addEventListener('click',()=>{const totalPages=Math.max(1,Math.ceil(filtered.length/perPage)); if(currentPage<totalPages){currentPage++;renderPage();}}); document.querySelectorAll('.item-select').forEach(ch=>ch.addEventListener('change', updateSelectedCount)); toggleSelectVisibleBtn.addEventListener('click',()=>{const visible=visiblePageCards(); const shouldCheck=visible.some(c=>!c.querySelector('.item-select').checked); visible.forEach(c=>{c.querySelector('.item-select').checked=shouldCheck;}); updateSelectedCount();}); printSelectedBtn.addEventListener('click',()=>{const ids=Array.from(document.querySelectorAll('.item-select:checked')).map(x=>x.value); if(!ids.length){alert('اختر قطعة واحدة على الأقل'); return;} window.open(`<?= e(base_url('?page=item_barcodes_bulk')) ?>&ids=${encodeURIComponent(ids.join(','))}`,'_blank');}); printVisibleBtn.addEventListener('click',()=>{const ids=visiblePageCards().map(c=>c.dataset.id); if(!ids.length){alert('لا توجد قطع ظاهرة للطباعة'); return;} window.open(`<?= e(base_url('?page=item_barcodes_bulk')) ?>&ids=${encodeURIComponent(ids.join(','))}`,'_blank');}); const modal=document.getElementById('galleryModal'), main=document.getElementById('galleryMain'), thumbs=document.getElementById('galleryThumbs'), closeBtn=document.getElementById('galleryClose'); function openGallery(images,title){ if(!images||!images.length) return; main.src=images[0]; main.alt=title||''; thumbs.innerHTML=''; images.forEach((src,idx)=>{const img=document.createElement('img'); img.src=src; img.alt=title||''; if(idx===0) img.classList.add('active'); img.addEventListener('click',()=>{main.src=src; thumbs.querySelectorAll('img').forEach(x=>x.classList.remove('active')); img.classList.add('active');}); thumbs.appendChild(img);}); modal.classList.add('open'); } document.querySelectorAll('.js-open-gallery').forEach(img=>img.addEventListener('click',()=>{let images=[]; try{images=JSON.parse(img.dataset.images||'[]');}catch(e){} openGallery(images,img.dataset.title||'');})); closeBtn.addEventListener('click',()=>modal.classList.remove('open')); modal.addEventListener('click',(e)=>{if(e.target===modal) modal.classList.remove('open');}); applyFilters(true); updateSelectedCount();})();
</script>
<?php include __DIR__.'/../layout/footer.php'; ?>