Subversion Repositories SmartDukaan

Rev

Rev 35971 | Blame | Compare with Previous | Last modification | View Log | RSS feed

$(document).on('click', ".onboarding-form1", function () {
    doGetAjaxRequestHandler(`${context}/loiForm`,
        function (response) {
            $('#' + 'main-content').html(response);
        });
});


$(document).on('change', "#maritalStatus", function () {
    let maritalStatus = $(this).val();
    if (maritalStatus == 1) {
        $(".loiAnniversaryDate").removeClass('hide-model');
        $(".loiAnniversaryDate").addClass('show-model');
    } else {
        $(".loiAnniversaryDate").removeClass('show-model');
        $(".loiAnniversaryDate").addClass('hide-model');
    }

});


$(document).on('click', ".mk_submit_loi_form", function () {
    // Gather input values
    const referId = $('select[name="referId"]').val();
    const stateHead = $('select[name="stateHead"]').val();
    const bdm = $('select[name="bdm"]').val();
    let billingAddress = $('select[name="billingAddress"]').val();
    if(!billingAddress){
        const addrFieldData = {
            "bno": "",
            "bnm": "",
            "st": "",
            "locality": "",
            "loc": "",
            "dst": "",
            "pncd": "",
            "stcd": ""
        };

        // Dynamically create input fields
        let address = [];
        Object.keys(addrFieldData).forEach(function (field) {
             addrFieldData[field] = $('input[name="'+field+'"]').val();
        });
        billingAddress = JSON.stringify(addrFieldData);

    }
    const acquiredDate = $('input[name="acquiredDate"]').val();
    const firstName = $('input[name="firstName"]').val();
    const lastName = $('input[name="lastName"]').val();
    const mobile = $('input[name="mobile"]').val();

    // validate email pattern
    const emailValue = $('input[name="email"]').val();
    var email;
    if (emailValue.length > 0) {
        if (isValidEmail(emailValue)) {
            email = emailValue;
        } else {
            alert("Please check your Email Address");
            return;
        }
    }
    const landline = $('input[name="landline"]').val();
    const dob = $('input[name="dob"]').val();
    var today = new Date();
    var birthDate = new Date(dob);
    var age = today.getFullYear() - birthDate.getFullYear();
    var monthDiff = today.getMonth() - birthDate.getMonth();

    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    var maritalStatus = $('select[name="maritalStatus"]').val();
    const anniversaryDate = $('input[name="anniversaryDate"]').val();
    const panNo = $('input[name="panNo"]').val();
    const adharNo = $('input[name="adharNo"]').val();
    const gstNo = $('input[name="gstNo"]').val();
    const bankName = $('input[name="bankName"]').val();
    const ifscCode = $('input[name="ifscCode"]').val();
    const accountNo = $('input[name="accountNo"]').val();
    const businessType = $('select[name="businessType"]').val();
    const companyName = $('input[name="companyName"]').val();
    const gstPin = $('input[name="gstPin"]').val();
    const gstState = $('input[name="gstState"]').val();
    const gstCity = $('input[name="gstCity"]').val();
    const gstDistrict = $('input[name="gstDistrict"]').val();
    const agreeWalletValue = $('select[name="agreeWalletValue"]').val();
    const storeArea = $('input[name="storeArea"]').val();
    const storePotential = $('input[name="storePotential"]').val();
    let financeOptions = [];
    document.querySelectorAll(".finance-code-input").forEach(function (input) {
        var code = input.value.trim();
        if (code) {
            financeOptions.push({
                paymentOptionId: parseInt(input.getAttribute("data-payment-option-id")),
                financeCode: code
            });
        }
    });
    let brandCommitment = [];
    var brandCommitmentInputs = document.querySelectorAll(".brand-commitment");
    var hasInvalidQty = false;
    brandCommitmentInputs.forEach(function (input) {
        var commitmentValue = parseInt(input.value);
        if (!isNaN(commitmentValue)) {
            if (commitmentValue > 1000) {
                hasInvalidQty = true;
            }
            brandCommitment.push({
                brandName: input.getAttribute("name"),
                value: commitmentValue
            });
        }
    });
    if (hasInvalidQty) {
        alert("Quantity per brand cannot exceed 1000. Please enter valid quantities.");
        return;
    }
    let totalCommitment = brandCommitment.reduce((total, commitment) => total + commitment.value, 0);
    // Calculate estimated value: total qty × 20000 (average smartphone value)
    let estimatedValue = totalCommitment * 20000;
    let minCommit = estimatedValue >= (0.7 * storePotential);
    const lessCommitReason = $('textarea[name="lessCommitReason"]').val();
    const agreedBrandFees = $('select[name="agreedBrandFees"]').val();
    const values = agreedBrandFees.split(/[-]/); // Split the string
    const brandFee = parseFloat(values[1]);
    const brandFeesCollected = $('input[name="brandFeesCollected"]').val();
    const paymentMode = $('select[name="paymentMode"]').val();
    const paymentReferenceNo = $('input[name="paymentReferenceNo"]').val();
    const feeCollectingDate = $('input[name="feeCollectingDate"]').val();
    const paymentAttachment = $('input[name="paymentAttachment"]').val();

    let missingFields = [];
    if (!firstName) missingFields.push('First Name');
    if (!lastName) missingFields.push('Last Name');
    if (mobile.length < 10 || !mobile) {
        missingFields.push('Mobile number should be 10 digit');
    }
    if (!minCommit) {
        if (!lessCommitReason) missingFields.push('Less Commit Reason');
    }
    if (!maritalStatus) missingFields.push('Marital Status');
    if (maritalStatus == 1) {
        if (!anniversaryDate) missingFields.push('Anniversary Date');
    }
    if (!email) missingFields.push('Email');
    if (!referId) missingFields.push('Refer By');
    if (!bdm) missingFields.push('Bdm');
    if (!stateHead) missingFields.push('State head');
    if (!acquiredDate) missingFields.push('Acquired date');
    if (!dob) missingFields.push('dob(Date of Birth)');
    if (age <= 18) missingFields.push('You must be at least 18 years old to Fill LOI FORM. ');
    if (!panNo) missingFields.push('Pan Number');
    if (!adharNo) missingFields.push('Aadhar Number');
    if (!gstNo) missingFields.push('GST Number');
    if (!bankName) missingFields.push('Bank Name');
    if (!ifscCode) missingFields.push('IFSC code');
    if (!accountNo) missingFields.push('Account Number');
    if (!businessType) missingFields.push('businessType');
    if (!companyName) missingFields.push('Company Name');
    if (!agreeWalletValue) missingFields.push('Agree Wallet Value');
    if (!storeArea) missingFields.push('storeArea');
    if (!storePotential) missingFields.push('Store Potential');
    if (!agreedBrandFees) missingFields.push('Agreed Brand Fees');
    if (!brandFeesCollected) missingFields.push('Brand Fees Collected');
    if (brandFeesCollected > brandFee) missingFields.push('The collected brand fee must not exceed the agreed brand fees.');
    if (!paymentMode) missingFields.push('Payment Mode');
    if (!paymentReferenceNo) missingFields.push('Payment Reference No');
    if (!feeCollectingDate) missingFields.push('Fee Collecting Date');
    if (!paymentAttachment) missingFields.push('Payment screenshot ');
    if (missingFields.length > 0) {
        alert('The following fields are required: ' + missingFields.join(', '));
        return;
    }
    const loiFormData = {
        referId: referId,
        stateHead: stateHead,
        bdm: bdm,
        businessType: businessType,
        acquiredDate: acquiredDate,
        firstName: firstName,
        lastName: lastName,
        mobile: mobile,
        email: email,
        landline: landline,
        dob: dob,
        anniversaryDate: anniversaryDate,
        panNo: panNo,
        adharNo: adharNo,
        gstNo: gstNo,
        bankName: bankName,
        ifscCode: ifscCode,
        accountNo: accountNo,
        companyName: companyName,
        gstPin: gstPin,
        gstState: gstState,
        gstCity: gstCity,
        gstDistrict: gstDistrict,
        agreeWalletValue: agreeWalletValue,
        storeArea: storeArea,
        storePotential: storePotential,
        financeOptions: financeOptions,
        lessCommitReason: lessCommitReason,
        agreedBrandFees: agreedBrandFees,
        brandFeesCollected: brandFeesCollected,
        paymentMode: paymentMode,
        paymentReferenceNo: paymentReferenceNo,
        feeCollectingTimeStamp: feeCollectingDate,
        paymentAttachment: paymentAttachment,
        billingAddress: billingAddress,
        brandCommitment: brandCommitment
    };

    if (confirm("Are you sure to submit the form ?")) {
        doPostAjaxRequestWithJsonHandler(`${context}/submitLoiForm`, JSON.stringify(loiFormData), function (response) {
            console.log('responsee', response);
            if (response) {
                alert("Your LOI form Submitted successfully ");
                pendingLoiForm("main-content");

            } else {
                alert("Your LOI form not Submitted , try again ");
                doGetAjaxRequestHandler(`${context}/loiForm`,
                    function (response) {
                        $('#' + 'main-content').html(response);
                    });
            }
        });
    }
});

