'; } function openPrintWindow(){ var html=makePrintableHtml();if(!html)return; var w=window.open('','_blank','width=1000,height=800'); if(!w){alert('Print window was blocked. Please allow pop-ups for this site and try again.');return;} w.document.open();w.document.write(html);w.document.close(); w.onload=function(){w.focus();setTimeout(function(){w.print();},250)}; } document.getElementById('dc-preview').addEventListener('click',function(){ calculate(); var html=makePrintableHtml();if(!html)return; var w=window.open('','_blank','width=1000,height=800'); if(!w){alert('Preview window was blocked. Please allow pop-ups for this site and try again.');return;} w.document.open();w.document.write(html);w.document.close(); w.onload=function(){w.focus();}; }); document.getElementById('dc-print').addEventListener('click',openPrintWindow); function getCustomerFilename(){ var to=(customerTo.value||'').trim(); var customer=(to.split(/\r?\n/)[0]||'Customer').trim(); var safeCustomer=customer.replace(/[\\/:*?"<>|]+/g,'-').replace(/\s+/g,'-').replace(/-+/g,'-').replace(/^-|-$/g,'')||'Customer'; var number=(document.getElementById('dc-number').value||'DC').trim().replace(/[^a-z0-9_-]/gi,'-')||'DC'; return {customer:safeCustomer, number:number, filename:safeCustomer+'-DC-'+number+'.pdf'}; } function loadPdfLibrary(){ return new Promise(function(resolve,reject){ if(window.html2pdf){resolve();return;} var existing=document.querySelector('script[data-freadio-html2pdf]'); if(existing){existing.addEventListener('load',resolve,{once:true});existing.addEventListener('error',reject,{once:true});return;} var script=document.createElement('script');script.src='https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js';script.async=true;script.setAttribute('data-freadio-html2pdf','true');script.onload=resolve;script.onerror=reject;document.head.appendChild(script); }); } async function createPdfFile(){ calculate(); var paper=document.querySelector('#freadio-dc-workspace .freadio-dc-paper'); if(!paper)throw new Error('DC form is not ready. Please log in first.'); await loadPdfLibrary(); var clone=paper.cloneNode(true); clone.querySelectorAll('input,textarea,select').forEach(function(el){ var value=el.tagName==='SELECT'?(el.options[el.selectedIndex]?el.options[el.selectedIndex].text:''):(el.value||''); var span=document.createElement('span');span.textContent=value;span.style.cssText='display:block;min-height:14px;white-space:pre-wrap;overflow-wrap:anywhere;font:inherit;color:#111;padding:2px 3px;';el.parentNode.replaceChild(span,el); }); clone.querySelectorAll('.freadio-dc-remove,button,.freadio-dc-row-tools').forEach(function(el){el.remove()}); clone.style.width='190mm';clone.style.maxWidth='190mm';clone.style.margin='0';clone.style.background='#ffd0e3';clone.style.color='#111';clone.style.padding='5mm';clone.style.fontSize='9px'; var wrap=document.createElement('div');wrap.style.cssText='position:fixed;left:-10000px;top:0;width:200mm;background:#fff;z-index:-1;';wrap.appendChild(clone);document.body.appendChild(wrap); try{ var info=getCustomerFilename(); var blob=await window.html2pdf().set({margin:7,filename:info.filename,image:{type:'jpeg',quality:0.98},html2canvas:{scale:2,useCORS:true,backgroundColor:'#ffffff',scrollY:0},jsPDF:{unit:'mm',format:'a4',orientation:'portrait'},pagebreak:{mode:['css','legacy']}}).from(clone).outputPdf('blob'); return {file:new File([blob],info.filename,{type:'application/pdf'}),info:info}; }finally{wrap.remove();} } function downloadBlob(blob,filename){var url=URL.createObjectURL(blob);var a=document.createElement('a');a.href=url;a.download=filename;document.body.appendChild(a);a.click();a.remove();setTimeout(function(){URL.revokeObjectURL(url)},5000)} document.getElementById('dc-pdf').addEventListener('click',async function(){ var button=this;button.disabled=true;button.textContent='Creating PDF…'; try{var result=await createPdfFile();downloadBlob(result.file,result.info.filename);document.getElementById('dc-save-status').textContent='PDF created and downloaded: '+result.info.filename;} catch(e){document.getElementById('dc-save-status').textContent='Automatic PDF creation failed (check internet connection). Use Direct Print → Save as PDF. Details: '+(e.message||'PDF error');} finally{button.disabled=false;button.textContent='Download PDF';} }); document.getElementById('dc-share').addEventListener('click',async function(){ var button=this;button.disabled=true;var original=button.innerHTML;button.textContent='Creating PDF…'; try{ var result=await createPdfFile(); var total=document.getElementById('dc-total-rupees').textContent+'.'+document.getElementById('dc-total-paise').textContent; var to=(customerTo.value||'').trim(); var shareText='Delivery Challan '+result.info.number+'\nCustomer: '+to+'\nTotal: Rs. '+total+'\nFull PDF attached.'; if(navigator.share && navigator.canShare && navigator.canShare({files:[result.file]})){ await navigator.share({title:'Delivery Challan '+result.info.number,text:shareText,files:[result.file]}); document.getElementById('dc-save-status').textContent='Actual PDF shared successfully: '+result.info.filename; }else{ downloadBlob(result.file,result.info.filename); document.getElementById('dc-save-status').textContent='Actual PDF downloaded as '+result.info.filename+'. Attach this .pdf file in WhatsApp/email; this browser does not support direct file sharing.'; } }catch(e){ if(e && e.name==='AbortError')return; document.getElementById('dc-save-status').textContent='PDF share failed. Check internet connection and try again; otherwise use Direct Print → Save as PDF. Details: '+(e.message||'PDF error'); }finally{button.disabled=false;button.innerHTML=original;} }); document.getElementById('dc-save').addEventListener('click',function(){calculate();var data={};Array.from(dcForm.elements).forEach(function(el){if(el.name&&el.type!=='button'&&el.type!=='submit'&&el.type!=='file')data[el.name]=el.value});data.items=Array.from(body.querySelectorAll('tr')).map(function(tr){return Array.from(tr.querySelectorAll('input')).map(function(i){return i.value})});try{var key='freadio-dc-draft-'+(data.dc_number||'draft');localStorage.setItem(key,JSON.stringify(data));document.getElementById('dc-save-status').textContent='DC draft saved in this browser. For shared cloud records, server storage must be connected.'}catch(ex){document.getElementById('dc-save-status').textContent='Could not save draft in this browser.'}}); document.getElementById('dc-clear').addEventListener('click',function(){if(!confirm('Clear all entered DC details?'))return;dcForm.reset();body.innerHTML='';for(var i=0;i<12;i++)addRow();date.value=new Date().toISOString().slice(0,10);document.getElementById('dc-date-copy').value=date.value;document.getElementById('dc-number-copy').value=document.getElementById('dc-number').value;calculate()}); document.getElementById('dc-logout').addEventListener('click',function(){login.hidden=false;workspace.hidden=true;document.getElementById('freadio-dc-password').value='';error.hidden=true}); })();