// /pages/api/netopia/process-order.js
import { db } from "@/helpers/api";
import nodemailer from "nodemailer";

import axios from "axios";
import crypto from "crypto";

import AWS from "aws-sdk";
import { PDFDocument, StandardFonts, rgb } from "pdf-lib";
import fs from "fs";
import path from "path";

AWS.config.update({
	accessKeyId: process.env.AWS_ACCESS_KEY_ID || "AKIA2AFW3Y3GU5WK2Y6G",
	secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY || "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",
	region: "eu-north-1",
});

async function generateFGOInvoice(order, items) {
	try {
		const codUnic = "50155117";
		const cheiePriva = "0E955F8378BECD8E785F91ABDF694FD6";
		const serie = "EMAGYL";

		const clientData = prepareClientDataForFGO(order);

		const hashString = codUnic + cheiePriva + clientData.Denumire;
		const hash = crypto.createHash("sha1").update(hashString).digest("hex").toUpperCase();

		const fgoPayload = {
			CodUnic: codUnic,
			Hash: hash,
			Valuta: "RON",
			TipFactura: "Factura",
			Serie: serie,
			IdExtern: order.id.toString(),
			PlatformaUrl: process.env.SITE_URL || "https://emagyl.ro",
			Client: clientData,
			Continut: formatItemsForFGO(items),
		};

		const response = await axios.post("https://api.fgo.ro/v1/factura/emitere", fgoPayload, {
			headers: {
				"Content-Type": "application/json",
				Authorization: "Bearer 0E955F8378BECD8E785F91ABDF694FD6",
			},
			timeout: 30000,
		});

		console.log("FGO Response:", response.data);
		return response.data;
	} catch (error) {
		console.error("Eroare FGO API:", {
			message: error.message,
			status: error.response?.status,
			data: error.response?.data,
		});
		throw error;
	}
}

function prepareClientDataForFGO(order) {
	if (order.pf_nume_familie && order.pf_prenume) {
		let parts = order.pf_judet_oras.split(",");
		let judet = parts[0].trim();
		let localitate = parts[1] ? parts[1].trim() : "";

		return {
			Denumire: `${order.pf_nume_familie} ${order.pf_prenume}`,
			CodUnic: "",
			Tip: "PF",
			Tara: "RO",
			Judet: judet,
			Localitate: localitate,
			Adresa: order.pf_adresa || "",
			Email: order.email || "",
			Telefon: order.pf_numar_telefon || "",
			IdExtern: order.id.toString(),
		};
	}

	if (order.pj_nume_firma) {
		return {
			Denumire: order.pj_nume_firma,
			CodUnic: order.pj_cui || "",
			NrRegCom: order.pj_reg_com || "",
			Tip: "PJ",
			Tara: "RO",
			Judet: order.pj_judet || "",
			Localitate: order.pj_localitate || "",
			Adresa: order.pj_adresa || "",
			Email: order.pj_email || "",
			Telefon: order.pj_numar_telefon || "",
			PlatitorTVA: true,
			IdExtern: order.id.toString(),
		};
	}

	return {
		Denumire: "Client Necunoscut",
		Tip: "PF",
		Tara: "RO",
		Judet: "",
		IdExtern: order.id.toString(),
	};
}

function formatItemsForFGO(items) {
	const products = items.map((item) => {
		const priceWithVAT = parseFloat(item.priceReduced || item.price);
		const priceWithoutVAT = priceWithVAT / 1.21; // Scade TVA 21%

		return {
			Denumire: item.name,
			CodArticol: item.sku || "",
			UM: "buc",
			NrProduse: parseFloat(item.quantity),
			PretUnitar: parseFloat(priceWithoutVAT.toFixed(2)), // Preț FĂRĂ TVA
			CotaTVA: 21,
		};
	});

	// Transport: 22 RON cu TVA = 18.18 RON fără TVA
	const transportWithoutVAT = 22.0 / 1.21;

	const transportCost = {
		Denumire: "Cost transport",
		CodArticol: "TRANSPORT",
		UM: "buc",
		NrProduse: 1,
		PretUnitar: parseFloat(transportWithoutVAT.toFixed(2)), // 18.18 RON
		CotaTVA: 21,
	};

	return [...products, transportCost];
}

function removeDiacritics(text) {
	if (!text) return "";
	return text
		.replace(/ă/g, "a")
		.replace(/Ă/g, "A")
		.replace(/â/g, "a")
		.replace(/Â/g, "A")
		.replace(/î/g, "i")
		.replace(/Î/g, "I")
		.replace(/ș/g, "s")
		.replace(/Ș/g, "S")
		.replace(/ț/g, "t")
		.replace(/Ț/g, "T");
}