$(document).on('click', ".updateLoiForm", function () {
    let loiId = $(this).val();
    doGetAjaxRequestHandler(context + "/updateLoiForm?loiId=" + loiId,
        function (response) {
            $('#' + 'main-content').html(response);
        });
});

$(document).on('click', ".save_agree_brand_fee", function () {
    let loiId = $(this).val();
    var $tr = $(this).closest('tr');
    var agreedBrandFee = $tr.find('input[name="brandFee"]').val();
    var brandType = $tr.find('select[name="brandType"]').val();
    if (confirm("Are you sure to change Agreed brand fee")) {
        doPutAjaxRequestHandler(`${context}/updateAgreedBrandFee?loiId=${loiId}&brandFee=${agreedBrandFee}&storeType=${brandType}`, function (response) {
            pendingLoiForm("main-content");
        });
    } else {
        pendingLoiForm("main-content");
    }
});

$(document).on('click', ".updateLoiFormDataButton", function () {
    let loiId = $(this).data('loiid');
    const firstName = $('input[name="firstName"]').val();
    const lastName = $('input[name="lastName"]').val();
    const mobile = $('input[name="mobile"]').val();
    const email = $('input[name="email"]').val();
    const landline = $('input[name="landline"]').val();
    const dob = $('input[name="dob"]').val();
    const panNo = $('input[name="panNo"]').val();
    const adharNo = $('input[name="adharNo"]').val();
    let missingFields = [];
    if (!firstName) missingFields.push('First Name');
    if (!lastName) missingFields.push('Last Name');
    if (mobile.length < 10 || !mobile) {
        missingFields.push('Mobile number should be 10 digit');
    }
    if (!dob) missingFields.push('dob(Date of Birth)');
    if (!panNo) missingFields.push('Pan Number');
    if (!adharNo) missingFields.push('Aadhar Number');
    if (!email) missingFields.push('Email');
    if (missingFields.length > 0) {
        alert('The following fields are required: ' + missingFields.join(', '));
        return;
    }
    const loiFormData = {
        firstName: firstName,
        lastName: lastName,
        mobile: mobile,
        email: email,
        landline: landline,
        dob: dob,
        panNo: panNo,
        adharNo: adharNo
    };
    alert("you want update ..");
    doPostAjaxRequestWithJsonHandler(`${context}/updateLoiFormData?loiId=${loiId}`, JSON.stringify(loiFormData), function (response) {
        pendingLoiForm("main-content");
    });

});

