  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' ;

  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='' ;
  var url=ROOT_URL + '/includes/master/deliveryMailer.php?zips=' + encodeURIComponent(outputString) + '&clientnumber=<?= $_REQUEST["clientnumber"]?>&tenant=' + TENANT_URL;
  loadContentAndExecuteScripts(url, 'mailerContainer' );
  }
  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) + ' &tenant=' + encodeURIComponent(TENANT_URL));


  }

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

  // Build a whitelist strictly from errordel
  function parseErrordel(raw) {
    raw = String(raw ?? '').trim();
    if (!raw) return [];
    const out = new Set();

    if (raw.includes('|')) {
      // Format: 1759415489-20150-500-1|...
      raw.split('|').map(s => s.trim()).filter(Boolean).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 {
      // Format: path1.pdf,path2.pdf,...
      raw.split(',').map(s => s.trim()).filter(Boolean).forEach(path => {
        // keep given path, just strip leading ./ or ../
        const norm = path.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;
        pulseElementBackgroundClass('notifyHeader', 'bg_secondary', 'danger-color-dark', 900);
      }
    }
  };
  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' ;

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

  var xhrShed=new XMLHttpRequest();
  xhrShed.open("POST", ROOT_URL+'/functions/generators/genShed.php' , true);
  xhrShed.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded' );
  xhrShed.send('clientnumber=<?= $_REQUEST["clientnumber"]?>&tenant=' +TENANT_URL);

  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='' ;
  var url=ROOT_URL + '/includes/master/deliveryMailer.php?zips=' + encodeURIComponent(outputString) + '&clientnumber=<?= $_REQUEST["clientnumber"]?>&tenant=' + TENANT_URL;
  loadContentAndExecuteScripts(url, 'mailerContainer' );
  }
  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) + ' &tenant=' + encodeURIComponent(TENANT_URL));

  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);
  }
  }