function stripHTML(html) {
	if (!html) return "";
	return html
		.replace(/<[^>]*>/g, " ") // Elimină toate tag-urile HTML
		.replace(/&nbsp;/g, " ") // Înlocuiește &nbsp;
		.replace(/&amp;/g, "&") // Înlocuiește &amp;
		.replace(/&lt;/g, "<") // Înlocuiește &lt;
		.replace(/&gt;/g, ">") // Înlocuiește &gt;
		.replace(/&quot;/g, '"') // Înlocuiește &quot;
		.replace(/&#39;/g, "'") // Înlocuiește &#39;
		.replace(/\s+/g, " ") // Înlocuiește multiple spații cu una singură
		.trim(); // Elimină spațiile de la început și sfârșit
}

async function generateInstructionsPDF(order, items) {
	try {
		console.log("📄 Start generare PDF instructiuni...");

		// Creează un document PDF nou
		const pdfDoc = await PDFDocument.create();

		// Încarcă fonturile
		const boldFont = await pdfDoc.embedFont(StandardFonts.HelveticaBold);
		const regularFont = await pdfDoc.embedFont(StandardFonts.Helvetica);
		const italicFont = await pdfDoc.embedFont(StandardFonts.HelveticaOblique);

		// Constante pentru formatare
		const pageWidth = 595; // A4 width in points
		const pageHeight = 842; // A4 height in points
		const margin = 50;
		const contentWidth = pageWidth - margin * 2;
		const lineHeight = 20;
		const titleSize = 18;
		const subtitleSize = 14;
		const textSize = 11;

		// Prima pagină - Titlu
		let currentPage = pdfDoc.addPage([pageWidth, pageHeight]);
		let yPosition = pageHeight - 100;

		// Titlu principal centrat (fără diacritice)
		const titleText = removeDiacritics(`Instructiuni de utilizare pentru produsele`);
		const titleText2 = removeDiacritics(`comandate din comanda #${order.id}`);

		const titleWidth = boldFont.widthOfTextAtSize(titleText, titleSize);
		const titleWidth2 = boldFont.widthOfTextAtSize(titleText2, titleSize);

		currentPage.drawText(titleText, {
			x: (pageWidth - titleWidth) / 2,
			y: yPosition,
			size: titleSize,
			font: boldFont,
			color: rgb(0, 0, 0),
		});

		yPosition -= lineHeight + 5;

		currentPage.drawText(titleText2, {
			x: (pageWidth - titleWidth2) / 2,
			y: yPosition,
			size: titleSize,
			font: boldFont,
			color: rgb(0, 0, 0),
		});

		yPosition -= lineHeight * 2;

		// Linie decorativă
		currentPage.drawLine({
			start: { x: margin, y: yPosition },
			end: { x: pageWidth - margin, y: yPosition },
			thickness: 2,
			color: rgb(0, 0, 0),
		});

		yPosition -= lineHeight * 2;

		// Data generării
		const currentDate = new Date().toLocaleDateString("ro-RO", {
			year: "numeric",
			month: "long",
			day: "numeric",
		});

		const dateText = removeDiacritics(`Generat la: ${currentDate}`);
		currentPage.drawText(dateText, {
			x: margin,
			y: yPosition,
			size: textSize,
			font: italicFont,
			color: rgb(0.3, 0.3, 0.3),
		});

		yPosition -= lineHeight * 2;

		// Parcurge fiecare produs și adaugă instrucțiunile
		for (let i = 0; i < items.length; i++) {
			const item = items[i];

			// Găsește produsul în baza de date pentru a lua descrierea
			let productDesc = "";
			try {
				const product = await db.Products.findOne({
					where: { sku: item.sku || item.id },
				});

				if (product && product.desc) {
					productDesc = removeDiacritics(stripHTML(product.desc));
				} else {
					productDesc = removeDiacritics("Nu sunt disponibile instructiuni pentru acest produs.");
				}
			} catch (dbError) {
				console.error(`⚠️ Eroare citire produs ${item.sku}:`, dbError.message);
				productDesc = removeDiacritics("Nu sunt disponibile instructiuni pentru acest produs.");
			}

			// Verifică dacă trebuie o pagină nouă pentru acest produs
			if (yPosition < 150) {
				currentPage = pdfDoc.addPage([pageWidth, pageHeight]);
				yPosition = pageHeight - margin;
			}

			// Titlu produs (fără diacritice)
			// Titlu produs (fără diacritice) - cu word wrap pentru titluri lungi
			const productTitle = removeDiacritics(`${i + 1}. ${item.name || "Produs"}`);

			// Word wrap pentru titlul produsului
			const titleWords = productTitle.split(" ");
			let titleLine = "";
			const maxTitleWidth = contentWidth;

			for (const word of titleWords) {
				const testLine = titleLine + word + " ";
				const testWidth = boldFont.widthOfTextAtSize(testLine, subtitleSize);

				if (testWidth > maxTitleWidth && titleLine !== "") {
					// Verifică dacă trebuie pagină nouă
					if (yPosition < margin + 50) {
						currentPage = pdfDoc.addPage([pageWidth, pageHeight]);
						yPosition = pageHeight - margin;
					}

					currentPage.drawText(titleLine.trim(), {
						x: margin,
						y: yPosition,
						size: subtitleSize,
						font: boldFont,
						color: rgb(0, 0, 0),
					});

					titleLine = word + " ";
					yPosition -= lineHeight;
				} else {
					titleLine = testLine;
				}
			}

			// Afișează ultima linie a titlului
			if (titleLine.trim() !== "") {
				if (yPosition < margin + 50) {
					currentPage = pdfDoc.addPage([pageWidth, pageHeight]);
					yPosition = pageHeight - margin;
				}

				currentPage.drawText(titleLine.trim(), {
					x: margin,
					y: yPosition,
					size: subtitleSize,
					font: boldFont,
					color: rgb(0, 0, 0),
				});

				yPosition -= lineHeight;
			}

			// SKU și cantitate (fără diacritice)
			const productInfo = removeDiacritics(`SKU: ${item.sku || "N/A"} | Cantitate: ${item.quantity || 1} buc`);
			currentPage.drawText(productInfo, {
				x: margin + 10,
				y: yPosition,
				size: textSize - 1,
				font: italicFont,
				color: rgb(0.4, 0.4, 0.4),
			});

			yPosition -= lineHeight * 1.5;

			// Linie separatoare subtilă
			currentPage.drawLine({
				start: { x: margin, y: yPosition },
				end: { x: pageWidth - margin, y: yPosition },
				thickness: 0.5,
				color: rgb(0.7, 0.7, 0.7),
			});

			yPosition -= lineHeight;

			// Procesează și afișează descrierea (instrucțiunile) - DEJA fără diacritice
			const words = productDesc.split(" ");
			let line = "";
			const maxLineWidth = contentWidth - 20;

			for (const word of words) {
				const testLine = line + word + " ";
				const testWidth = regularFont.widthOfTextAtSize(testLine, textSize);

				if (testWidth > maxLineWidth && line !== "") {
					// Verifică dacă trebuie pagină nouă
					if (yPosition < margin + 50) {
						currentPage = pdfDoc.addPage([pageWidth, pageHeight]);
						yPosition = pageHeight - margin;
					}

					currentPage.drawText(line.trim(), {
						x: margin + 10,
						y: yPosition,
						size: textSize,
						font: regularFont,
						color: rgb(0, 0, 0),
					});

					line = word + " ";
					yPosition -= lineHeight;
				} else {
					line = testLine;
				}
			}

			// Afișează ultima linie
			if (line.trim() !== "") {
				if (yPosition < margin + 50) {
					currentPage = pdfDoc.addPage([pageWidth, pageHeight]);
					yPosition = pageHeight - margin;
				}

				currentPage.drawText(line.trim(), {
					x: margin + 10,
					y: yPosition,
					size: textSize,
					font: regularFont,
					color: rgb(0, 0, 0),
				});

				yPosition -= lineHeight;
			}

			// Spațiu între produse
			yPosition -= lineHeight * 1.5;

			// Linie separatoare între produse
			if (i < items.length - 1) {
				if (yPosition < margin + 50) {
					currentPage = pdfDoc.addPage([pageWidth, pageHeight]);
					yPosition = pageHeight - margin;
				}

				currentPage.drawLine({
					start: { x: margin, y: yPosition },
					end: { x: pageWidth - margin, y: yPosition },
					thickness: 1,
					color: rgb(0.8, 0.8, 0.8),
					dashArray: [3, 3],
				});

				yPosition -= lineHeight * 2;
			}
		}

		// Adaugă footer pe ultima pagină (fără diacritice)
		const footerText = removeDiacritics(
			"Pentru intrebari suplimentare, va rugam sa ne contactati la contact@emagyl.ro"
		);
		const footerY = 30;
		const footerWidth = regularFont.widthOfTextAtSize(footerText, textSize - 2);

		currentPage.drawText(footerText, {
			x: (pageWidth - footerWidth) / 2,
			y: footerY,
			size: textSize - 2,
			font: italicFont,
			color: rgb(0.5, 0.5, 0.5),
		});

		// Salvează PDF-ul
		const pdfBytes = await pdfDoc.save();
		console.log("✅ PDF instructiuni generat, marime:", pdfBytes.length, "bytes");

		const s3 = new AWS.S3();
		const fileName = `instructions/${order.id}_${Date.now()}.pdf`;

		const s3Params = {
			Bucket: process.env.AWS_S3_BUCKET || "emagyl",
			Key: fileName,
			Body: Buffer.from(pdfBytes),
			ContentType: "application/pdf",
			ContentDisposition: `attachment; filename="instructiuni_comanda_${order.id}.pdf"`,
			ACL: "public-read",
		};

		// Upload în S3
		console.log("📤 Upload PDF instructiuni in S3...");
		const uploadResult = await s3.upload(s3Params).promise();
		console.log("✅ PDF instructiuni uploadat:", uploadResult.Location);

		// Returnează URL-ul cu CloudFront
		const formattedUrl = uploadResult.Location.replace(
			"https://emagyl.s3.eu-north-1.amazonaws.com",
			"https://d372xxb7fb1cod.cloudfront.net"
		);

		return formattedUrl;
	} catch (error) {
		console.error("❌ EROARE generare PDF instructiuni:", error.message);
		console.error("Stack:", error.stack);
		throw error;
	}
}

async function generateWarrantyCertificate(order, items) {
	try {
		const templatePath = path.join(process.cwd(), "public", "certificat.pdf");

		if (!fs.existsSync(templatePath)) {
			console.error("❌ Template-ul certificat.pdf NU EXISTĂ la calea:", templatePath);
			throw new Error(`Template certificat.pdf nu există la: ${templatePath}`);
		}

		const existingPdfBytes = fs.readFileSync(templatePath);
		const pdfDoc = await PDFDocument.load(existingPdfBytes);

		const pages = pdfDoc.getPages();
		const page = pages[0];

		const font = await pdfDoc.embedFont(StandardFonts.HelveticaBold);
		const regularFont = await pdfDoc.embedFont(StandardFonts.Helvetica);

		const purchaseDate = new Date().toLocaleDateString("ro-RO");
		const clientName = order.Denumire || "Client";

		let deliverAddress = "";
		let deliverAddress2 = "";

		if (order.Adresa) {
			deliverAddress = order.Adresa.substring(0, Math.min(20, order.Adresa.length));
			if (order.Adresa.length > 20) {
				deliverAddress2 = order.Adresa.substring(20, Math.min(order.Adresa.length, 60));
			}
		}

		page.drawText(clientName, { x: 428, y: 724.6, size: 12, font });
		page.drawText(deliverAddress, { x: 490, y: 710, size: 12, font });
		page.drawText(deliverAddress2, { x: 389, y: 695, size: 12, font });
		page.drawText(order.IdExtern || "", { x: 485, y: 681, size: 12, font });
		page.drawText(purchaseDate, { x: 475, y: 666, size: 12, font });
		page.drawText(purchaseDate, { x: 45, y: 100, size: 12, font });

		const newPage = pdfDoc.addPage([610, 842]);
		const { width, height } = newPage.getSize();

		const margin = 40;
		const tableWidth = width - margin * 2;
		const tableX = margin;
		const tableY = height - 80;
		const rowHeight = 30;
		const col1Width = tableWidth - 100;

		newPage.drawRectangle({
			x: tableX,
			y: tableY,
			width: tableWidth,
			height: rowHeight,
			borderColor: rgb(0, 0, 0),
			borderWidth: 1,
		});

		newPage.drawLine({
			start: { x: tableX + col1Width, y: tableY },
			end: { x: tableX + col1Width, y: tableY + rowHeight },
			color: rgb(0, 0, 0),
			thickness: 1,
		});

		newPage.drawText("Denumire Produs", {
			x: tableX + 10,
			y: tableY + rowHeight / 2 - 5,
			size: 12,
			font: font,
		});

		newPage.drawText("Cantitate", {
			x: tableX + col1Width + 20,
			y: tableY + rowHeight / 2 - 5,
			size: 12,
			font: font,
		});

		items.forEach((product, index) => {
			const rowY = tableY - (index + 1) * rowHeight;

			newPage.drawRectangle({
				x: tableX,
				y: rowY,
				width: tableWidth,
				height: rowHeight,
				borderColor: rgb(0, 0, 0),
				borderWidth: 1,
			});

			newPage.drawLine({
				start: { x: tableX + col1Width, y: rowY },
				end: { x: tableX + col1Width, y: rowY + rowHeight },
				color: rgb(0, 0, 0),
				thickness: 1,
			});

			const productName = product.Denumire || "Produs necunoscut";
			const quantity = product.NrProduse || 1;

			newPage.drawText(productName, {
				x: tableX + 10,
				y: rowY + rowHeight / 2 - 5,
				size: 11,
				font: regularFont,
			});

			newPage.drawText(quantity.toString(), {
				x: tableX + col1Width + 35,
				y: rowY + rowHeight / 2 - 5,
				size: 11,
				font: regularFont,
			});
		});

		const pdfBytes = await pdfDoc.save();

		AWS.config.update({
			accessKeyId: process.env.AWS_ACCESS_KEY_ID || "AKIA2AFW3Y3GU5WK2Y6G",
			secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY || "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",
			region: "eu-north-1",
		});

		const s3 = new AWS.S3();
		const fileName = `certificates/${order.IdExtern}_${Date.now()}.pdf`;

		const s3Params = {
			Bucket: process.env.AWS_S3_BUCKET || "emagyl",
			Key: fileName,
			Body: Buffer.from(pdfBytes),
			ContentType: "application/pdf",
			ContentDisposition: `attachment; filename="${fileName}"`,
			ACL: "public-read",
		};

		const uploadResult = await s3.upload(s3Params).promise();

		return uploadResult.Location;
	} catch (error) {
		console.error("❌ EROARE generare certificat:", error.message);
		console.error("Stack:", error.stack);
		throw error;
	}
}

async function sendOrderConfirmationEmail(orderData, cartProducts) {
	try {
		// DEBUG la începutul funcției
		console.log("📧 sendOrderConfirmationEmail called");
		console.log("📧 cartProducts type:", typeof cartProducts);
		console.log("📧 cartProducts is array?", Array.isArray(cartProducts));
		console.log("📧 cartProducts value:", cartProducts);

		// Verifică că este array
		if (!Array.isArray(cartProducts)) {
			console.error("❌ cartProducts is not an array in sendOrderConfirmationEmail!");
			console.error("Type:", typeof cartProducts);
			console.error("Value:", cartProducts);
			return false;
		}

		if (cartProducts.length === 0) {
			console.error("❌ cartProducts is empty!");
			return false;
		}

		const transporter = nodemailer.createTransport({
			host: "mail.emagyl.ro",
			port: 465,
			secure: "465",
			auth: {
				user: "noreply@emagyl.ro",
				pass: "$}*UC#8S-0U2XL+H",
			},
		});

		const subtotal = cartProducts.reduce((sum, product) => {
			const price =
				product.priceReduced != null ? parseFloat(product.priceReduced) : parseFloat(product.price);
			return sum + price * product.quantity;
		}, 0);

		const transport = 22; // TVA INCLUS (18.18 fara TVA)

		const productsHTML = cartProducts
			.map((product) => {
				const price =
					product.priceReduced != null ? parseFloat(product.priceReduced) : parseFloat(product.price);

				const totalProduct = price * product.quantity;

				return `
                    <tr>
                         <td style="padding: 12px; border-bottom: 1px solid #eee;">
                              <strong>${product.name}</strong><br>
                              <span style="color: #666; font-size: 12px;">SKU: ${product.sku || "N/A"}</span>
                         </td>
                         <td style="padding: 12px; border-bottom: 1px solid #eee; text-align: center;">${
						product.quantity
					}</td>
                         <td style="padding: 12px; border-bottom: 1px solid #eee; text-align: right;">${price.toFixed(
						2
					)} RON</td>
                         <td style="padding: 12px; border-bottom: 1px solid #eee; text-align: right;"><strong>${totalProduct.toFixed(
						2
					)} RON</strong></td>
                    </tr>
               `;
			})
			.join("");

		// Generează HTML pentru adresa de livrare
		let deliveryAddressHTML = "";
		if (orderData.billingType === 0) {
			deliveryAddressHTML = `
                    <p><strong>Nume:</strong> ${orderData.pf_prenume} ${orderData.pf_nume_familie}</p>
                    <p><strong>Adresă:</strong> ${orderData.pf_adresa}, ${orderData.pf_judet_oras}, ${
				orderData.pf_tara
			}</p>
                    <p><strong>Telefon:</strong> ${orderData.pf_numar_telefon}</p>
                    ${orderData.pf_mentiuni ? `<p><strong>Mențiuni:</strong> ${orderData.pf_mentiuni}</p>` : ""}
               `;
		} else {
			deliveryAddressHTML = `
                    <p><strong>Firmă:</strong> ${orderData.pj_nume_firma}</p>
                    <p><strong>CUI:</strong> ${orderData.pj_cui}</p>
                    <p><strong>Nr. Reg. Com.:</strong> ${orderData.pj_nr_reg}</p>
                    <p><strong>Adresă facturare:</strong> ${orderData.pj_adresa}, ${orderData.pj_localitate}, ${
				orderData.pj_judet
			}</p>
                    <p><strong>Adresă livrare:</strong> ${orderData.pj_adresa_livrare}</p>
                    <p><strong>Telefon:</strong> ${orderData.pj_numar_telefon}</p>
                    <p><strong>Bancă:</strong> ${orderData.pj_banca} - ${orderData.pj_iban}</p>
                    ${orderData.pj_mentiuni ? `<p><strong>Mențiuni:</strong> ${orderData.pj_mentiuni}</p>` : ""}
               `;
		}

		const emailHTML = `
               <!DOCTYPE html>
               <html>
               <head>
                    <meta charset="UTF-8">
                    <style>
                         body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; margin: 0; padding: 0; }
                         .container { max-width: 650px; margin: 0 auto; padding: 20px; background-color: #ffffff; }
                         .header { background: linear-gradient(135deg, #007bff 0%, #2da4d0ff 100%); color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0; }
                         .header h1 { margin: 0; font-size: 28px; }
                         .content { padding: 30px; background-color: #f9f9f9; }
                         .order-info { background-color: white; padding: 20px; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
                         .order-info h2 { color: #007bff; margin-top: 0; border-bottom: 2px solid #007bff; padding-bottom: 10px; }
                         table { width: 100%; border-collapse: collapse; background-color: white; margin: 20px 0; }
                         th { background-color: #007bff; color: white; padding: 12px; text-align: left; }
                         .totals { background-color: white; padding: 20px; border-radius: 8px; margin-top: 20px; }
                         .totals-row { display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #eee; }
                         .totals-row.final { font-size: 20px; font-weight: bold; color: #007bff; border-bottom: none; margin-top: 10px; }
                         .footer { text-align: center; padding: 20px; color: #666; font-size: 14px; }
                         .success-badge { background-color: #4caf50; color: white; padding: 10px 20px; border-radius: 20px; display: inline-block; margin: 20px 0; }
                    </style>
               </head>
               <body>
                    <div class="container">
                         <div class="header">
                              <h1>✅ Comanda Ta a Fost Plasată!</h1>
                              <div class="success-badge">Comandă Confirmată</div>
                         </div>
                         
                         <div class="content">
                              <div class="order-info">
                                   <h2>📦 Detalii Comandă</h2>
                                   <p><strong>ID Comanda:</strong> ${orderData.id}</p>
                                   <p><strong>Status:</strong> <span style="color: green; font-weight: bold;">Achitat</span></p>
                                   <p><strong>Data:</strong> ${new Date().toLocaleDateString("ro-RO", {
								year: "numeric",
								month: "long",
								day: "numeric",
								hour: "2-digit",
								minute: "2-digit",
							})}</p>
                              </div>

                              <div class="order-info">
                                   <h2>📍 Adresă Livrare</h2>
                                   ${deliveryAddressHTML}
                              </div>

                              <div class="order-info">
                                   <h2>🛒 Produse Comandate</h2>
                                   <table>
                                        <thead>
                                             <tr>
                                                  <th>Produs</th>
                                                  <th style="text-align: center;">Cantitate</th>
                                                  <th style="text-align: right;">Preț unitar</th>
                                                  <th style="text-align: right;">Total</th>
                                             </tr>
                                        </thead>
                                        <tbody>
                                             ${productsHTML}
                                             <tr>
                                                  <td style="padding: 12px; border-bottom: 1px solid #eee;">
                                                       <strong>Transport</strong>
                                                  </td>
                                                  <td style="padding: 12px; border-bottom: 1px solid #eee; text-align: center;">1</td>
                                                  <td style="padding: 12px; border-bottom: 1px solid #eee; text-align: right;">${transport.toFixed(
											2
										)} RON</td>
                                                  <td style="padding: 12px; border-bottom: 1px solid #eee; text-align: right;"><strong>${transport.toFixed(
											2
										)} RON</strong></td>
                                             </tr>
                                        </tbody>
                                   </table>
                              </div>

                              <div class="totals">
                                   <div class="totals-row">
                                        <span>Subtotal produse:</span>
                                        <span>${subtotal.toFixed(2)} RON</span>
                                   </div>
                                   <div class="totals-row">
                                        <span>Transport:</span>
                                        <span>${transport.toFixed(2)} RON</span>
                                   </div>
                                   TVA INCLUS (21%) 
                              </div>

                              <div class="order-info" style="background-color: #e3f2fd; border-left: 4px solid #2196f3;">
                                   <p style="margin: 0;"><strong>ℹ️ Ce urmează?</strong></p>
                                   <p style="margin: 10px 0 0 0;">Comanda ta va fi pregătită pentru livrare în cel mai scurt timp posibil!</p>
                              </div>
                         </div>

                         <div class="footer">
                              <p>Mulțumim pentru comandă!</p>
                              <p><strong>emagyl.ro</strong> | contact@emagyl.ro</p>
                              <p style="font-size: 12px; color: #999;">Acest email a fost trimis automat. Te rugăm să nu răspunzi la acest mesaj.</p>
                         </div>
                    </div>
               </body>
               </html>
          `;

		// Trimite emailul
		await transporter.sendMail({
			from: `"emagyl.ro" <noreply@emagyl.ro>`,
			to: orderData.billingType === 0 ? orderData.pf_email : orderData.pj_email,
			subject: `✅ Comandă confirmată - emagyl.ro`,
			html: emailHTML,
		});

		console.log(
			"Email trimis cu succes către:",
			orderData.billingType === 0 ? orderData.pf_email : orderData.pj_email
		);
		return true;
	} catch (error) {
		console.error("Eroare la trimiterea emailului:", error);
		return false;
	}
}

async function getCargusToken() {
	const response = await fetch(`https://urgentcargus.azure-api.net/api/LoginUser`, {
		method: "POST",
		headers: {
			"Content-Type": "application/json",
			"Ocp-Apim-Subscription-Key": "18c8a73674984390b1a723f55597e6a8",
		},
		body: JSON.stringify({
			UserName: "magyl_emag",
			Password: "emag123",
		}),
	});

	if (!response.ok) {
		throw new Error("Autentificare Cargus eșuată");
	}

	const token = await response.text();
	return token.replace('"', " ");
}

async function generateCargusAWB(order, items) {
	try {
		const token = (await getCargusToken()).replace('"', " ");

		let parts = order.pf_judet_oras.split(",");
		let judet = parts[0].trim();
		let localitate = parts[1] ? parts[1].trim() : "";
          const cashAmount = order.payment_method === 'ramburs' ? parseFloat(order.total_amount) : 0; 

		const body = {
			DeliveryPudoPoint: 0,
			ConsumerReturnType: 0,
			ReturnCodeExpirationDays: 0,
			SenderClientId: null,
			TertiaryClientId: null,
			TertiaryLocationId: 0,

			Sender: {
				LocationId: 201636888,
				Name: "AVEX ONLINE SRL",
				CountyId: 0,
				CountyName: "Alba",
				LocalityId: 0,
				LocalityName: "Petresti",
				StreetId: 0,
				StreetName: "Mihai Viteazu 84, Petrești, jud. Alba",
				BuildingNumber: "84",
				AddressText: "Mihai Viteazu 84, Petrești, jud. Alba",
				ContactPerson: "Gestionar Depozit Avex",
				PhoneNumber: "0771163254",
				Email: "comenzi@avex.ro",
				PostalCode: "515850",
				CountryId: 642,
			},

			Recipient: {
				LocationId: 0,
				Name:
					order.billingType === 0 ? order.pf_nume_familie + " " + order.pf_prenume : order.pj_nume_firma,
				CountyId: 0,
				CountyName: order.billingType === 0 ? judet : order.pj_judet,
				LocalityId: 0,
				LocalityName: order.billingType === 0 ? localitate : order.pj_localitate,
				StreetId: 0,
				StreetName: order.billingType === 0 ? order.pf_adresa : order.pj_adresa_livrare,
				BuildingNumber: "-",
				AddressText: order.billingType === 0 ? order.pf_adresa : order.pj_adresa_livrare,
				ContactPerson:
					order.billingType === 0 ? order.pf_nume_familie + " " + order.pf_prenume : order.pj_nume_firma,
				PhoneNumber: order.billingType === 0 ? order.pf_numar_telefon : order.pj_numar_telefon,
				Email: order.billingType === 0 ? order.pf_email : order.pj_email,
				PostalCode: "107255",
				CountryId: 642,
			},

			Parcels: 1,
			Envelopes: 0,
			TotalWeight: 1,

			ServiceId: 1, // Standard
			DeclaredValue: 0,

			CashRepayment: cashAmount,
			BankRepayment: 0,
			OtherRepayment: "",
			BarCodeRepayment: "",

			PaymentInstrumentId: 0,
			PaymentInstrumentValue: 0,
			HasTertReimbursement: false,

			OpenPackage: false,
			ShipmentPayer: order.payment_method === 'ramburs' ? 0 : 1, // 1 = expeditor
			ShippingRepayment: 0,

			SaturdayDelivery: false,
			MorningDelivery: false,
			HasNonStandardParcel: false,
			DeliveryTime: 0,

			Observations: "",
			PackageContent: "Produse",
			CustomString: order.netopia_payment_id,

               ParcelCodes: items.map((item) => {
                  return {
                     Code: item.sku,
                     Type: 1, // Standard
                     Weight: 1,
                     Length: 30,
                     Width: 20,
                     Height: 10,
                     ParcelContent: item.name,
                     NetAmount:0,
                  };
               }), 

			SenderReference1: "REF-SENDER-001",
			RecipientReference1: "REF-CLIENT-001",
			RecipientReference2: "",
			InvoiceReference: "",

			Length: 30,
			Width: 20,
			Height: 10,
		};

		const response = await fetch(`https://urgentcargus.azure-api.net/api/Awbs`, {
			method: "POST",
			headers: {
				Authorization: `Bearer ${token}`,
				"Content-Type": "application/json",
				"Ocp-Apim-Subscription-Key": "18c8a73674984390b1a723f55597e6a8",
			},
			body: JSON.stringify(body),
		});

		if (!response.ok) {
			const err = await response.text();
			throw new Error("Eroare creare AWB: " + err);
		}

		const result = await response.json();

		if (result) {
			const responsePDF = await fetch(
				"https://urgentcargus.azure-api.net/api/AwbDocuments?barCodes=" + result + "&type=PDF&format=0&printOneAwbPerPage=1",
				{
					method: "GET",
					headers: {
						Authorization: `Bearer ${token}`,
						"Content-Type": "application/json",
						"Ocp-Apim-Subscription-Key": "18c8a73674984390b1a723f55597e6a8",
						"Accept-Encoding": "identity",
					},
				}
			);

			if (!responsePDF.ok) {
				throw new Error(`Cargus API error: ${responsePDF.status} ${responsePDF.statusText}`);
			}

			// Citește răspunsul ca text
			const responseText = await responsePDF.text();

			console.log("📦 Lungime răspuns:", responseText.length);
			console.log("📦 Primele 100 chars:", responseText.substring(0, 100));

			let pdfBuffer;

			try {
				// Parsează JSON-ul
				const json = JSON.parse(responseText);

				// JSON-ul este un STRING (nu array, nu object cu Content)
				// Deci json însuși este stringul Base64
				const base64String = typeof json === "string" ? json : JSON.stringify(json);

				console.log("📦 Tip JSON:", typeof json);
				console.log("📦 Lungime Base64:", base64String.length);
				console.log("📦 Primele 50 chars Base64:", base64String.substring(0, 50));

				// Decodează Base64
				pdfBuffer = Buffer.from(base64String, "base64");
			} catch (error) {
				console.error("❌ Eroare parsare JSON:", error.message);
				throw new Error("Nu pot parsa răspunsul de la Cargus");
			}

			// Validează PDF
			const pdfHeader = pdfBuffer.slice(0, 10).toString("ascii");
			console.log("📄 Header PDF:", pdfHeader);

			if (!pdfHeader.startsWith("%PDF")) {
				console.error("❌ PDF invalid! Primii 200 bytes:");
				console.error("HEX:", pdfBuffer.slice(0, 200).toString("hex"));
				console.error("ASCII:", pdfBuffer.slice(0, 200).toString("ascii"));

				fs.writeFileSync("./cargus_corrupted.pdf", pdfBuffer);
				console.log("⚠️ PDF salvat în: cargus_corrupted.pdf");

				throw new Error("PDF-ul primit nu este valid");
			}

			console.log("✅ PDF valid, mărime:", pdfBuffer.length, "bytes");

			// Upload în S3
			const s3 = new AWS.S3();
			const fileName = `awb/cargus/${order.id}_${result}.pdf`;

			const s3Params = {
				Bucket: process.env.AWS_S3_BUCKET || "emagyl",
				Key: fileName,
				Body: pdfBuffer,
				ContentType: "application/pdf",
				ContentDisposition: `inline; filename="AWB_${result}.pdf"`,
				ACL: "public-read",
			};

			console.log("📤 Upload AWB Cargus PDF în S3...");
			const uploadResult = await s3.upload(s3Params).promise();

			const formattedUrl = uploadResult.Location.replace(
				"https://emagyl.s3.eu-north-1.amazonaws.com",
				"https://d372xxb7fb1cod.cloudfront.net"
			);

               order.awbNumber = result;
			order.awbUrl = formattedUrl;
			await order.save();

               try {
				console.log("📦 Start procesare comandă AVEX...");
				await processAvexOrder(order, items);
				console.log("✅ Comandă AVEX procesată");
			} catch (avexError) {
				console.error("⚠️ Eroare AVEX (non-critical):", avexError.message);
			}

               try {
                    console.log("📦 Procesare comandă DEPOX EasySales...");
                    await processDepoxOrder(order, items);
                    console.log("✅ Comandă DEPOX trimisă la EasySales");
               } catch (depoxError) {
                    console.error("⚠️ Eroare EasySales DEPOX (non-critical):", depoxError.message);
               }

			console.log("✅ AWB Cargus salvat:", formattedUrl);
		}

	
	} catch (error) {
		console.error("❌ Eroare generare AWB Cargus:", error.message);
	}
}

async function processDepoxOrder(order, items) {
     try {
          // Token Basic base64(user:pass)
          const credentials = Buffer.from(
               `2FECMRvktwXDLqZYoysa:eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIwZDcwNTM2MS03YWJhLTQ3ZDgtYTg4Yy05OTI3NGNmNWQ5YzUiLCJqdGkiOiI4MzYxNTQ4ZGZlNTViMmQ2NTg0ZDQ0MGY5ZjBiNDkyZjBjOGU4OTUwOGNhZTI0YTU1NGExYWJhNTIwYzYwOTVlOTBlYjk5ODI0OTYxMzgyNSIsImlhdCI6MTc3NTQ4NDAzMCwibmJmIjoxNzc1NDg0MDMwLCJleHAiOjE4MDcwMjAwMzAsInN1YiI6IjQ0NSIsInNjb3BlcyI6WyJ1cGRhdGUtb3JkZXJzIl19.K5I9VwlJZr_N1qUPO8o2ZirD_BNQV8SosUSHdbMpGQIkp4XFvqt7L-bNn3NvoEz2zMc-x837dwzwpzHyNxIKnLoQxOAhCewtojrVTsbiYmmYITJOVp6gGmlkFPFrjGxvuUmddX7AQ-anN_ps0JBaJRsyvxCiywdR_BWAE0BgV_9BVYySDYm49LivewcjCjKOLlRpXQIdA-4bI3oOwluuWVR3qfaNhHxpp0cOzVmtea1Hj5nuuv3C2gdaFXyL3UpUpKkwV-sESiOs9ectGNIFStO68h6B_hvGjXrQneZRhCZZT5yLmdJ4VjmqeiXX07ClhFfHAhWLIUXHIlX9IcMgMTRyCpi4eRXhkvVvqXClVmNQ0uUP7VSrSu99TwD-Rs8IjDAMX5Xy7mmMFSSWf9kcx8sLCytMUxEmm4SwLrqI3X9G60tDs_kaZgFfoGilqHjIa5hiMmhO-X9NVf6rCyCiCF7cmalAM0znqinGID1bKj2nGYCc-OhEVox-4ayFy7-C7iN0yg0pQ9UJwipNMoYdxgHmybzIWzyZvH9TGj-NQlLDWvRf-NzRw9TxrZtf3WVq9QfEiwQtKlqg44T-Wo3W4dxYkyTXiZHSfCdomsaTKhhkJ4lKzThwViIOc3jJt2w-2ecuOl40xQrGKr9XElTGQIT7u0Ot11li-_fhLJgopWM`
          ).toString("base64");

          // Determină adresa de livrare
          const isCompany = order.billingType === 1;

          const shippingName = isCompany
               ? order.pj_nume_firma
               : `${order.pf_nume_familie} ${order.pf_prenume}`;

          const shippingPhone = isCompany
               ? order.pj_numar_telefon
               : order.pf_numar_telefon;

          const shippingAddress = isCompany
               ? order.pj_adresa_livrare || order.pj_adresa
               : order.pf_adresa;

          const shippingCity = isCompany
               ? order.pj_localitate
               : (order.pf_judet_oras?.split(",")?.[1]?.trim() || "");

          const shippingRegion = isCompany
               ? order.pj_judet
               : (order.pf_judet_oras?.split(",")?.[0]?.trim() || "");

          const customerEmail = isCompany
               ? order.pj_email
               : order.pf_email;

          // Filtrează doar produsele DEPOX din comandă
          const depoxItems = [];
          for (const item of items) {
               const product = await db.Products.findOne({
                    where: { sku: item.sku },
                    attributes: ["back_supplier"],
                    raw: true,
               });
               if (product?.back_supplier === "DEPOX") {
                    depoxItems.push(item);
               }
          }

          if (depoxItems.length === 0) {
               console.log("ℹ️ Nicio comandă DEPOX de trimis la EasySales");
               return;
          }

          const payload = {
               orderId: order.id.toString(),
               orderCode: order.id.toString(),
               status: 1, // New
               statusText: "Comanda noua",
               paymentMethod: order.payment_method === "ramburs" ? 2 : 1, // 2=Cash on delivery, 1=Online
               orderDate: new Date().toISOString().slice(0, 10),
               shippingTax: 22.00,

               customer: {
                    isCompany: isCompany,
                    companyIdentifier: isCompany ? order.pj_cui || null : null,
                    companyName: isCompany ? order.pj_nume_firma || null : null,
                    companyRegistrationNumber: isCompany ? order.pj_nr_reg || null : null,
                    phone: shippingPhone || "",
                    name: isCompany ? null : shippingName,
                    identificationNumber: null,
                    email: customerEmail || "",
                    bank: isCompany ? order.pj_banca || "" : "",
                    iban: isCompany ? order.pj_iban || "" : "",
                    fax: "",
               },

               billingAddress: {
                    name: shippingName,
                    phone: shippingPhone || "",
                    country: "RO",
                    region: shippingRegion,
                    city: shippingCity,
                    address: shippingAddress || "",
                    postalCode: "",
               },

               shippingAddress: {
                    name: shippingName,
                    phone: shippingPhone || "",
                    country: "RO",
                    region: shippingRegion,
                    city: shippingCity,
                    address: shippingAddress || "",
                    postalCode: "",
               },

               vouchers: [],

               products: depoxItems.map((item) => ({
                    offerId: item.sku,
                    name: item.name,
                    price: parseFloat(item.priceReduced || item.price),
                    tax: 0.21,
                    quantity: parseInt(item.quantity),
               })),
          };

          console.log("📦 Trimitere comandă DEPOX la EasySales...");

          const response = await axios.post(
               "https://api.easy-sales.com/api/orders",
               payload,
               {
                    headers: {
                         "Authorization": `Basic ${credentials}`,
                         "Content-Type": "application/json",
                         "Accept": "application/json",
                    },
                    timeout: 30000,
               }
          );

          console.log("✅ EasySales DEPOX response:", response.data);

          // Dacă are AWB generat, trimitem și AWB-ul
          if (order.awbUrl && order.awbNumber) {
               await sendDepoxAwbToEasySales(
                    order.id.toString(),
                    order.awbUrl,
                    order.awbNumber,
                    credentials
               );
          }

          // Dacă are factură, trimitem și factura
          if (order.bill && order.bill_number) {
               await sendDepoxInvoiceToEasySales(
                    order.id.toString(),
                    order.bill,
                    order.bill_number,
                    credentials
               );
          }

          return response.data;

     } catch (error) {
          console.error("❌ Eroare EasySales DEPOX:", {
               message: error.message,
               status: error.response?.status,
               data: error.response?.data,
          });
          throw error;
     }
}

async function sendDepoxAwbToEasySales(orderId, awbUrl, awbNumber, credentials) {
     try {
          const response = await axios.post(
               "https://api.easy-sales.com/api/orders/awb",
               {
                    orderId: orderId,
                    url: awbUrl,
                    awbNumber: awbNumber,
               },
               {
                    headers: {
                         "Authorization": `Basic ${credentials}`,
                         "Content-Type": "application/json",
                         "Accept": "application/json",
                    },
                    timeout: 15000,
               }
          );
          console.log("✅ AWB trimis la EasySales DEPOX:", response.data);
     } catch (error) {
          console.error("⚠️ Eroare trimitere AWB EasySales:", error.response?.data || error.message);
     }
}

async function sendDepoxInvoiceToEasySales(orderId, billUrl, billNumber, credentials) {
     try {
          const response = await axios.post(
               "https://api.easy-sales.com/api/orders/invoice",
               {
                    orderId: orderId,
                    url: billUrl,
                    invoiceNumber: billNumber,
               },
               {
                    headers: {
                         "Authorization": `Basic ${credentials}`,
                         "Content-Type": "application/json",
                         "Accept": "application/json",
                    },
                    timeout: 15000,
               }
          );
          console.log("✅ Factură trimisă la EasySales DEPOX:", response.data);
     } catch (error) {
          console.error("⚠️ Eroare trimitere factură EasySales:", error.response?.data || error.message);
     }
}

async function processAvexOrder(order, items) {
	try {
		const awbUrl = order.awbUrl;
		const awbResponse = await axios.get(awbUrl, {
			responseType: "arraybuffer",
			timeout: 15000,
		});
		const awbBase64 = Buffer.from(awbResponse.data).toString("base64");

		const avexPayload = {
			order_id: order.id,
			notes: order.pf_mentiuni || order.pj_mentiuni || "Comanda online",
			recipient:
				order.pf_nume_familie && order.pf_prenume
					? `${order.pf_nume_familie} ${order.pf_prenume}`
					: order.pj_nume_firma,
			products: items.map((item) => ({
				product_code: item.sku,
				amount: parseInt(item.quantity),
			})),
			awb: {
				file_content: awbBase64,
			},
		};

		const avexResponse = await axios.post("https://api.avex.ro/orders/add_order", avexPayload, {
			headers: {
				"Content-Type": "application/json",
				Authorization: `Bearer 1d06b62740f9e27b6a089bd6d22cc0.61481173qkiOyHtrxJYJVDBfTixNJLAC3`,
			},
			timeout: 30000,
		});

		console.log("AVEX response:", avexResponse.data);

		if (avexResponse.data && avexResponse.data.id) {
			order.avex_order_id = avexResponse.data.id;
			await order.save();
		}
	} catch (avexError) {
		console.error("Eroare AVEX:", {
			message: avexError.message,
			status: avexError.response?.status,
			data: avexError.response?.data,
		});
		throw avexError;
	}
}

async function processOrderAsync(orderId) {
	console.log(`🔄 Start procesare asincronă pentru comanda #${orderId}`);
	
	if (!db.initialized) await db.initialize();
	
	try {
		const order = await db.Orders.findByPk(orderId);
		if (!order) {
			console.error("❌ Order not found:", orderId);
			return;
		}

		const orderPlain = order.get({ plain: true });

		// Parse items
		let items;
		try {
			let itemsString = String(orderPlain.items);
			if (itemsString[0] === '"') {
				itemsString = JSON.parse(itemsString);
			}
			items = JSON.parse(itemsString);
		} catch (error) {
			console.error("❌ Parse error items:", error.message);
			return;
		}

		// 1. Trimite email
		try {
			console.log("📧 Trimitere email...");
			await sendOrderConfirmationEmail(orderPlain, items);
			console.log("✅ Email trimis");
		} catch (error) {
			console.error("⚠️ Eroare email:", error.message);
		}

		// 2. Generează factură FGO
		try {
			console.log("📄 Generare factură FGO...");
			const fgoResponse = await generateFGOInvoice(order, items);
			if (fgoResponse?.Success) {
				order.bill_number = fgoResponse.Factura.Numar;
				order.bill_series = fgoResponse.Factura.Serie;
				order.bill = fgoResponse.Factura.Link;
				await order.save();
				console.log("✅ Factură FGO generată");
			}
		} catch (error) {
			console.error("⚠️ Eroare FGO:", error.message);
		}

		// 3. Generează certificat garanție
		try {
			console.log("📜 Generare certificat...");
			const certificateOrder = {
				Denumire: order.pf_nume_familie && order.pf_prenume
					? `${order.pf_nume_familie} ${order.pf_prenume}`
					: order.pj_nume_firma || "Client",
				Adresa: order.pf_adresa || order.pj_adresa || "",
				IdExtern: order.id.toString(),
			};

			const certificateItems = items.map((item) => ({
				Denumire: item.name || "Produs",
				NrProduse: parseInt(item.quantity) || 1,
			}));

			const certificateUrl = await generateWarrantyCertificate(certificateOrder, certificateItems);
			const formattedUrl = certificateUrl.replace(
				"https://emagyl.s3.eu-north-1.amazonaws.com",
				"https://d372xxb7fb1cod.cloudfront.net"
			);

			order.certificate = formattedUrl;
			await order.save();
			console.log("✅ Certificat generat");
		} catch (error) {
			console.error("⚠️ Eroare certificat:", error.message);
		}

		// 4. Generează PDF instrucțiuni
		try {
			console.log("📄 Generare PDF instrucțiuni...");
			const instructionsUrl = await generateInstructionsPDF(order, items);
			const formattedUrl = instructionsUrl.replace(
				"https://emagyl.s3.eu-north-1.amazonaws.com",
				"https://d372xxb7fb1cod.cloudfront.net"
			);

			order.informations = formattedUrl;
			await order.save();
			console.log("✅ PDF instrucțiuni generat");
		} catch (error) {
			console.error("⚠️ Eroare PDF instrucțiuni:", error.message);
		}

		// 5. Generează AWB Cargus
		try {
			console.log("📦 Generare AWB Cargus...");
			await generateCargusAWB(order, items);
			console.log("✅ AWB Cargus generat");
		} catch (error) {
			console.error("⚠️ Eroare AWB Cargus:", error.message);
		}

		console.log(`✅ Procesare asincronă completă pentru #${orderId}`);

	} catch (error) {
		console.error(`❌ Eroare procesare asincronă pentru #${orderId}:`, error);
	}
}

export default async function handler(req, res) {
	if (req.method !== "POST") {
		return res.status(405).json({ error: "Method not allowed" });
	}

	const { orderId } = req.body;

	if (!orderId) {
		return res.status(400).json({ error: "Missing orderId" });
	}

	console.log(`🔄 Start procesare background pentru comanda #${orderId}`);

	// Răspunde rapid că am primit request-ul
	res.status(200).json({ success: true, message: "Processing started" });

	// Procesează comanda
	try {
		if (!db.initialized) await db.initialize();

		const order = await db.Orders.findByPk(orderId);
		if (!order) {
			console.error("❌ Order not found:", orderId);
			return;
		}

		const orderPlain = order.get({ plain: true });

		// Parse items
		let items;
		try {
			let itemsString = String(orderPlain.items);
			if (itemsString[0] === '"') {
				itemsString = JSON.parse(itemsString);
			}
			items = JSON.parse(itemsString);
		} catch (error) {
			console.error("❌ Parse error items:", error.message);
			return;
		}

		await processOrderAsync(orderId); 

		console.log(`✅ Procesare completă pentru #${orderId}`);

	} catch (error) {
		console.error(`❌ Eroare procesare #${orderId}:`, error);
	}
}