$(document).on('click', ".pending-onboarding-form", function () {
    doGetAjaxRequestHandler(`${context}/pendingLoiForm`,
        function (response) {
            $('#' + 'main-content').html(response);
        });
});
$(document).on('click', "#addBrandFeePayment", function () {
    var $btn = $(this);
    if ($btn.prop('disabled')) return false;
    let formData = objectifyForm($("form[name='brandFeeCollectionForm']").serializeArray());
    let loiId = $btn.val();
    for (var key in formData) {
        if (formData.hasOwnProperty(key) && formData[key].trim() === '') {
            alert("The (" + key + ") value is blank please fill this field !");
            return false;
        }
    }
    let jsonData = JSON.stringify(formData);
    if (confirm("Are you sure to add payment ?")) {
        $btn.prop('disabled', true);
        doPostAjaxRequestWithJsonHandler(`${context}/brandfeeCollection?loiId=` + loiId, jsonData, function (response) {
            if (response) {
                alert("Payment add successfully...");
                $('#brandFeeCollectionModel').modal('hide');
                pendingLoiForm("main-content");
            }
            $btn.prop('disabled', false);
        });
    } else {
        alert("Payment is not add.");
    }
});

$(document).on('click', ".generateLoi", function () {
    let loiId = $(this).val();
    doGetAjaxRequestHandler(context + "/generateLoi?loiId=" + loiId,
        function (response) {
            $('#' + 'main-content').html(response);
        });
});

