Subversion Repositories SmartDukaan

Rev

Rev 37523 | 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);
        });
});


// Format a Date as a local YYYY-MM-DD string (avoids UTC/IST day shift from toISOString)
function toLocalYMD(d) {
    const y = d.getFullYear();
    const m = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    return `${y}-${m}-${day}`;
}

// Parse a "YYYY-MM-DD" string into a LOCAL-midnight Date. `new Date("YYYY-MM-DD")`
// parses as UTC midnight, which in timezones ahead of UTC (e.g. IST +5:30) compares
// as later than local midnight "today" — making today's date wrongly fail the range check.
function parseLocalYMD(s) {
    const [y, m, day] = s.split('-').map(Number);
    return new Date(y, m - 1, day);
}

// Restrict the Acquired Date picker to the last 7 days (today and the 7 days before it).
// The form HTML is injected via AJAX, so set min/max lazily when the field is focused.
// NOTE: native min/max only reliably greys out dates in Chrome's calendar; Firefox/Safari
// still let the user pick an out-of-range date, so we also enforce the range on 'change'.
$(document).on('blur', 'input[name="acquiredDate"]', function () {
    const today = new Date();
    const minDate = new Date();
    minDate.setDate(today.getDate() - 7);
    $(this).attr('max', toLocalYMD(today));
    $(this).attr('min', toLocalYMD(minDate));
});

// Browser-independent guard: if the entered Acquired Date is outside the last 7 days,
// reject it (clear the field) instead of waiting until form submit.
// IMPORTANT: validate on 'blur', NOT 'change'. When a user TYPES into a type="date"
// field, the year is entered one digit at a time, so the field momentarily holds
// complete-but-wrong dates (e.g. 0002-06-16 → 0020-... → 0202-... before 2026-...),
// each of which fires 'change'. Validating on 'change' would reject and clear those
// intermediate years, making manual entry impossible. 'blur' fires only once the
// user has finished editing the field.
$(document).on('blur', 'input[name="acquiredDate"]', function () {
    const picked = $(this).val();
    if (!picked) return;
    const acq = parseLocalYMD(picked);
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const minAllowed = new Date(today);
    minAllowed.setDate(today.getDate() - 7);
    if (acq > today || acq < minAllowed) {
        alert('Acquired date must be within the last 7 days (today or up to 7 days ago).');
        $(this).val('');
    }
});


