let qzInitialized = false;

async function initQzSecurity(baseUrl) {
  if (qzInitialized) return;
  
  // Fetch certificate
  const certResponse = await fetch(baseUrl + "assets/thema/posr/sign/digital-certificate.txt");
  const certificate = await certResponse.text();
  qz.security.setCertificatePromise(function(resolve, reject) {
    resolve(certificate);
  });

  // Fetch private key
  //const keyResponse = await fetch(baseUrl + "assets/thema/posr/sign/private-key.pem");
  //const privateKey = await keyResponse.text();
  
  qz.security.setSignatureAlgorithm("SHA512"); // Since 2.1
  qz.security.setSignaturePromise(function(toSign) {
   return function(resolve, reject) {
      fetch(baseUrl + "posr/sign?hash=" + toSign, {cache: 'no-store', headers: {'Content-Type': 'text/plain'}})
         .then(function(data) { data.ok ? resolve(data.text()) : reject(data.text()); });
   };
  });
  /*qz.security.setSignaturePromise(function(toSign) {
    return function(resolve, reject) {
        try {
            var pk = KEYUTIL.getKey(privateKey);
            var sig = new KJUR.crypto.Signature({"alg": "SHA512withRSA"});  // Use "SHA1withRSA" for QZ Tray 2.0 and older
            sig.init(pk); 
            sig.updateString(toSign);
            var hex = sig.sign();
            console.log("DEBUG: \n\n" + stob64(hextorstr(hex)));
            resolve(stob64(hextorstr(hex)));
        } catch (err) {
            console.error(err);
            reject(err);
        }
    };
  });*/
  
  qzInitialized = true;
}

async function printReceipt(printerName, useQz, baseUrl) {
  if(!useQz){
    window.print();
    return;
  }  
  try {
    console.log("Using QZ Tray printing...");
    await initQzSecurity(baseUrl);
    await qz.websocket.connect();
    
  	//alert(printerName);
  	/*qz.printers.find().then(printers => {
    	console.log("Installed printers:", printers);
    	alert("Check browser console for printer list");
	});*/
  
    const printer = await qz.printers.find(printerName);
    console.log("Printer found:", printer);
    
    const config = qz.configs.create(printer, {
      colorType: 'color',
      copies: 1
    });
    
    const htmlData = document.body.outerHTML;
    await qz.print(config, [{ type: 'html', format: 'plain', data: htmlData }]);
    console.log("Printed successfully using QZ Tray!");
    await qz.websocket.disconnect();
  	window.close();
  } catch (err) {
    console.error("QZ Tray error:", err);
    console.log("Falling back to normal print...");
    //window.print();
    return;
  }
}
window.onafterprint = function() {
  window.close();
};