// $(document).on('change', 'select[name="pageSize"]', function () {
//     let pageSize = $(this).val();
//     console.log("pageSize - ", pageSize);
//     doGetAjaxRequestHandler(`${context}/pendingLoiForm?pageSize=${pageSize}&pageNumber=${1}`,
//         function (response) {
//             $('#' + 'main-content').html(response);
//         });
// });

$(document).on('click', ".mk-approve-loi", function () {
    let loiId = $(this).val();
    let companyName = $(this).data('company');
    let flag = $(this).data('flag');
    if (flag === 1) {
        if (confirm(`Are you sure Approve Loi of  ${companyName} `)) {
            doPutAjaxRequestHandler(`${context}/approve-reject-Loi?loiId=${loiId}&flag=${true}`,
                function (response) {
                    alert("Loi Approved successfully");
                    pendingLoiForm("main-content");
                });
        }
    } else {
        if (confirm(`Are you sure to Reject "${companyName}" LOI`)) {
            doPutAjaxRequestHandler(`${context}/approve-reject-Loi?loiId=${loiId}&flag=${false}`,
                function (response) {
                    pendingLoiForm("main-content");
                });
        }
    }
});

var otpCountdownTimer = null;

function startResendCountdown(btn) {
    var remaining = 30;
    btn.prop('disabled', true).removeClass('btn-success').addClass('btn-warning');
    btn.text('Resend OTP (' + remaining + 's)');
    otpCountdownTimer = setInterval(function () {
        remaining--;
        if (remaining <= 0) {
            clearInterval(otpCountdownTimer);
            otpCountdownTimer = null;
            btn.text('Resend OTP').prop('disabled', false);
        } else {
            btn.text('Resend OTP (' + remaining + 's)');
        }
    }, 1000);
}

$(document).on('click', "#LOI_otp", function () {
    let btn = $(this);
    let loiId = btn.val();
    if (otpCountdownTimer) return;
    let isResend = btn.text().indexOf('Resend') >= 0;
    if (!isResend && !confirm("Are you sure to send OTP ?")) return;
    btn.prop('disabled', true).text('Sending...');
    doPostAjaxRequestHandler(`${context}/loiAcceptanceOtp?loiId=` + loiId,
        function (response) {
            $('#otp_status').show().text('OTP Sent Successfully!');
            startResendCountdown(btn);
        });
});

//confirmPayment
$(document).on('click', ".paymentConfirmBtn", function () {
    let approval = $(this).data('approval');
    let bfcId = $(this).val();
    let description = "All details are correct";
    if (confirm("Are you sure to confirm this payment ?")) {
        doPutAjaxRequestHandler(`${context}/feePaymentApproval?bfcId=${bfcId}&feePaymentStatus=${approval}&description=${description}`,
            function (response) {
                alert("Payment is confirm successfully");
                pendingLoiForm("main-content");
            });
    }
});

$(document).on('click', ".paymentRejectBtn", function () {
    let approval = $(this).data('approval');
    let bfcId = $(this).val();
    let description;
    description = prompt("Reason for rejection..");
    if (description !== null) {
        if (confirm("Are you sure to Reject this payment ?")) {
            doPutAjaxRequestHandler(`${context}/feePaymentApproval?bfcId=${bfcId}&feePaymentStatus=${approval}&description=${description}`,
                function (response) {
                    alert("Payment is rejected successfully");
                    pendingLoiForm("main-content");
                });
        }
    } else {
        alert("Please mention the reason as description and try again");
    }
});
$(document).on('click', ".deleteFeeCollection", function () {
    let bfcId = $(this).val();
    if (confirm("Are you sure you want to delete this payment entry?")) {
        doPutAjaxRequestHandler(
            `${context}/feePaymentDeletion?bfcId=${bfcId}`,
            function (response) {
                alert("Payment entry has been deleted successfully.");
                pendingLoiForm("main-content");
            }
        );
    }
});

