
// Strip old listeners from app_final.js
['btn-save-manufacture', 'manufacture-items-tbody', 'manufacture-product', 'manufacture-qty', 'manufacture-warehouse'].forEach(id => {
    let oldElem = document.getElementById(id);
    if (oldElem) {
        let newElem = oldElem.cloneNode(true);
        oldElem.parentNode.replaceChild(newElem, oldElem);
    }
});

window.openManufactureModal = function() {
  document.getElementById('manufacture-date').value = new Date().toISOString().slice(0,16);
  
  const whSelect = document.getElementById('manufacture-warehouse');
  const allWhOptions = currentWarehouses.map(w => `<option value="${w.id}">${w.name}</option>`).join('');
  if (currentUser.role === 'مدير عام') { whSelect.innerHTML = allWhOptions; } 
  else {
    const myWh = currentWarehouses.find(w => w.id === currentUser.warehouse_id);
    if (myWh) whSelect.innerHTML = `<option value="${myWh.id}">${myWh.name}</option>`;
  }

  const prods = currentItems.filter(i => i.category === 'منتج تام' && i.bom && i.bom.length > 0);
  document.getElementById('manufacture-product').innerHTML = prods.length > 0 ? prods.map(p => `<option value="${p.id}">${p.name}</option>`).join('') : '<option value="">-- لا يوجد منتجات تامة لها مكونات --</option>';
  
  document.getElementById('manufacture-qty').value = 1;
  renderManufactureTable();
  showModal('manufacture-modal');
}

function renderManufactureTable() {
  const tbody = document.getElementById('manufacture-items-tbody'); tbody.innerHTML = '';
  const prodId = parseInt(document.getElementById('manufacture-product').value);
  const targetQty = parseFloat(document.getElementById('manufacture-qty').value) || 0;
  const whId = parseInt(document.getElementById('manufacture-warehouse').value);
  
  if(!prodId || targetQty <= 0) return;
  const prodDef = currentItems.find(i => String(i.id) === String(prodId));
  if(!prodDef || !prodDef.bom) return;
  
  const bomProducedQty = prodDef.bom_produced_qty || 1;
  
  (prodDef.bom || []).forEach((b, idx) => {
    const requiredQty = (b.qty / bomProducedQty) * targetQty;
    const bal = (balancesCache[b.item_id] && balancesCache[b.item_id].warehouses[whId]) || 0;
    const isOk = bal >= requiredQty;
    const status = `<span id="man-status-${idx}" style="color:${isOk?'var(--success)':'var(--danger)'}">${isOk?'متوفر':'عجز'} (${bal})</span>`;
    
    tbody.innerHTML += `<tr>
      <td>${b.item_name}</td>
      <td>${b.qty} <small>${b.unit}</small></td>
      <td>
        <div style="display:flex; align-items:center; gap:5px; justify-content:flex-end;">
          <input type="number" id="man-qty-${idx}" data-idx="${idx}" data-item="${b.item_id}" class="man-editable-qty" min="0" step="0.001" value="${requiredQty.toFixed(3)}" style="width:100px; margin:0; text-align:center;">
          <small>${b.unit}</small>
        </div>
      </td>
      <td>${status}</td>
    </tr>`;
  });
}

document.getElementById('manufacture-items-tbody').addEventListener('input', (e) => {
  if (e.target.classList.contains('man-editable-qty')) {
    const idx = e.target.getAttribute('data-idx');
    const itemId = e.target.getAttribute('data-item');
    const whId = parseInt(document.getElementById('manufacture-warehouse').value);
    const newQty = parseFloat(e.target.value) || 0;
    const bal = (balancesCache[itemId] && balancesCache[itemId].warehouses[whId]) || 0;
    const isOk = bal >= newQty;
    const statusSpan = document.getElementById(`man-status-${idx}`);
    if(statusSpan) {
      statusSpan.style.color = isOk ? 'var(--success)' : 'var(--danger)';
      statusSpan.innerText = `${isOk?'متوفر':'عجز'} (${bal})`;
    }
  }
});

document.getElementById('manufacture-product').addEventListener('change', renderManufactureTable);

document.getElementById('manufacture-qty').addEventListener('input', renderManufactureTable);

document.getElementById('manufacture-warehouse').addEventListener('change', renderManufactureTable);

document.getElementById('btn-save-manufacture').addEventListener('click', async () => {
  try {
    const prodId = parseInt(document.getElementById('manufacture-product').value);
    const targetQty = parseFloat(document.getElementById('manufacture-qty').value);
    const whId = parseInt(document.getElementById('manufacture-warehouse').value);
    const dateStr = document.getElementById('manufacture-date').value;
    
    if(!prodId || !targetQty || targetQty <= 0 || !whId || !dateStr) { alert('تأكد من إدخال جميع البيانات!'); return; }
    const prodDef = currentItems.find(i => String(i.id) === String(prodId));
    const bomProducedQty = prodDef.bom_produced_qty || 1;
    
    // Check balances from inputs
    let rawItems = [];
    let hasError = false;
    
    (prodDef.bom || []).forEach((b, idx) => {
      const inputEl = document.getElementById(`man-qty-${idx}`);
      if(!inputEl) return;
      const consumedQty = parseFloat(inputEl.value) || 0;
      if (consumedQty <= 0) return; // Skip zero usage
      
      const bal = (balancesCache[b.item_id] && balancesCache[b.item_id].warehouses[whId]) || 0;
      if(bal < consumedQty) {
        alert(`لا يوجد رصيد كافٍ من المادة: ${b.item_name} في هذا المخزن! المطلوب: ${consumedQty}، المتاح: ${bal}`);
        hasError = true;
      } else {
        rawItems.push({ item_id: b.item_id, item_name: b.item_name, qty: consumedQty, unit: b.unit });
      }
    });
    
    if(hasError) return;
    if(rawItems.length === 0) { alert('يجب استهلاك مادة واحدة على الأقل للتصنيع!'); return; }
    
    const attachInput = document.getElementById('manufacture-attachment');
    let attachmentBase64 = null;
    if (attachInput && attachInput.files && attachInput.files[0]) {
      attachmentBase64 = await new Promise((resolve) => {
        const reader = new FileReader();
        reader.onloadend = () => resolve(reader.result);
        reader.readAsDataURL(attachInput.files[0]);
      });
    }

    const invoice = {
      type: 'manufacture', date: dateStr,
      from_warehouse_id: whId, from_warehouse_name: currentWarehouses.find(w => String(w.id) === String(whId)).name,
      product_id: prodId, produced_item_name: prodDef.name, produced_qty: targetQty,
      items: rawItems, user: currentUser.username, created_at: new Date().toISOString(),
      attachment: attachmentBase64
    };
    
    await window.DB.add('transactions', invoice);
    closeModal('manufacture-modal'); await loadData();
  } catch(e) { alert("خطأ: " + e.message); }
});
