<!-- GESTIONE MAGAZZINO PRO – JS (Footer Injection con wrapper sicuro) -->
<script>
function initMagazzinoSafe() {
  const checkExist = setInterval(function() {
    const formExists = document.getElementById("submitBtn");
    const tabellaExists = document.getElementById("tabellaBody");
    if(formExists && tabellaExists){
      clearInterval(checkExist);
      initMagazzino(); // richiama la funzione principale quando il Code Block è pronto
    }
  }, 100);
}

document.addEventListener("DOMContentLoaded", initMagazzinoSafe);
document.addEventListener("pjax:complete", initMagazzinoSafe);

// Funzione principale
function initMagazzino(){
  if(window.magazzinoInizializzato) return;
  window.magazzinoInizializzato = true;

  const GIORNI_GIALLO = 10;
  let db = JSON.parse(localStorage.getItem("magazzino")) || [];
  let indiceModifica = null;

  const fornitoreInput = document.getElementById("fornitore");
  const prodottoInput = document.getElementById("prodotto");
  const lottoInput = document.getElementById("lotto");
  const quantitaInput = document.getElementById("quantita");
  const prezzoInput = document.getElementById("prezzo");
  const dataScadenzaInput = document.getElementById("dataScadenza");
  const submitBtn = document.getElementById("submitBtn");

  function salvaLocal(){ localStorage.setItem("magazzino", JSON.stringify(db)); }

  function calcolaStato(scadenza){
    if(!scadenza) return "ok";
    const diff=(new Date(scadenza)-new Date())/(1000*60*60*24);
    if(diff<0) return "scaduto";
    if(diff<=GIORNI_GIALLO) return "inScadenza";
    return "ok";
  }

  function filtraTabella(){
    const val=document.getElementById("ricercaAvanzata").value.toLowerCase();
    document.querySelectorAll("#tabellaBody tr").forEach(row=>{
      row.style.display=row.innerText.toLowerCase().includes(val)?"":"none";
    });
  }

  window.elimina = function(index){
    if(confirm("Eliminare prodotto?")){
      db.splice(index,1);
      salvaLocal();
      aggiornaTabella();
    }
  }

  window.modifica = function(index){
    const p = db[index];
    fornitoreInput.value = p.fornitore;
    prodottoInput.value = p.prodotto;
    lottoInput.value = p.lotto;
    quantitaInput.value = p.quantita;
    prezzoInput.value = p.prezzo;
    dataScadenzaInput.value = p.dataScadenza;
    indiceModifica = index;
    submitBtn.innerText = "AGGIORNA";
  }

  function resetCampi(){
    [fornitoreInput, prodottoInput, lottoInput, quantitaInput, prezzoInput, dataScadenzaInput].forEach(el=>el.value="");
    indiceModifica=null;
    submitBtn.innerText="SALVA";
  }

  submitBtn.addEventListener("click", function(){
    const nuovoProdotto = {
      fornitore: fornitoreInput.value,
      prodotto: prodottoInput.value,
      lotto: lottoInput.value,
      quantita: parseFloat(quantitaInput.value)||0,
      prezzo: parseFloat(prezzoInput.value)||0,
      dataScadenza: dataScadenzaInput.value
    };

    if(indiceModifica !== null){
      db[indiceModifica] = nuovoProdotto;
    } else {
      db.push(nuovoProdotto);
    }

    salvaLocal();
    aggiornaTabella();
    resetCampi();
  });

  function aggiornaTabella(){
    const tbody=document.getElementById("tabellaBody");
    tbody.innerHTML="";
    let scaduti=0,inScad=0,totaleGen=0;

    db.forEach((r,index)=>{
      const stato = calcolaStato(r.dataScadenza);
      if(stato==="scaduto") scaduti++;
      if(stato==="inScadenza") inScad++;
      const totale = r.quantita*r.prezzo;
      totaleGen += totale;

      const tr = document.createElement("tr");
      tr.className = stato;
      tr.innerHTML = `
        <td>${r.fornitore}</td>
        <td>${r.prodotto}</td>
        <td>${r.lotto||""}</td>
        <td>${r.quantita}</td>
        <td>${r.prezzo.toFixed(2)}</td>
        <td>${totale.toFixed(2)}</td>
        <td>${r.dataScadenza||"-"}</td>
        <td>
          <button onclick="modifica(${index})">✏️</button>
          <button onclick="elimina(${index})">❌</button>
        </td>
      `;
      tbody.appendChild(tr);
    });

    document.getElementById("alertMagazzino").innerHTML=
      `🔴 ${scaduti} scaduti | 🟡 ${inScad} in scadenza | 💰 Valore totale: € ${totaleGen.toFixed(2)}`;
  }

  document.getElementById("ricercaAvanzata").addEventListener("keyup", filtraTabella);
  aggiornaTabella();
}
</script>