function showLoader(button) {
    if (!button) return;
    button.disabled = true;
    button.dataset.originalText = button.innerHTML;
    button.innerHTML = '<span class="loader"></span> در حال پردازش...';
}

function hideLoader(button) {
    if (!button) return;
    button.disabled = false;
    button.innerHTML = button.dataset.originalText || "Download";
}
document.addEventListener("DOMContentLoaded", function () {
    let orderId = new URLSearchParams(window.location.search).get("kaveh_download_invoice");
    let nonce = kavehInvoiceData.nonce_download;

    if (orderId) {
        console.log("📜 صفحه فاکتور باز شد، بررسی وضعیت PDF...");

        jQuery.post(kavehInvoiceData.ajax_url, {
            action: "kaveh_check_invoice_pdf",
            order_id: orderId,
            _wpnonce: nonce
        }, function (response) {
            if (response.success && response.data.pdf_url) {
                console.log("✅ PDF موجود است، نیازی به ساخت دوباره نیست.");
            } else {
                console.log("⚠️ PDF یافت نشد، در حال ساخت و ذخیره...");
                generateAndSaveInvoice(orderId, nonce, null, function (pdfUrl) {
                    console.log("📄 PDF ساخته و ذخیره شد:", pdfUrl);
                });
            }
        }).fail(function (xhr, status, error) {
            console.error("🚨 خطا در بررسی PDF:", error);
        });
    }

    async function generateAndSaveInvoice(orderId, nonce, button, callback) {
        console.log("🚀 ذخیره فاکتور برای سفارش:", orderId);
        if (button) showLoader(button);

        let existingInvoice = document.querySelector("#invoice-container");
        if (!existingInvoice) return;

        existingInvoice.style.display = "block";
        existingInvoice.style.width = "680px";
        existingInvoice.style.boxSizing = "border-box";
        existingInvoice.style.overflow = "hidden";
        existingInvoice.style.backgroundColor = "white";

        try {
            const canvas = await html2canvas(existingInvoice, {
                scale: 2,
                width: 680,
                height: 1123,
                backgroundColor: "#fff"
            });

            const imgData = canvas.toDataURL("image/jpeg", 0.9);
            const { jsPDF } = window.jspdf;
            const pdf = new jsPDF({
                orientation: "portrait",
                unit: "mm",
                format: "a4"
            });

            let imgWidth = 210;
            let imgHeight = (canvas.height * imgWidth) / canvas.width;
            pdf.addImage(imgData, "JPEG", 0, 0, imgWidth, imgHeight, "", "FAST");

            let pdfBase64 = pdf.output("datauristring").split(",")[1];

            jQuery.post(kavehInvoiceData.ajax_url, {
                action: "kaveh_save_invoice_pdf",
                order_id: orderId,
                _wpnonce: nonce,
                pdf_data: pdfBase64
            }, function (serverResponse) {
                console.log("✅ PDF ذخیره شد:", serverResponse);
                if (serverResponse.success && callback) {
                    callback(serverResponse.data.pdf_url);
                }
            }).fail(function (xhr, status, error) {
                console.error("🚨 خطا در ذخیره PDF روی سرور:", error);
            }).always(function () {
                if (button) hideLoader(button);
            });

        } catch (error) {
            console.error("⚠️ خطا در تبدیل به تصویر:", error);
            if (button) hideLoader(button);
        }
    }

    function sendPaymentLink(orderId, nonce, button = null) {
        let responseBox = null;
        if (button) {
            responseBox = jQuery("<p>").insertAfter(button).css("margin-top", "10px");
            button.prop("disabled", true).text("⏳ در حال ارسال...");
        }

        jQuery.post(kavehInvoiceData.ajax_url, {
            action: "kaveh_send_payment_link",
            order_id: orderId,
            _wpnonce: nonce
        }, function (response) {
            if (response.success) {
                responseBox?.html("✅ لینک پرداخت ارسال شد!").css("color", "green");
            } else {
                responseBox?.html("❌ خطا: " + response.data.message).css("color", "red");
            }
        }).fail(function () {
            responseBox?.html("❌ خطای سرور، دوباره امتحان کنید.").css("color", "red");
        }).always(function () {
            if (button) button.prop("disabled", false).text("💳 ارسال لینک پرداخت به مشتری");
        });
    }

    function sendInvoiceSMS(orderId, nonce, button = null) {
        if (!orderId || !nonce) return;
        jQuery.post(kavehInvoiceData.ajax_url, {
            action: "kaveh_send_invoice_sms",
            order_id: orderId,
            _wpnonce: nonce
        }, function (response) {
            if (response.success) {
                console.log("📲 پیامک فاکتور ارسال شد.");
            } else {
                console.error("❌ خطا در ارسال پیامک:", response.data.message);
            }
        }).fail(function () {
            console.error("❌ خطای ارتباط با سرور هنگام ارسال پیامک.");
        });
    }

    document.body.addEventListener("click", function (event) {
        let target = event.target.closest(".send-invoice-sms, .send-invoice-email, #download-pdf-btn, #download-image-btn");
        if (!target) return;

        let orderId = target.dataset.orderId;
        let nonce = kavehInvoiceData.nonce_download;
        let noncesms = target.dataset.nonce;
        let nonceemail = target.dataset.nonce;

        if (target.matches("#download-pdf-btn")) downloadInvoicePDF(orderId, nonce, target);
        if (target.matches("#download-image-btn")) downloadInvoiceImage(orderId, target);
        if (target.classList.contains("send-invoice-email")) sendInvoiceEmail(orderId, nonceemail, target);
        if (target.classList.contains("send-invoice-sms")) sendInvoiceSMS(orderId, noncesms, target);
    });

    let previewButton = document.querySelector("#preview-invoice-btn");

    if (previewButton) {
        previewButton.addEventListener("click", function (e) {
            e.preventDefault();
            previewButton.disabled = true;
            previewButton.textContent = "در حال ساخت پیش‌فاکتور...";

            let formData = {
                action: "kaveh_create_guest_order",
                _wpnonce: kavehInvoiceData.pre_invoice,
                billing_first_name: document.querySelector("#billing_first_name")?.value || "",
                billing_last_name: document.querySelector("#billing_last_name")?.value || "",
                billing_email: document.querySelector("#billing_email")?.value || "",
                billing_phone: document.querySelector("#billing_phone")?.value || "",
                billing_address_1: document.querySelector("#billing_address_1")?.value || "",
                billing_city: document.querySelector("#billing_city")?.value || "",
                billing_postcode: document.querySelector("#billing_postcode")?.value || ""
            };

            jQuery.post(kavehInvoiceData.ajax_url, formData, function (response) {
                if (response.success && response.data.order_id) {
                    let orderId = response.data.order_id;
                    let nonce = kavehInvoiceData.nonce_download;
                    let smsNonce = kavehInvoiceData.nonce_sms;

                    sendPaymentLink(orderId, nonce);

                    sendInvoiceSMS(orderId, smsNonce);

                    setTimeout(() => {
                        let invoiceUrl = `${kavehInvoiceData.preview_url}?kaveh_create_guest_order=${orderId}&_wpnonce=${response.data.nonce}`;
                        window.location.href = invoiceUrl;
                    }, 10000);
                } else {
                    alert("⚠️ خطایی رخ داده است: " + response.data.message);
                }
                previewButton.disabled = false;
                previewButton.textContent = "پیش‌نمایش فاکتور";
            }).fail(function () {
                alert("❌ ارتباط با سرور برقرار نشد.");
                previewButton.disabled = false;
                previewButton.textContent = "پیش‌نمایش فاکتور";
            });
        });
    }

    function downloadInvoicePDF(orderId, nonce, button) {
        showLoader(button);
        jQuery.post(kavehInvoiceData.ajax_url, {
            action: "kaveh_check_invoice_pdf",
            order_id: orderId,
            _wpnonce: nonce
        }, function (response) {
            if (response.success && response.data.pdf_url) {
                window.location.href = response.data.pdf_url;
            } else {
                generateAndSaveInvoice(orderId, nonce, button, function (pdfUrl) {
                    window.location.href = pdfUrl;
                });
            }
        }).fail(function () {
            console.error("🚨 خطا در بررسی PDF");
        }).always(function () {
            hideLoader(button);
        });
    }

    function downloadInvoiceImage(orderId, button) {
        showLoader(button);
        let existingInvoice = document.querySelector("#invoice-container");
        if (!existingInvoice) {
            hideLoader(button);
            return;
        }
        html2canvas(existingInvoice, {
            scale: 2,
            backgroundColor: "#fff"
        }).then(canvas => {
            let imgData = canvas.toDataURL("image/png");
            let link = document.createElement("a");
            link.href = imgData;
            link.download = `invoice_${orderId}.png`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }).finally(() => {
            hideLoader(button);
        });
    }
});


    function sendInvoiceEmail(orderId,nonce, button) {
        console.log("📧 ارسال ایمیل برای سفارش:", orderId);
    
        showLoader(button);
    
        jQuery.post(kavehInvoiceData.ajax_url, {
            action: "kaveh_send_invoice_email",
            order_id: orderId,
            _wpnonce: nonce,
        }, function (response) {
            if (response.success) {
            } else {
                if (response.data && response.data.open_invoice) { 
                    console.log("🔄 فاکتور موجود نیست، باز کردن صفحه برای ساخت...");
                    let invoiceWindow = window.open(response.data.open_invoice, "_blank");
    
                    if (!invoiceWindow) {
                    } else {
                        setTimeout(() => {
                            sendInvoiceEmail(orderId, nonce, button);
                        }, 10000);
                    }
                } else {
                    console.error("🚨 خطا در ارسال پیامک:", response.data.message || response.message);
                }
            }
            
        }).fail(function (xhr, status, error) {
            console.error("🚨 خطا در ارسال ایمیل:", error);
        }).always(function () {
            hideLoader(button);
        });
    }
 
    
     function sendInvoiceSMS (orderId, nonce, button) {
        console.log("📲 ارسال پیامک برای سفارش:", orderId);
        showLoader(button);
    
        jQuery.post(kavehInvoiceData.ajax_url, {
            action: "kaveh_send_invoice_sms",
            order_id: orderId,
            _wpnonce: nonce
        }, function (response) {
            if (response.success) {
                console.log("فاکتور با موفقیت ارسال شد");

            } else {
                if (response.data && response.data.open_invoice) { 
                    console.log("🔄 فاکتور موجود نیست، باز کردن صفحه برای ساخت...");
                    let invoiceWindow = window.open(response.data.open_invoice, "_blank");
    
                    if (!invoiceWindow) {
                    } else {
                        setTimeout(() => {
                            sendInvoiceSMS(orderId, nonce, button);
                        }, 10000);
                    }
                } else {
                    console.error("🚨 خطا در ارسال پیامک:", response.data.message || response.message);
                }
            }
        }).fail(function (xhr, status, error) {
            console.error("🚨 خطای AJAX در ارسال پیامک:", error);
        }).always(function () {
            hideLoader(button);
        });
    }
    
    