$(document).on('click', ".upload-document-form", function () {
    let loiId = $(this).val();
    doGetAjaxRequestHandler(`${context}/uploadDocumentForm?loiId=${loiId}`,
        function (response) {
            $('#' + 'main-content').html(response);
        });
});
$(document).on('input', 'table#OnboardingDocumentTable input[type=file],table#mk_brand-fee-collection-details input[type=file]', function () {
    if (confirm('Confirm file upload ?')) {
        var fileSelector = $(this)[0];
        if (fileSelector != undefined
            && fileSelector.files[0] != undefined) {
            var file = this.files[0];
            let fileInput = $(this);
            uploadDocument(file, function (documentId) {
                fileInput.closest('td').find(".documentId").val(documentId);
            });
        }
    }
});

$(document).on('input', '#payment-sc-doc', function () {
    if (confirm('Confirm file upload ?')) {
        var file = this.files[0];
        uploadDocument(file, function (documentId) {
            $('#payment-sc-docId').val(documentId);
        });
    }
});


$(document).on('click', ".mk_docApproval", function () {
    let loiId = $(this).data('form_id');
    let docMasterId = $(this).data('doc_master_id');
    let flag = $(this).data('flag');
    doPutAjaxRequestHandler(`${context}/documentVerify?loiId=${loiId}&docMasterId=${docMasterId}&flag=${flag}`,
        function (response) {
            alert(response);
            doGetAjaxRequestHandler(`${context}/uploadDocumentForm?loiId=${loiId}`,
                function (response) {
                    $('#' + 'main-content').html(response);
                });

        });
});
$(document).on('click', "#uploadDocumentbtn1", function () {
    if (confirm("Are you sure to upload all documents ?")) {
        var loiId = $(this).val();
        var loiDocModels = [];
        $("#OnboardingDocumentTable > tbody > tr").each(function (rowIndex) {
            var marsterId = $(this).find(".masterId").val();
            var docId = $(this).find(".documentId").val();
            var docName = $(this).find(".documentName").val();
            var loiDocModel = {
                documentId: docId,
                documentName: docName,
                documentMasterId: marsterId
            };
            loiDocModels.push(loiDocModel);
        });
        var loiDocModelData = JSON.stringify(loiDocModels);
        doPostAjaxRequestWithJsonHandler(`${context}/uploadOnboardingDocument?loiId=${loiId}`, loiDocModelData, function (response) {
            pendingLoiForm("main-content");
        });
    } else {
        //Nothing to do
    }


});

$(document).on('click', ".CompletedLoiForm", function () {
    doGetAjaxRequestHandler(`${context}/completedLoiForms`,
        function (response) {
            $('#' + 'main-content').html(response);
        });
});

$(document).on('click', "#createNewOnboardingPanel", function () {
    let loiId = $(this).val();
    //let authId = $(this).closest('tr').find('.authId').val();

    if (true) {

        doPostAjaxRequestHandler(`${context}/createNewOnboardingPanel?loiId=${loiId}&authId=${0}`,
            function (response) {
                if (response) {
                    // doGetAjaxRequestHandler(`${context}/completedLoiForms`,
                    //     function (response) {
                    //         $('#' + 'main-content').html(response);
                    //     });
                    alert("it moved successfully ");
                } else {
                    //nothing
                }

            });
    } else {
        alert("Please choose RBM ");
    }

});

