  function genZip(selected, errordel) {console.log('zip gen')
  var getWS=document.getElementById('wsAttach').checked ? "yes" : "no" ;
  var schAttach=document.getElementById('schAttach').checked ? "attach" : "" ;
  var wsattach=(getWS==="yes" ) ? selected : 'bypass' ;
  var covers=JSON.stringify(deliveryGetCoverAttachments());
  var wsWarningPromise=deliveryZipWsWarnings(wsattach);

  document.getElementById('statusCount').innerHTML='Generating Zip<br><i class="fad fa-file-archive"></i>' ;

  var xhr=new XMLHttpRequest();
  xhr.open("POST", ROOT_URL + '/functions/generators/genZIP.php' , true);
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded' );
  xhr.onreadystatechange=function () {
  if (xhr.readyState===4 && xhr.status===200) {
  var data=xhr.responseText.trim();
  if (data !=="" ) {
  var str=data.split('|');
  document.getElementById('delivery').style.display='block' ;

  var output={
  source: 'output/reports/<?= $_REQUEST["clientnumber"]?>' ,
  file: str[0],
  type: 'zip'
  };
  var outputString=JSON.stringify(output);

  document.getElementById('mailerContainer').innerHTML='' ;
  wsWarningPromise.then(function(warnings) {
  deliveryLoadMailer({zips: output, clientnumber: '<?= $_REQUEST["clientnumber"]?>', deliveryWarnings: warnings});
  });
  }
  document.getElementById('loading').style.display='none' ;
  setTimeout(function() {
  var el = document.getElementById('defectList');

  if (!el) {
  console.error('defectList not found.');
  } else {
  const hasContent = el.textContent.replace(/\u00A0/g, ' ').trim().length > 0;
  if (hasContent) {
  console.log('defectList has content. Proceeding.');
  genHSEZip(selected, errordel);
  } else {
  console.log('defectList empty. Skipping.');
  }
  }
  }, 300);
  }
  };
  xhr.send('clientnumber=<?= $_REQUEST["clientnumber"]?>&items=' + encodeURIComponent(selected) + ' &ws=' + encodeURIComponent(wsattach) + ' &schMode=' + encodeURIComponent(schAttach) + ' &covers=' + encodeURIComponent(covers) + ' &tenant=' + encodeURIComponent(TENANT_URL));


  }

  function deliveryZipWsWarnings(wsattach) {
  if (wsattach === 'bypass') {
  return Promise.resolve([]);
  }

  return fetch(ROOT_URL + '/includes/master/report_functions.php', {
  method: 'POST',
  headers: {'Content-Type': 'application/x-www-form-urlencoded'},
  body: new URLSearchParams({
  FUNCTION: 'detectPWS',
  items: String(wsattach || ''),
  client: '<?= $_REQUEST["clientnumber"]?>',
  tenant: TENANT_URL,
  format: 'json'
  })
  }).then(function(response) {
  return response.json();
  }).then(function(data) {
  return Array.isArray(data.warnings) ? data.warnings : [];
  }).catch(function() {
  return [];
  });
  }

  function genHSEZip(selected, errordel) {
  const noticeHost = document.getElementById('hseNotice');
  if (!noticeHost) return;

  // Build a whitelist strictly from errordel
  function parseErrordel(raw) {
  const items = deliveryListFromAny(raw).flatMap(item => String(item).split(',')).map(item => item.trim()).filter(Boolean);
  if (!items.length) return [];
  const out = new Set();

  items.forEach(tok => {
  const p = tok.split('-').map(x => x.trim());
  if (p.length >= 2 && p[0] && p[1]) {
  out.add(`output/reports/<?= $_REQUEST["clientnumber"]?>/${p[0]}_${p[1]}.pdf`);
  } else if (tok) {
  const norm = tok.replace(/^(\.\/|\.\.\/)+/, '');
  out.add(norm);
  }
  });

  return Array.from(out);
  }

  const links = parseErrordel(errordel);

  // Render ONLY these links
  const alert = document.createElement('div');
  alert.className = 'alert alert-warning text-dark text-center';
  alert.innerHTML = 'You have URGENT in your reporting data. <b>Notify HSE</b>' +
  `<div class="small mt-1">Detected items: ${links.length}</div>`;

  const row = document.createElement('div');
  row.className = 'd-flex flex-wrap justify-content-center mt-2 gap-2';

  links.forEach(href => {
  const fileName = href.split('/').pop();
  const a = document.createElement('a');
  a.href = href;
  a.target = '_blank';
  a.className = 'btn btn-sm-btn-secondary me-2';
  a.setAttribute('data-mdb-tooltip-init', '');
  a.setAttribute('data-mdb-placement', 'top');
  a.setAttribute('data-mdb-trigger', 'hover');
  a.setAttribute('data-html', 'true');
  a.setAttribute('aria-label', fileName);
  a.setAttribute('data-mdb-original-title', fileName);

  const i = document.createElement('i');
  i.className = 'fad fa-file-pdf';
  i.style.color = '#e96152';
  i.style.fontSize = '1.1rem';

  a.appendChild(i);
  row.appendChild(a);
  });

  noticeHost.innerHTML = '';
  alert.appendChild(row);
  noticeHost.appendChild(alert);

  try { if (window.mdb && mdb.Tooltip) row.querySelectorAll('[data-mdb-tooltip-init]').forEach(el => new mdb.Tooltip(el)); } catch(_) {}

  // Continue ZIP generation, unchanged
  document.getElementById('statusCount').innerHTML = 'Generating HSE Zip<br><i class="fad fa-file-archive"></i>';
  var xhr = new XMLHttpRequest();
  xhr.open("POST", ROOT_URL + '/functions/generators/genZIP.php', true);
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
  var data = (xhr.responseText || '').trim();
  if (data) {
  document.getElementById('defectList').value = data;
  document.getElementById('defectTemp').textContent = data;
  setTimeout(function() {
  //pulseElementBackgroundClass('notifyHeader', 'bg_secondary', 'danger-color-dark', 900);
  }, 3000);
  }
  }
  };
  xhr.send(
  'mode=hse&clientnumber=<?= $_REQUEST["clientnumber"]?>&items=' +
  encodeURIComponent(String(errordel ?? '').trim()) +
  '&tenant=' + encodeURIComponent(TENANT_URL)
  );
  }



  function genZips(hse) {
  console.log('loaded zip');
  var selected=document.getElementById('itemList').textContent;
  var schAttach=document.getElementById('schAttach').checked ? "attach" : "" ;
  var getWS=document.getElementById('wsAttach').checked ? "yes" : "no" ;

  var wsattach=(getWS==="yes" ) ? selected : 'bypass' ;
  var covers=JSON.stringify(deliveryGetCoverAttachments());
  var wsWarningPromise=deliveryZipWsWarnings(wsattach);

  document.getElementById('statusCount').innerHTML='Generating Zip<br><i class="fad fa-file-archive"></i>' ;
  var ml=document.getElementById('multiList').textContent;

  function startMultiZip() {
  var xhrZip=new XMLHttpRequest();
  xhrZip.open("POST", ROOT_URL + '/functions/generators/genZIP.php' , true);
  xhrZip.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded' );
  xhrZip.onreadystatechange=function () {
  if (xhrZip.readyState===4 && xhrZip.status===200) {
  var data=xhrZip.responseText.trim();
  if (data !=="" ) {
  console.log('zip created');
  var str=data.split('|');
  document.getElementById('delivery').style.display='block' ;

  var output={
  source: 'output/reports/<?= $_REQUEST["clientnumber"]?>' ,
  file: str[0],
  type: 'zip'
  };
  var outputString=JSON.stringify(output);
  console.log('outputString created');

  document.getElementById('mailerContainer').innerHTML='' ;
  wsWarningPromise.then(function(warnings) {
  deliveryLoadMailer({zips: output, clientnumber: '<?= $_REQUEST["clientnumber"]?>', deliveryWarnings: warnings});
  });
  }
  document.getElementById('loading').style.display='none' ;
  document.getElementById('delivery').style.display='block' ;

  console.log('zip done');
  }
  };
  xhrZip.send('clientnumber=<?= $_REQUEST["clientnumber"]?>&items=' + encodeURIComponent(ml) + ' &ws=' + encodeURIComponent(wsattach) + ' &schMode=' + encodeURIComponent(schAttach) + ' &covers=' + encodeURIComponent(covers) + ' &tenant=' + encodeURIComponent(TENANT_URL));
  }

  if (schAttach === "attach") {
  var xhrShed=new XMLHttpRequest();
  xhrShed.open("POST", ROOT_URL+'/functions/generators/genShed.php' , true);
  xhrShed.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded' );
  xhrShed.onreadystatechange=function () {
  if (xhrShed.readyState===4) {
  startMultiZip();
  }
  };
  xhrShed.send('clientnumber=<?= $_REQUEST["clientnumber"]?>&site=' + encodeURIComponent(deliverySelectedSite) + '&tenant=' + encodeURIComponent(TENANT_URL));
  } else {
  startMultiZip();
  }

  if (hse !== '') {
  setTimeout(function() {
  var defectListElement = document.getElementById('defectList');
  if (defectListElement) {
  console.log("defectList found, calling genHSEZip");
  genHSEZip(selected, errordel); // Call genHSEZip after delay
  } else {
  console.error("defectList not found.");
  }
  }, 300);
  }
  }
