import { usePage } from "@inertiajs/vue3";
import { ref } from "vue";
import qz from "qz-tray";
//#region resources/js/lib/printService.ts
var isPrinting = ref(false);
var printStatus = ref("");
var STORAGE_KEY = "cafepos_print_settings";
var DEFAULT_SETTINGS = {
	method: "browser",
	posPrinter: "",
	kitchenPrinter: "",
	autoPrintPos: false,
	autoPrintKitchen: false
};
function getPrintSettings() {
	try {
		const stored = localStorage.getItem(STORAGE_KEY);
		if (stored) return {
			...DEFAULT_SETTINGS,
			...JSON.parse(stored)
		};
	} catch (e) {
		console.error("Failed to read print settings from localStorage:", e);
	}
	return DEFAULT_SETTINGS;
}
function savePrintSettings(settings) {
	try {
		localStorage.setItem(STORAGE_KEY, JSON.stringify(settings));
	} catch (e) {
		console.error("Failed to save print settings to localStorage:", e);
	}
}
async function connectQZ() {
	const page = usePage();
	const qzCert = page.props.qz_cert;
	const qzAlgo = page.props.qz_algo || "sha256";
	if (qzCert) {
		qz.security.setSignatureAlgorithm(qzAlgo.toUpperCase());
		qz.security.setCertificatePromise((resolve) => {
			resolve(qzCert);
		});
		const csrfToken = document.querySelector("meta[name=\"csrf-token\"]")?.getAttribute("content") || "";
		qz.security.setSignaturePromise((toSign) => {
			return (resolve, reject) => {
				fetch(route("qz-tray.sign"), {
					method: "POST",
					headers: {
						"Content-Type": "application/json",
						"X-CSRF-TOKEN": csrfToken,
						"Accept": "application/json"
					},
					body: JSON.stringify({ payload: toSign })
				}).then(async (res) => {
					if (!res.ok) {
						const errData = await res.json();
						throw new Error(errData.message || "Signature endpoint failed.");
					}
					return res.json();
				}).then((data) => {
					if (data.success) resolve(data.signature);
					else reject(data.message || "Signing failed");
				}).catch((err) => {
					reject(err.message || err);
				});
			};
		});
	}
	if (qz.websocket.isActive()) return true;
	try {
		await qz.websocket.connect();
		return true;
	} catch (err) {
		console.warn("QZ Tray is not running or connection failed:", err);
		return false;
	}
}
async function getAvailablePrinters() {
	if (!await connectQZ()) throw new Error("QZ Tray is not connected");
	return await qz.printers.find();
}
async function printHtmlViaQz(printerName, htmlContent) {
	if (!await connectQZ()) throw new Error("QZ Tray is not connected");
	const config = qz.configs.create(printerName, {
		margins: 0,
		orientation: "portrait",
		size: {
			width: 58,
			height: 297
		},
		units: "mm"
	});
	const printData = [{
		type: "html",
		format: "plain",
		data: htmlContent,
		options: {
			pageWidth: 58,
			margins: 0
		}
	}];
	await qz.print(config, printData);
}
function printUrlViaQz(printerName, url) {
	return new Promise((resolve, reject) => {
		const iframe = document.createElement("iframe");
		iframe.style.position = "absolute";
		iframe.style.width = "0px";
		iframe.style.height = "0px";
		iframe.style.border = "none";
		iframe.style.visibility = "hidden";
		iframe.src = url;
		document.body.appendChild(iframe);
		iframe.onload = async () => {
			try {
				printStatus.value = "Mengunduh format struk...";
				const doc = iframe.contentDocument || iframe.contentWindow?.document;
				if (!doc) throw new Error("Could not access iframe document");
				const headElements = doc.head.querySelectorAll("link[rel=\"stylesheet\"], style");
				let stylesHtml = "";
				headElements.forEach((el) => {
					if (el.tagName.toLowerCase() === "link") {
						const href = el.getAttribute("href");
						if (href && href.startsWith("/")) {
							const absoluteHref = window.location.origin + href;
							stylesHtml += `<link rel="stylesheet" href="${absoluteHref}">`;
						} else stylesHtml += el.outerHTML;
					} else stylesHtml += el.outerHTML;
				});
				const bodyClone = doc.body.cloneNode(true);
				bodyClone.querySelectorAll("img").forEach((img) => {
					const src = img.getAttribute("src");
					if (src && src.startsWith("/")) img.setAttribute("src", window.location.origin + src);
				});
				const htmlContent = stylesHtml + bodyClone.innerHTML;
				if (!bodyClone.innerHTML || bodyClone.innerHTML.trim() === "") throw new Error("Iframe loaded but content is empty");
				printStatus.value = "Mengirim data ke printer...";
				await printHtmlViaQz(printerName, htmlContent);
				document.body.removeChild(iframe);
				resolve();
			} catch (err) {
				if (iframe.parentNode) document.body.removeChild(iframe);
				reject(err);
			}
		};
		iframe.onerror = (err) => {
			if (iframe.parentNode) document.body.removeChild(iframe);
			reject(/* @__PURE__ */ new Error("Failed to load print preview iframe"));
		};
	});
}
async function printReceipt(transactionId, type, cashReceived, change) {
	const settings = getPrintSettings();
	let url = "";
	if (type === "pos") {
		const params = { transaction: transactionId };
		if (cashReceived !== void 0 && cashReceived !== null) params.cash_received = cashReceived;
		if (change !== void 0 && change !== null) params.change = change;
		url = route("transactions.print", params);
	} else url = route("transactions.kitchen-print", transactionId);
	try {
		isPrinting.value = true;
		if (settings.method === "qz") {
			printStatus.value = "Menghubungkan ke QZ Tray...";
			const printerName = type === "pos" ? settings.posPrinter : settings.kitchenPrinter;
			if (!printerName) return {
				success: false,
				method: "qz",
				error: `Printer name for ${type === "pos" ? "POS" : "Kitchen"} is not configured in settings.`
			};
			await printUrlViaQz(printerName, url.includes("?") ? `${url}&raw=true` : `${url}?raw=true`);
			return {
				success: true,
				method: "qz"
			};
		}
		printStatus.value = "Membuka dialog cetak browser...";
		window.open(url, "_blank");
		await new Promise((resolve) => setTimeout(resolve, 800));
		return {
			success: true,
			method: "browser"
		};
	} catch (err) {
		console.error("QZ Tray print failed, falling back to browser print:", err);
		printStatus.value = "Dialihkan ke dialog cetak browser...";
		window.open(url, "_blank");
		await new Promise((resolve) => setTimeout(resolve, 800));
		return {
			success: true,
			method: "browser",
			error: `QZ Tray print failed: ${err.message || err}. Opened print dialog instead.`
		};
	} finally {
		isPrinting.value = false;
		printStatus.value = "";
	}
}
//#endregion
export { printReceipt as a, isPrinting as i, getAvailablePrinters as n, printStatus as o, getPrintSettings as r, savePrintSettings as s, connectQZ as t };
