<?php
$title = ($mode === 'edit' ? 'تعديل القطعة' : 'إضافة قطعة جديدة');
include __DIR__.'/../layout/header.php';
$existingImages = [];
if (!empty($item['images_json'])) {
  $decoded = json_decode((string)$item['images_json'], true);
  if (is_array($decoded)) $existingImages = $decoded;
}
if (!$existingImages && !empty($item['primary_image'])) $existingImages = [$item['primary_image']];
$primaryImage = $item['primary_image'] ?? ($existingImages[0] ?? '');
?>
<style>
.item-form-wrap{max-width:1080px;margin:0 auto}
.item-form-grid{display:grid;grid-template-columns:repeat(12,1fr);gap:16px}
.item-form-grid .col-6{grid-column:span 6}
.item-form-grid .col-4{grid-column:span 4}
.item-form-grid .col-3{grid-column:span 3}
.item-form-grid .col-12{grid-column:span 12}
@media(max-width:860px){
  .item-form-grid .col-6,.item-form-grid .col-4,.item-form-grid .col-3,.item-form-grid .col-12{grid-column:1/-1}
}
.actions{display:flex;gap:10px;flex-wrap:wrap;margin-top:8px}
.hint{font-size:12px;color:#8b7a6b}
.drop-zone{border:2px dashed #d9c6b3;border-radius:20px;background:#fcfaf8;padding:18px;text-align:center;cursor:pointer;transition:.18s}
.drop-zone.drag{background:#f7f1ea;border-color:#7a5d47}
.preview-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:14px;margin-top:14px}
.preview-card{background:#fff;border:1px solid #eadfd5;border-radius:18px;padding:12px;display:grid;gap:10px}
.preview-card img{width:100%;height:140px;object-fit:cover;border-radius:14px;background:#f6efe8}
.preview-actions{display:flex;gap:8px;align-items:center;justify-content:space-between}
.preview-existing{border-color:#dbeafe;background:#f8fbff}
.preview-remove{cursor:pointer}
.lightbox{position:fixed;inset:0;background:rgba(15,23,42,.72);display:none;align-items:center;justify-content:center;padding:18px;z-index:1200}
.lightbox.open{display:flex}
.lightbox-box{background:#fff;border-radius:24px;max-width:960px;width:min(100%,960px);padding:16px;position:relative}
.lightbox-main{width:100%;height:min(70vh,540px);object-fit:contain;background:#f8fafc;border-radius:18px;border:1px solid #e5e7eb}
.lightbox-thumbs{display:flex;gap:10px;overflow:auto;margin-top:12px;padding-bottom:6px}
.lightbox-thumbs img{width:88px;height:88px;border-radius:14px;object-fit:cover;border:2px solid transparent;cursor:pointer}
.lightbox-thumbs img.active{border-color:#5e3b23}
</style>

<div class="item-form-wrap">
  <div class="card">
    <div style="display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap">
      <div>
        <h2 style="margin:0 0 6px"><?= $mode === 'edit' ? 'تعديل بيانات القطعة' : 'إضافة قطعة جديدة' ?></h2>
        <div class="muted">يمكنك إضافة قطعة جديدة أو تعديل بيانات قطعة موجودة مع دعم الصور حتى 5 صور واختيار الصورة الرئيسية.</div>
      </div>
      <a class="btn light" href="<?= e(base_url('?page=items')) ?>">العودة إلى القطع</a>
    </div>
  </div>

  <form class="card" method="post" enctype="multipart/form-data" action="<?= e(base_url($mode === 'edit' ? '?page=item_update' : '?page=item_store')) ?>" id="itemForm">
    <input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>">
    <?php if($mode === 'edit'): ?>
      <input type="hidden" name="id" value="<?= (int)$item['id'] ?>">
    <?php endif; ?>
    <input type="hidden" name="primary_image_choice" id="primaryImageChoice" value="<?= e((string)$primaryImage) ?>">

    <div class="item-form-grid">
      <div class="col-4">
        <label class="label">الفئة <span style="color:#b42318">*</span></label>
        <select class="select" name="category_id" required>
          <option value="">اختر الفئة</option>
          <?php foreach(($categories ?? []) as $c): ?>
            <option value="<?= (int)$c['id'] ?>" <?= (int)($item['category_id'] ?? 0) === (int)$c['id'] ? 'selected' : '' ?>><?= e($c['name_ar']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>

      <div class="col-4">
        <label class="label">رقم / كود القطعة <span style="color:#b42318">*</span></label>
        <input class="input" type="text" name="item_code" value="<?= e((string)($item['item_code'] ?? '')) ?>" required placeholder="مثال: 1A أو B-12">
      </div>

      <div class="col-4">
        <label class="label">اسم القطعة</label>
        <input class="input" type="text" name="item_name" value="<?= e((string)($item['item_name'] ?? '')) ?>" placeholder="اسم إضافي اختياري">
      </div>

      <div class="col-3">
        <label class="label">السعر الافتراضي</label>
        <input class="input" type="number" step="0.001" min="0" name="default_price" value="<?= e(number_format((float)($item['default_price'] ?? 0), 3, '.', '')) ?>">
      </div>

      <div class="col-3">
        <label class="label">نوع القطعة</label>
        <select class="select" name="item_type">
          <option value="rental" <?= (($item['item_type'] ?? '')==='rental')?'selected':'' ?>>إيجار فقط</option>
          <option value="sale" <?= (($item['item_type'] ?? '')==='sale')?'selected':'' ?>>بيع فقط</option>
          <option value="rental_or_sale" <?= (($item['item_type'] ?? '')==='rental_or_sale')?'selected':'' ?>>إيجار أو بيع</option>
        </select>
      </div>

      <div class="col-3">
        <label class="label">الحالة</label>
        <select class="select" name="item_status">
          <?php foreach(['available'=>'متاحة','reserved'=>'محجوزة','rented'=>'مؤجرة','maintenance'=>'صيانة','missing'=>'مفقودة','sold'=>'مباعة'] as $k=>$v): ?>
            <option value="<?= e($k) ?>" <?= (($item['item_status'] ?? '')===$k)?'selected':'' ?>><?= e($v) ?></option>
          <?php endforeach; ?>
        </select>
      </div>

      <div class="col-3">
        <label class="label">الموقع</label>
        <select class="select" name="location_id">
          <option value="">بدون موقع</option>
          <?php foreach(($locations ?? []) as $loc): ?>
            <option value="<?= (int)$loc['id'] ?>" <?= (int)($item['location_id'] ?? 0) === (int)$loc['id'] ? 'selected' : '' ?>><?= e($loc['name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>

      <div class="col-6">
        <label class="label">قيمة الباركود</label>
        <input class="input" type="text" name="barcode_value" value="<?= e((string)($item['barcode_value'] ?? '')) ?>" placeholder="اختياري، ويمكن تركه فارغًا">
        <div class="hint">في حال تركه فارغًا، يبقى QR المرتبط بصفحة المواعيد متاحًا عبر زر الطباعة الحالي.</div>
      </div>

      <div class="col-6" style="display:flex;align-items:center;gap:10px;padding-top:30px">
        <label style="display:flex;align-items:center;gap:10px;font-weight:700">
          <input type="checkbox" name="is_active" value="1" <?= !empty($item['is_active']) ? 'checked' : '' ?>>
          القطعة مفعلة
        </label>
      </div>

      <div class="col-12">
        <label class="label">صور القطعة (حتى 5 صور)</label>
        <div class="drop-zone" id="dropZone">
          <strong>اسحب الصور وأفلتها هنا</strong>
          <div class="muted" style="margin-top:6px">أو اضغط لاختيار الصور من جهازك. يمكنك رفع 5 صور كحد أقصى وتحديد صورة رئيسية.</div>
          <input type="file" id="imageInput" name="item_images[]" accept="image/*" multiple hidden>
          <button class="btn light" type="button" id="pickImagesBtn" style="margin-top:10px">اختيار الصور</button>
        </div>

        <?php foreach($existingImages as $imgPath): ?>
          <input type="hidden" name="existing_images[]" value="<?= e($imgPath) ?>">
        <?php endforeach; ?>

        <div class="preview-grid" id="previewGrid">
          <?php foreach($existingImages as $imgPath): ?>
            <?php $full = file_url($imgPath); ?>
            <div class="preview-card preview-existing" data-existing="1" data-src="<?= e($imgPath) ?>">
              <img src="<?= e($full) ?>" alt="img" class="js-preview-open" data-full="<?= e($full) ?>">
              <div class="preview-actions">
                <label style="display:flex;align-items:center;gap:6px;font-size:12px">
                  <input type="radio" name="primary_image_selector" value="<?= e($imgPath) ?>" <?= ((string)$primaryImage === (string)$imgPath) ? 'checked' : '' ?>>
                  رئيسية
                </label>
                <label class="preview-remove" style="font-size:12px;color:#b42318">
                  <input type="checkbox" name="remove_existing_images[]" value="<?= e($imgPath) ?>">
                  حذف
                </label>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
        <div class="hint" style="margin-top:8px">اضغط على أي صورة لعرضها والتنقل بين باقي الصور. عند الرفع، لا تتجاوز 5 صور إجمالاً (الجديدة + الحالية غير المحذوفة).</div>
      </div>

      <div class="col-12">
        <div class="actions">
          <button class="btn secondary" type="submit"><?= $mode === 'edit' ? 'حفظ التعديلات' : 'إضافة القطعة' ?></button>
          <a class="btn light" href="<?= e(base_url('?page=items')) ?>">إلغاء</a>
        </div>
      </div>
    </div>
  </form>
</div>

<div class="lightbox" id="lightbox">
  <div class="lightbox-box">
    <button class="btn light" type="button" id="lightboxClose" style="position:absolute;top:12px;left:12px">إغلاق</button>
    <img src="" alt="" class="lightbox-main" id="lightboxMain">
    <div class="lightbox-thumbs" id="lightboxThumbs"></div>
  </div>
</div>

<script>
(function(){
  const dropZone = document.getElementById('dropZone');
  const imageInput = document.getElementById('imageInput');
  const pickImagesBtn = document.getElementById('pickImagesBtn');
  const previewGrid = document.getElementById('previewGrid');
  const primaryImageChoice = document.getElementById('primaryImageChoice');
  let newFiles = [];

  function currentExistingCount(){
    return Array.from(previewGrid.querySelectorAll('.preview-existing')).filter(card => {
      const del = card.querySelector('input[name="remove_existing_images[]"]');
      return !(del && del.checked);
    }).length;
  }

  function totalCountAfterNew(){
    return currentExistingCount() + newFiles.length;
  }

  function syncPrimaryChoice(){
    const checked = previewGrid.querySelector('input[name="primary_image_selector"]:checked');
    if (checked) primaryImageChoice.value = checked.value;
  }

  function renderNewFiles(){
    previewGrid.querySelectorAll('.preview-card[data-new="1"]').forEach(el => el.remove());

    newFiles.forEach((fileObj, idx) => {
      const card = document.createElement('div');
      card.className = 'preview-card';
      card.dataset.new = '1';

      const img = document.createElement('img');
      img.alt = 'img';
      img.className = 'js-preview-open';
      img.dataset.full = fileObj.url;
      img.src = fileObj.url;
      card.appendChild(img);

      const actions = document.createElement('div');
      actions.className = 'preview-actions';

      const left = document.createElement('label');
      left.style.display = 'flex';
      left.style.alignItems = 'center';
      left.style.gap = '6px';
      left.style.fontSize = '12px';
      left.innerHTML = `<input type="radio" name="primary_image_selector" value="new:${idx}"> رئيسية`;

      const right = document.createElement('button');
      right.type = 'button';
      right.className = 'btn light';
      right.style.padding = '6px 10px';
      right.textContent = 'إزالة';
      right.addEventListener('click', () => {
        URL.revokeObjectURL(fileObj.url);
        newFiles.splice(idx,1);
        refreshFileInput();
        renderNewFiles();
      });

      actions.appendChild(left);
      actions.appendChild(right);
      card.appendChild(actions);
      previewGrid.appendChild(card);
    });

    if (!previewGrid.querySelector('input[name="primary_image_selector"]:checked')) {
      const first = previewGrid.querySelector('input[name="primary_image_selector"]');
      if (first) first.checked = true;
    }
    syncPrimaryChoice();
  }

  function refreshFileInput(){
    const dt = new DataTransfer();
    newFiles.forEach(x => dt.items.add(x.file));
    imageInput.files = dt.files;
  }

  function addFiles(files){
    const valid = Array.from(files).filter(f => f.type.startsWith('image/'));
    const allowed = 5 - currentExistingCount() - newFiles.length;
    if (allowed <= 0) {
      alert('الحد الأقصى 5 صور فقط.');
      return;
    }
    valid.slice(0, allowed).forEach(file => {
      newFiles.push({file, url: URL.createObjectURL(file)});
    });
    refreshFileInput();
    renderNewFiles();
  }

  pickImagesBtn.addEventListener('click', () => imageInput.click());
  imageInput.addEventListener('change', (e) => addFiles(e.target.files));

  ['dragenter','dragover'].forEach(ev => dropZone.addEventListener(ev, e => {
    e.preventDefault(); e.stopPropagation(); dropZone.classList.add('drag');
  }));
  ['dragleave','drop'].forEach(ev => dropZone.addEventListener(ev, e => {
    e.preventDefault(); e.stopPropagation(); dropZone.classList.remove('drag');
  }));
  dropZone.addEventListener('drop', e => addFiles(e.dataTransfer.files));

  previewGrid.addEventListener('change', (e) => {
    if (e.target.name === 'primary_image_selector' || e.target.name === 'remove_existing_images[]') {
      syncPrimaryChoice();
    }
  });

  const lightbox = document.getElementById('lightbox');
  const main = document.getElementById('lightboxMain');
  const thumbs = document.getElementById('lightboxThumbs');
  const lightboxClose = document.getElementById('lightboxClose');

  function collectGalleryImages(){
    return Array.from(previewGrid.querySelectorAll('img.js-preview-open')).map(img => img.dataset.full || img.src).filter(Boolean);
  }

  function openLightbox(startSrc){
    const images = collectGalleryImages();
    if (!images.length) return;
    let current = images.indexOf(startSrc);
    if (current < 0) current = 0;

    function render(idx){
      current = idx;
      main.src = images[current];
      thumbs.innerHTML = '';
      images.forEach((src,i) => {
        const t = document.createElement('img');
        t.src = src;
        if (i === current) t.classList.add('active');
        t.addEventListener('click', () => render(i));
        thumbs.appendChild(t);
      });
      thumbs.children[current]?.scrollIntoView({inline:'center',behavior:'smooth',block:'nearest'});
    }

    render(current);
    lightbox.classList.add('open');
  }

  previewGrid.addEventListener('click', (e) => {
    const img = e.target.closest('.js-preview-open');
    if (!img) return;
    openLightbox(img.dataset.full || img.src);
  });

  lightboxClose.addEventListener('click', () => lightbox.classList.remove('open'));
  lightbox.addEventListener('click', (e) => { if (e.target === lightbox) lightbox.classList.remove('open'); });

  document.getElementById('itemForm').addEventListener('submit', (e) => {
    if (totalCountAfterNew() > 5) {
      e.preventDefault();
      alert('لا يمكن حفظ أكثر من 5 صور.');
      return;
    }
    syncPrimaryChoice();
  });
})();
</script>
<?php include __DIR__.'/../layout/footer.php'; ?>