$(document).on('click', "#downloadAllLoiForm", function () {
    const from = $('input[name="from"]').val();
    const to = $('input[name="to"]').val();
    let missingFields = [];
    if (!from) missingFields.push('From date');
    if (!to) missingFields.push('To date');
    if (missingFields.length > 0) {
        alert('Please select : ' + missingFields.join(','));
        return;
    }
    window.location.href = `${context}/downloadLoiFromReport?from=${from}&to=${to}`;
});
$(document).on('click', ".brandFeePaymentEdit", function () {
    var bfcId = $(this).val();

    // Get the table row
    var $row = $(this).closest('tr');
    var feeCollectingTimeStamp = $row.find('input[name="feeCollectingTimeStamp"]').val();
    var collectedAmount = $row.find('input[name="collectedAmount"]').val();
    var paymentReferenceNo = $row.find('input[name="paymentReferenceNo"]').val();
    var paymentMode = $row.find('select[name="paymentMode"]').val();
    var documentId = $row.find('input[name="documentId"]').val();

    const Data = {
        id: bfcId,
        feeCollectingTimeStamp: feeCollectingTimeStamp,
        collectedAmount: collectedAmount,
        paymentReferenceNo: paymentReferenceNo,
        paymentAttachment: documentId,
        paymentMode: paymentMode
    };
    var jsonData = JSON.stringify(Data);
    if (confirm("Are you sure to update details")) {
        doPostAjaxRequestWithJsonHandler(`${context}/updatePayment`, jsonData,
            function (response) {
                if (response) {
                    alert("Updated payment details are save successfully ")
                    pendingLoiForm('main-content');
                } else {
                    alert("Updated payment details are not save ")
                    pendingLoiForm('main-content');
                }
            });
    } else {
        pendingLoiForm('main-content');
    }


});
/*function validateOTP() {
    while (true) {
        let otp = prompt("Enter received OTP here");
        if (otp === null) {
            alert('OTP entry was cancelled. Try again.');
            return null;
        }
        let regex = /^[0-9]{5}$/;
        if (regex.test(otp)) {
            console.log('otp-flag-', otp);
            return otp;  // Return valid OTP
        } else {
            alert('Please enter a valid 5-digit numeric OTP');
        }
    }
}*/

$(document).on('click', "#confirmSign", function () {
    let loiId = $(this).val();
    let otp = prompt("Enter received OTP here");
    let validateOtpUrl = `${context}/validateLoiOtp?loiId=${loiId}&provideOtp=${otp}`;

    if (otp !== undefined && otp !== null) {
        doPutAjaxRequestHandler(validateOtpUrl, function (response) {
            console.log('OTP validation response:', response);

            if (response && response.response && response.response.success) {
                const docHash = (response.response.documentHash || "");
                const ip = response.response.ipAddress || "";
                const createdAt = response.response.createdAt || new Date().toLocaleString();
                const watermarkText =
                    `OTP VERIFIED\n` +
                    `DOCUMENT HASH:\n ${docHash}\n` +
                    `IP ADDRESS: ${ip}\n` +
                    `CREATED ON: ${createdAt}`;
                const originalElement = document.getElementById('loiPDF_content');
                const clonedElement = originalElement.cloneNode(true);
                const existingStyles = clonedElement.querySelectorAll('style');
                existingStyles.forEach(style => style.remove());
                $(clonedElement).find('.pending-badge, .pending-indicator').remove();
                $(clonedElement).find('.signature-section').each(function () {
                    this.style.setProperty('position', 'relative', 'important');
                    this.style.setProperty('padding', '20px', 'important');
                });

                const signatureSections = clonedElement.querySelectorAll('.signature-section');
                signatureSections.forEach(section => {
                    const oldWatermarks = section.querySelectorAll('.watermark-overlay');
                    oldWatermarks.forEach(w => w.remove());

                    const watermarkDiv = document.createElement('div');
                    watermarkDiv.className = 'watermark-overlay';
                    watermarkDiv.textContent = watermarkText;
                    watermarkDiv.style.position = 'absolute';
                    watermarkDiv.style.fontSize = '7px';
                    watermarkDiv.style.top = '30px';
                    watermarkDiv.style.left = '1%';
                    watermarkDiv.style.color = 'rgb(4,97,225)';
                    watermarkDiv.style.fontWeight = 'bold';
                    watermarkDiv.style.fontFamily = 'Arial,sans-serif';
                    watermarkDiv.style.whiteSpace = 'pre-line';
                    watermarkDiv.style.textAlign = 'center';
                    watermarkDiv.style.pointerEvents = 'none';
                    watermarkDiv.style.width = '90%';
                    watermarkDiv.style.lineHeight = '1.7';
                    watermarkDiv.style.zIndex = '1';
                    watermarkDiv.style.userSelect = 'none';

                    section.style.position = 'relative';
                    section.appendChild(watermarkDiv);
                });

                const tempContainer = document.createElement('div');
                tempContainer.style.position = 'absolute';
                tempContainer.style.left = '-9999px';
                tempContainer.style.width = '800px';
                tempContainer.appendChild(clonedElement);
                document.body.appendChild(tempContainer);

                const opt = {
                    margin: [0.5, 0.5, 0.5, 0.5],
                    filename: `LOI_${loiId}_${new Date().getTime()}.pdf`,
                    image: {
                        type: 'jpeg',
                        quality: 0.98
                    },
                    html2canvas: {
                        scale: 1.2,
                        logging: false,
                        useCORS: true,
                        allowTaint: false,
                        backgroundColor: '#ffffff'
                    },
                    jsPDF: {
                        unit: 'in',
                        format: 'letter',
                        orientation: 'portrait'
                    }
                };

                html2pdf().from(clonedElement).set(opt).outputPdf("arraybuffer")
                    .then(function (pdf) {
                        document.body.removeChild(tempContainer);

                        const file = new Blob([pdf], {type: 'application/pdf'});

                        uploadDocument(file, function (documentId) {
                            IdempotencyKey = uuidv4();
                            if (documentId > 0) {
                                saveLoiDoc(loiId, documentId);
                                alert("Document signed and saved successfully!");
                            } else {
                                alert("Something went wrong, please try again to confirm OTP");
                            }
                        });
                    })
                    .catch(function (error) {
                        console.error('PDF generation failed:', error);
                        document.body.removeChild(tempContainer);
                        alert("PDF generation failed. Please try again.");
                    });
            } else {
                console.error('OTP validation failed:', response);
                alert("OTP validation failed: " + (response.response?.message || "Please try again."));
            }
        }, function (error) {
            console.error('AJAX request failed:', error);
            alert("Request failed. Please check your connection and try again.");
        });
    } else {
        return false;
    }
});