$(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 onboardingType = $('input[name="loiOnboardingType"]:checked').val() || 'NEW';
    const oldStoreCode = $('#loiOldStoreCode').val() ? $('#loiOldStoreCode').val().trim() : '';
    const revivalReason = $('#loiRevivalReason').val() ? $('#loiRevivalReason').val().trim() : '';
    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 (onboardingType !== 'NEW') {
        if (!revivalReason) {
            missingFields.push(onboardingType === 'ANY_OTHER' ? 'Reason (Any Other)' : 'Reason for Revival');
        }
        if (onboardingType === 'REVIVAL' && !oldStoreCode) {
            missingFields.push('Old Store Code (required for Revival)');
        }
    }
    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');
    } else {
        // Acquired date must fall within the last 7 days (not in the future, not older than 7 days back)
        const acq = parseLocalYMD(acquiredDate);
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        const minAllowed = new Date(today);
        minAllowed.setDate(today.getDate() - 7);
        if (acq > today || acq < minAllowed) {
            missingFields.push('Acquired date must be within the last 7 days');
        }
    }
    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) {
        var screenshotInput = $('#payment-sc-doc')[0];
        if (paymentScreenshotUploading) {
            missingFields.push('Payment screenshot (still uploading - wait for "Attached: ..." under the field)');
        } else if (screenshotInput && screenshotInput.files && screenshotInput.files.length > 0) {
            missingFields.push('Payment screenshot (the file was picked but the upload did not complete - select it again)');
        } else {
            missingFields.push('Payment screenshot');
        }
    }
    if (missingFields.length > 0) {
        alert('The following fields are required: ' + missingFields.join(', '));
        return;
    }
    const loiFormData = {
        onboardingType: onboardingType,
        oldStoreCode: oldStoreCode,
        revivalReason: revivalReason,
        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();
    // paymentAttachment is a hidden field filled by the screenshot upload, so name it
    // the way the operator sees it rather than echoing the raw form key.
    const brandFeeFieldLabels = {
        collectedAmount: 'Amount',
        paymentMode: 'Payment Mode',
        paymentReferenceNo: 'Reference No',
        paymentAttachment: 'Attachment (pick the screenshot again - the upload did not complete)',
        feeCollectingTimeStamp: 'Collecting Date'
    };
    for (var key in formData) {
        if (formData.hasOwnProperty(key) && formData[key].trim() === '') {
            alert("The (" + (brandFeeFieldLabels[key] || 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);
}

function showOtpStatus(color, text) {
    $('#otp_status').show().css('color', color).text(text);
}

$(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;
    let previousText = btn.text();
    btn.prop('disabled', true).text('Sending...');
    doPostAjaxRequestHandler(`${context}/loiAcceptanceOtp?loiId=` + loiId,
        function (response) {
            let res = null;
            try {
                res = (typeof response === 'string' ? JSON.parse(response) : response);
            } catch (e) {
                res = null;
            }
            if (!res || typeof res.status === 'undefined') {
                showOtpStatus('red', 'Could not confirm the OTP was sent. Check with tech support before retrying.');
                btn.prop('disabled', false).text(previousText);
                return;
            }
            if (res.status && res.sent) {
                showOtpStatus('green', res.message || 'OTP sent.');
                startResendCountdown(btn);
            } else if (res.status) {
                // Accepted, but nothing was dispatched - the previous OTP is still valid (resend throttle).
                showOtpStatus('#c07000', 'No new OTP sent - ' + (res.message || 'the previous OTP is still valid.'));
                startResendCountdown(btn);
            } else {
                showOtpStatus('red', 'OTP NOT sent - ' + (res.message || 'unknown reason.'));
                btn.prop('disabled', false).text(previousText);
            }
        },
        function (xhr, msg) {
            showOtpStatus('red', 'OTP NOT sent - request failed (' + xhr.status + ').');
            btn.prop('disabled', false).text(previousText);
        });
});

//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);
        });
});
// A file input keeps showing the chosen filename no matter what happens next, so the
// operator reads "attached" from the widget while the validator reads the hidden
// documentId that the upload was supposed to fill. Every path below keeps those two in
// step: if the id does not land, the file input is cleared so the form stops claiming a
// file is attached. (The old confirm() gate is gone - picking a file in the OS dialog is
// already an explicit action, and Chrome's "prevent additional dialogs" checkbox made
// confirm() silently return false, which skipped the upload with no trace.)
var paymentScreenshotUploading = false;

function setPaymentScreenshotStatus(text, cssClass) {
    $('#payment-sc-status').text(text).attr('class', 'help-block ' + (cssClass || ''));
}

$(document).on('change', 'table#OnboardingDocumentTable input[type=file],table#mk_brand-fee-collection-details input[type=file]', function () {
    var input = this;
    var fileInput = $(input);
    var file = input.files && input.files[0];
    fileInput.closest('td').find(".documentId").val('');
    if (!file) {
        return;
    }
    uploadDocument(file, function (documentId) {
        fileInput.closest('td').find(".documentId").val(documentId);
    }, function (message) {
        input.value = '';
        alert(message);
    });
});

$(document).on('change', '#payment-sc-doc', function () {
    var input = this;
    var file = input.files && input.files[0];
    // A fresh pick invalidates whatever was uploaded before it.
    $('#payment-sc-docId').val('');
    if (!file) {
        paymentScreenshotUploading = false;
        setPaymentScreenshotStatus('', '');
        return;
    }
    paymentScreenshotUploading = true;
    setPaymentScreenshotStatus('Uploading ' + file.name + ' ...', '');
    uploadDocument(file, function (documentId) {
        paymentScreenshotUploading = false;
        $('#payment-sc-docId').val(documentId);
        setPaymentScreenshotStatus('Attached: ' + file.name, 'text-success');
    }, function (message) {
        paymentScreenshotUploading = false;
        input.value = '';
        setPaymentScreenshotStatus('Not attached - please select the file again', 'text-danger');
        alert(message);
    });
});


