`;
resultsHTML += `
Estimated Approval & Gap:
Estimated Maximum Approved Loan Amount: ${lge_formatCurrency(estimatedApprovedAmount)}
`;
if (gap > 0) {
resultsHTML += `
This is ${lge_formatCurrency(gap)} LESS than your desired amount of ${lge_formatCurrency(desiredLoanAmount)}.
`;
resultsHTML += `
Primary limiting factor(s): ${maxLoanByDTI < estimatedApprovedAmount + 1 ? 'Debt-to-Income Ratio' : ''} ${ (loanType.includes('auto') || loanType === 'otherSecured') && maxLoanByLTV < estimatedApprovedAmount + 1 ? (maxLoanByDTI < estimatedApprovedAmount + 1 ? ' & ' : '') + 'Loan-to-Value/Collateral' : ''}.
`;
} else if (gap === 0) {
resultsHTML += `
Your desired loan amount of ${lge_formatCurrency(desiredLoanAmount)} appears potentially serviceable based on these estimates.
`;
} else { // gap < 0 means they could potentially be approved for more
resultsHTML += `
Your desired loan amount of ${lge_formatCurrency(desiredLoanAmount)} is well within the estimated serviceable range. You might even qualify for up to ~${lge_formatCurrency(Math.min(maxLoanByDTI, maxLoanByLTV === Infinity ? maxLoanByDTI : maxLoanByLTV))} based on these factors.
`;
}
resultsHTML += `
`;
if(lge_el.resultsContainer) lge_el.resultsContainer.innerHTML = resultsHTML;
if(lge_el.pdfDownloadBtn && lge_el.pdfDownloadBtn.style) lge_el.pdfDownloadBtn.style.display = 'block';
}
function lge_resetForm() {
if(lge_el.desiredLoanAmount) lge_el.desiredLoanAmount.value = "20000";
if(lge_el.loanPurposeType) lge_el.loanPurposeType.value = "personalUnsecured";
if(lge_el.desiredLoanTerm) lge_el.desiredLoanTerm.value = "60";
if(lge_el.creditScoreTier) lge_el.creditScoreTier.value = "good";
if(lge_el.annualIncome) lge_el.annualIncome.value = "60000";
if(lge_el.monthlyDebts) lge_el.monthlyDebts.value = "1000";
if(lge_el.collateralValue) lge_el.collateralValue.value = "";
lge_toggleCollateralFieldsFromLoanType();
document.querySelectorAll('#loanGapEstimator .lge-error-message').forEach(el => el.textContent = '');
if(lge_el.resultsContainer) lge_el.resultsContainer.innerHTML = "";
if(lge_el.pdfDownloadBtn && lge_el.pdfDownloadBtn.style) lge_el.pdfDownloadBtn.style.display = 'none';
if(lge_el.resultsTabButton) lge_el.resultsTabButton.disabled = true;
lge_currentTab = 0;
lge_openTab(null, 'lge-tabLoanRequest');
}
function lge_downloadPDF() {
if (typeof window.jspdf === 'undefined' || typeof window.jspdf.jsPDF !== 'function' || typeof window.html2canvas !== 'function') {
alert("PDF generation library (jsPDF/html2canvas) not loaded. Check CDN links & internet connection."); return;
}
const jsPDFConstructor = window.jspdf.jsPDF;
const resultsToCapture = lge_el.resultsContainer;
const tipsContent = document.querySelector('#loanGapEstimator .lge-tips');
const disclaimerContent = document.querySelector('#loanGapEstimator .lge-disclaimer-final');
if (!resultsToCapture || !resultsToCapture.innerHTML.trim().includes("Estimated Maximum Approved Loan Amount")) {
alert("No analysis to download. Please complete the steps first."); return;
}
const pdf = new jsPDFConstructor('p', 'pt', 'a4');
const toolTitle = "Loan Request vs. Approval Gap Estimate";
const margins = { top: 30, bottom: 30, left: 30, right: 30 };
const pdfWidth = pdf.internal.pageSize.getWidth() - margins.left - margins.right;
let yPos = margins.top;
pdf.setFontSize(16);
pdf.text(toolTitle, pdf.internal.pageSize.getWidth() / 2, yPos, { align: 'center' });
yPos += 25;
// --- Inputs Summary ---
pdf.setFontSize(10);
pdf.setFont(undefined, 'bold');
pdf.text("Your Inputs:", margins.left, yPos); yPos += 14;
pdf.setFont(undefined, 'normal');
pdf.setFontSize(8);
let inputsText = [
`Desired Loan: ${lge_formatCurrency(parseFloat(lge_el.desiredLoanAmount.value))} for ${lge_el.desiredLoanTerm.value} months`,
`Purpose: ${lge_el.loanPurposeType.options[lge_el.loanPurposeType.selectedIndex].text}`,
`Credit Tier: ${lge_el.creditScoreTier.options[lge_el.creditScoreTier.selectedIndex].text}`,
`Annual Income: ${lge_formatCurrency(parseFloat(lge_el.annualIncome.value))}, Existing Monthly Debts: ${lge_formatCurrency(parseFloat(lge_el.monthlyDebts.value))}`
];
if (lge_el.collateralDetailsSection.style.display !== 'none' && lge_el.collateralValue.value) {
inputsText.push(`Collateral Value: ${lge_formatCurrency(parseFloat(lge_el.collateralValue.value))}`);
}
inputsText.forEach(line => {
const splitLines = pdf.splitTextToSize(line, pdfWidth);
if (yPos + (splitLines.length * 10) > pdf.internal.pageSize.getHeight() - margins.bottom) { pdf.addPage(); yPos = margins.top; }
pdf.text(splitLines, margins.left, yPos);
yPos += (splitLines.length * 10) + 2;
});
yPos += 10;
// --- Results using html2canvas ---
if (yPos > pdf.internal.pageSize.getHeight() - margins.bottom - 150) { pdf.addPage(); yPos = margins.top;} // Check space for results
pdf.setFontSize(10);
pdf.setFont(undefined, 'bold');
pdf.text("Gap Analysis Estimate:", margins.left, yPos); yPos += 5;
html2canvas(resultsToCapture, {scale: 1.2, backgroundColor: '#ffffff', useCORS: true, windowWidth: resultsToCapture.scrollWidth}).then(canvasResults => {
const imgDataResults = canvasResults.toDataURL('image/png');
const imgPropsResults = pdf.getImageProperties(imgDataResults);
let pdfHeightResults = (imgPropsResults.height * pdfWidth) / imgPropsResults.width;
const maxHeightPerPage = pdf.internal.pageSize.getHeight() - margins.top - margins.bottom - yPos;
if (pdfHeightResults > maxHeightPerPage && yPos > margins.top + 20) {
pdf.addPage(); yPos = margins.top;
} else if (pdfHeightResults > maxHeightPerPage) {
pdfHeightResults = maxHeightPerPage;
console.warn("PDF results section might be truncated.");
}
pdf.addImage(imgDataResults, 'PNG', margins.left, yPos, pdfWidth, pdfHeightResults);
yPos += pdfHeightResults + 15;
// --- Tips ---
if (tipsContent) {
if (yPos > pdf.internal.pageSize.getHeight() - margins.bottom - 60) { pdf.addPage(); yPos = margins.top;}
pdf.setFontSize(10); pdf.setFont(undefined, 'bold');
pdf.text("Tips to Bridge the Gap:", margins.left, yPos); yPos += 14;
pdf.setFont(undefined, 'normal'); pdf.setFontSize(8);
const tipItems = tipsContent.querySelectorAll('li');
Array.from(tipItems).forEach(item => {
const textLines = pdf.splitTextToSize("- " + item.innerText.trim(), pdfWidth - 10);
if (yPos + (textLines.length * 10) > pdf.internal.pageSize.getHeight() - margins.bottom) {
pdf.addPage(); yPos = margins.top;
}
pdf.text(textLines, margins.left + 5, yPos);
yPos += (textLines.length * 10) + 2;
});
yPos += 10;
}
// --- Disclaimer ---
if (disclaimerContent) {
if (yPos > pdf.internal.pageSize.getHeight() - margins.bottom - 40) { pdf.addPage(); yPos = margins.top; }
pdf.setFontSize(7.5); pdf.setTextColor(108, 117, 125);
const disclaimerLines = pdf.splitTextToSize(disclaimerContent.innerText.trim(), pdfWidth);
pdf.text(disclaimerLines, margins.left, yPos);
}
pdf.save('Loan_Approval_Gap_Estimate.pdf');
}).catch(err => {
console.error("Error generating PDF results with html2canvas:", err);
alert("Error rendering results to PDF. The PDF may be incomplete.");
pdf.save('Loan_Approval_Gap_Estimate_Partial.pdf');
});
}