function saveLoiDoc(loiId, documentId) {
    let saveLoiDocUrl = `${context}/saveLoiDoc?loiId=` + loiId + `&loiDocId=` + documentId
    doPostAjaxRequestHandler(saveLoiDocUrl, function (response) {
        if (response) {
            alert("LOI has been signed successfully and sent to the registered email. Please check your email.");
            pendingLoiForm("main-content");
        } else {
            alert("Something went wrong , Please try again to generate Loi and Validate otp");
        }
    });
}


function pendingLoiForm(domId) {
    doGetAjaxRequestHandler(`${context}/pendingLoiForm`,
        function (response) {
            $('#' + domId).html(response);
        });
}

/*
function createPagination(containerId, totalPages, currentPage = 1, onPageChange = null) {
    const $container = $('#' + containerId);
    $container.empty(); // Clear the container

    // Helper Function to Render Pagination
    function renderPagination(currentPage) {
        $container.empty();

        // Previous Button
        const $prevButton = $('<button>')
            .text('Previous')
            .click(() => handlePageChange(currentPage > 1 ? currentPage - 1 : totalPages)); // Loop to last page if on the first page
        $container.append($prevButton);

        // First Page
        const $firstPageButton = $('<button>')
            .text('1')
            .addClass(currentPage === 1 ? 'active' : '')
            .click(() => handlePageChange(1));
        $container.append($firstPageButton);

        // Ellipsis Before Current Pages
        if (currentPage > 3) {
            $container.append($('<span>').text('...'));
        }

        // Dynamic Pages Around Current Page
        for (let i = Math.max(2, currentPage - 1); i <= Math.min(totalPages - 1, currentPage + 1); i++) {
            const $pageButton = $('<button>')
                .text(i)
                .addClass(currentPage === i ? 'active' : '')
                .click(() => handlePageChange(i));
            $container.append($pageButton);
        }

        // Ellipsis Before Last Page
        if (currentPage < totalPages - 2) {
            $container.append($('<span>').text('...'));
        }

        // Last Page
        if (totalPages > 1) {
            const $lastPageButton = $('<button>')
                .text(totalPages)
                .addClass(currentPage === totalPages ? 'active' : '')
                .click(() => handlePageChange(totalPages));
            $container.append($lastPageButton);
        }

        // Next Button
        const $nextButton = $('<button>')
            .text('Next')
            .click(() => handlePageChange(currentPage < totalPages ? currentPage + 1 : 1)); // Loop to first page if on the last page
        $container.append($nextButton);
    }

    // Handle Page Change
    function handlePageChange(selectedPage) {
        if (onPageChange) {
            onPageChange(selectedPage); // Trigger the callback with the selected page
        }
        renderPagination(selectedPage); // Re-render pagination
    }

    // Initial Render
    renderPagination(currentPage);
}*/