$(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 btn = $(this);
    let loiId = btn.val();
    if (btn.prop('disabled')) return false;
    let otp = prompt("Enter received OTP here");
    if (otp === undefined || otp === null) {
        return false;
    }
    otp = otp.trim();
    if (!otp) {
        alert("Please enter the OTP received by the partner.");
        return false;
    }
    let validateOtpUrl = `${context}/validateLoiOtp?loiId=${loiId}&provideOtp=${encodeURIComponent(otp)}`;

    // Once the OTP is accepted the LOI is only half signed: the server has the OTP but not the
    // signed PDF, and the partner mail + onboarding only happen in /saveLoiDoc. Every failure from
    // here on must say that plainly - a silent failure here left LOIs stuck with no mail.
    function signNotSaved(reason) {
        btn.prop('disabled', false);
        alert("OTP was verified, but the signed LOI was NOT saved.\nReason: " + reason
            + "\n\nNothing has been emailed to the partner. Click Send OTP to get a new OTP, then Confirm Sign again."
            + " Keep this page open until you see the \"LOI has been signed successfully\" message.");
    }

    btn.prop('disabled', true);
    $.ajax({
        url: validateOtpUrl,
        type: 'PUT',
        cache: false,
        suppressGlobalError: true,
        success: function (response) {
            console.log('OTP validation response:', response);

            if (response && response.response && response.response.success) {
                // html2pdf comes from cdnjs; if that script was blocked, the old code threw a
                // ReferenceError right here and the operator saw nothing at all.
                if (typeof html2pdf !== 'function') {
                    signNotSaved("the PDF library did not load in this browser (check internet / try Chrome, then reload the page)");
                    return;
                }
                let tempContainer = null;
                try {
                    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);
                    });

                    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 File([pdf], `LOI_${loiId}_signed.pdf`, {type: 'application/pdf'});

                            uploadDocument(file, function (documentId) {
                                IdempotencyKey = uuidv4();
                                saveLoiDoc(loiId, documentId, signNotSaved);
                            }, function (message) {
                                signNotSaved("upload failed - " + message);
                            });
                        })
                        .catch(function (error) {
                            console.error('PDF generation failed:', error);
                            if (tempContainer && tempContainer.parentNode) {
                                tempContainer.parentNode.removeChild(tempContainer);
                            }
                            signNotSaved("the PDF could not be generated in this browser (" + (error && error.message ? error.message : error) + ")");
                        });
                } catch (error) {
                    console.error('Signed LOI build failed:', error);
                    if (tempContainer && tempContainer.parentNode) {
                        tempContainer.parentNode.removeChild(tempContainer);
                    }
                    signNotSaved("the signed PDF could not be prepared (" + (error && error.message ? error.message : error) + ")");
                }
            } else {
                console.error('OTP validation failed:', response);
                btn.prop('disabled', false);
                alert("OTP validation failed: " + (response && response.response && response.response.message ? response.response.message : "Please try again."));
            }
        },
        error: function (xhr) {
            btn.prop('disabled', false);
            alert("OTP not accepted: " + uploadErrorMessage(xhr));
        }
    });
});


function saveLoiDoc(loiId, documentId, onFailure) {
    let saveLoiDocUrl = `${context}/saveLoiDoc?loiId=` + loiId + `&loiDocId=` + documentId;
    $.ajax({
        url: saveLoiDocUrl,
        type: 'POST',
        cache: false,
        suppressGlobalError: true,
        success: function (response) {
            // The "response" view renders the bare boolean, so a failure arrives as the string "false".
            if (response === true || String(response).trim() === 'true') {
                alert("LOI has been signed successfully and sent to the registered email. Please check your email.");
                pendingLoiForm("main-content");
            } else {
                onFailure("the server did not accept the signed document");
            }
        },
        error: function (xhr) {
            onFailure("saving failed - " + uploadErrorMessage(xhr));
        }
    });
}


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);
}*/