`;
if(fhlae_domElements.resultsContainer) fhlae_domElements.resultsContainer.innerHTML = summaryHTML;
if (fhlae_domElements.pdfDownloadBtn) {
fhlae_domElements.pdfDownloadBtn.classList.remove('fhlae-hidden');
}
}
function fhlae_hexToRgb(hex) {
if (!hex || typeof hex !== 'string') return null;
const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) { return r + r + g + g + b + b; });
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) } : null;
}
function fhlae_generatePdf() {
if (typeof window.jspdf === 'undefined' || typeof window.jspdf.jsPDF === 'undefined' || typeof window.jspdf.jsPDF.API === 'undefined' || typeof window.jspdf.jsPDF.API.autoTable === 'undefined') {
alert("PDF generation library is not loaded. Please try again later."); return;
}
// Re-validate all data
let errorMessagesListPDF = [];
if (!fhlae_validateTab1()) { errorMessagesListPDF.push("Tab 1 (Income & Employment) has errors."); }
if (!fhlae_validateTab2()) { errorMessagesListPDF.push("Tab 2 (Expenses & Debts) has errors."); }
if (!fhlae_validateTab3()) { errorMessagesListPDF.push("Tab 3 (Assets & Context) has errors."); }
if (errorMessagesListPDF.length > 0) {
alert(`Please correct errors before generating PDF:\n- ${errorMessagesListPDF.join('\n- ')}`);
if (!fhlae_validateTab1()) fhlae_navigateToTab('fhlae-tab1');
else if (!fhlae_validateTab2()) fhlae_navigateToTab('fhlae-tab2');
else if (!fhlae_validateTab3()) fhlae_navigateToTab('fhlae-tab3');
return;
}
fhlae_calculateAndDisplaySummary(); // Ensure data is fresh
if (fhlae_domElements.resultsContainer && fhlae_domElements.resultsContainer.innerHTML.includes("fhlae-error-message")) {
alert("Cannot generate PDF due to errors in input or calculation. Please correct them."); return;
}
const ActualJsPDF = window.jspdf.jsPDF;
const doc = new ActualJsPDF();
const { income, expenses, otherDebtPayments, assets, context, calculated } = fhlae_userData;
doc.setFontSize(18);
const primaryColorRGB = fhlae_hexToRgb(getComputedStyle(document.documentElement).getPropertyValue('--fhlae-primary-color').trim()) || {r:0,g:123,b:255};
const secondaryColorRGB = fhlae_hexToRgb(getComputedStyle(document.documentElement).getPropertyValue('--fhlae-secondary-color').trim()) || {r:0,g:86,b:179};
doc.setTextColor(primaryColorRGB.r, primaryColorRGB.g, primaryColorRGB.b);
doc.text("Financial Hardship Factors Summary", 105, 20, null, null, "center");
doc.setFontSize(10);
doc.setTextColor(33,37,41);
let startY = 30;
const tableHeadFillColor = [secondaryColorRGB.r, secondaryColorRGB.g, secondaryColorRGB.b];
const bodyStylesPDF = { fontSize: 9, cellPadding: 2 };
const headStylesPDF = { fillColor: tableHeadFillColor, textColor: 255, fontSize: 9.5, fontStyle: 'bold' };
const boldStylePDF = { fontStyle: 'bold' };
doc.setFontSize(12); doc.setTextColor(secondaryColorRGB.r, secondaryColorRGB.g, secondaryColorRGB.b);
doc.text("Your Financial Situation:", 14, startY); startY += 7;
const inputSummaryBody = [
["Current Monthly Income:", fhlae_formatCurrency(income.current)],
["Previous Monthly Income:", fhlae_formatCurrency(income.previous)],
["Reason for Income Change:", income.reason || 'N/A'],
["Employment Status:", fhlae_getSelectedText('isEmployed')],
["Total Essential Monthly Expenses:", fhlae_formatCurrency(expenses.totalEssential)],
["Total Other Monthly Debt Payments:", fhlae_formatCurrency(otherDebtPayments)],
["Liquid Savings Available:", fhlae_formatCurrency(assets.liquidSavings)],
["Recent Major Financial Event:", fhlae_getSelectedText('majorUnexpectedEvent')],
["Loan Type for Assistance:", context.loanType || 'Not specified']
];
doc.autoTable({ startY: startY, body: inputSummaryBody, theme: 'grid', styles: bodyStylesPDF, columnStyles: {0:boldStylePDF, 1:{halign:'right'}}});
startY = doc.autoTable.previous.finalY + 8;
doc.setFontSize(12); doc.setTextColor(secondaryColorRGB.r, secondaryColorRGB.g, secondaryColorRGB.b);
doc.text("Calculated Indicators:", 14, startY); startY += 7;
const calcSummaryBody = [
["Income Change:", isFinite(calculated.incomeDropPercent) ? fhlae_formatPercent(calculated.incomeDropPercent) + (calculated.incomeDropPercent > 0 ? ' decrease' : (calculated.incomeDropPercent < 0 ? ' increase' : '')) : 'N/A'],
["Income After Essentials & Other Debts:", fhlae_formatCurrency(calculated.incomeAfterEssentialsAndDebts)],
["Savings Buffer (Approx. Months):", isFinite(calculated.savingsBufferMonths) ? calculated.savingsBufferMonths.toFixed(1) + ' months' : 'N/A'],
];
doc.autoTable({ startY: startY, body: calcSummaryBody, theme: 'grid', styles: bodyStylesPDF, columnStyles: {0:boldStylePDF, 1:{halign:'right'}}});
startY = doc.autoTable.previous.finalY + 8;
// Hardship Indication Level
const resultsContainerHTML = document.getElementById('fhlae-resultsContainer');
const indicationTitle = resultsContainerHTML.querySelector('h4') ? resultsContainerHTML.querySelector('h4').textContent : "Indication Not Determined";
doc.setFontSize(12);
// Determine color for indication title
let indicationColor = [33,37,41]; // default text color
if (indicationTitle.includes("High Indication")) indicationColor = fhlae_hexToRgb(getComputedStyle(document.documentElement).getPropertyValue('--fhlae-error-color').trim()) || {r:220,g:53,b:69};
else if (indicationTitle.includes("Moderate Indication")) indicationColor = fhlae_hexToRgb(getComputedStyle(document.documentElement).getPropertyValue('--fhlae-accent-color').trim()) || {r:255,g:193,b:7};
else if (indicationTitle.includes("Lower Indication")) indicationColor = fhlae_hexToRgb(getComputedStyle(document.documentElement).getPropertyValue('--fhlae-primary-color').trim()) || {r:0,g:123,b:255};
doc.setTextColor(indicationColor.r, indicationColor.g, indicationColor.b);
doc.text(indicationTitle, 14, startY); startY += 7;
doc.setFontSize(9); doc.setTextColor(33,37,41);
const pointersHTML = resultsContainerHTML.querySelectorAll('.fhlae-pointers ul li');
if (pointersHTML.length > 0) {
doc.text("Key Pointers Based on Your Inputs:", 14, startY); startY += 5;
pointersHTML.forEach(li => {
const text = `• ${li.textContent}`;
const splitText = doc.splitTextToSize(text, doc.internal.pageSize.width - 28 - 4); // 4 for bullet indent
doc.text(splitText, 18, startY);
startY += (splitText.length * (doc.getLineHeight() / doc.internal.scaleFactor * 0.85)) + 1;
});
}
startY += 5;
doc.setFontSize(10); doc.setTextColor(secondaryColorRGB.r, secondaryColorRGB.g, secondaryColorRGB.b);
doc.text("Important Next Steps:", 14, startY); startY += 6;
doc.setFontSize(8.5); doc.setTextColor(33,37,41);
const nextSteps = [
"This tool provides a general indication and IS NOT a guarantee of eligibility for assistance.",
"Contact your lender(s)/servicer(s) IMMEDIATELY to discuss your situation and hardship options.",
"Be prepared to provide documentation (proof of income loss, expenses, hardship letter).",
"Consider free/low-cost help from a non-profit credit counseling agency (e.g., NFCC.org in the US).",
"Explore official resources like StudentAid.gov (federal student loans) or consumerfinance.gov."
];
nextSteps.forEach(step => {
const splitStep = doc.splitTextToSize(`- ${step}`, doc.internal.pageSize.width - 28);
doc.text(splitStep, 14, startY);
startY += (splitStep.length * (doc.getLineHeight() / doc.internal.scaleFactor * 0.8)) + 1.5;
});
doc.setFontSize(9);
doc.setTextColor(150);
doc.text(`Report generated on: ${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}`, 14, doc.internal.pageSize.height - 10);
doc.save("Financial_Hardship_Factors_Estimate.pdf");
}
window.fhlae_switchTab = fhlae_switchTab;
window.fhlae_navigateToTab = fhlae_navigateToTab;
window.fhlae_generatePdf = fhlae_generatePdf;
window.fhlae_updateTotalExpensesDisplay = fhlae_updateTotalExpensesDisplay; // Expose for listeners
