`;
if (slvcc_domElements.pdfDownloadBtn) {
slvcc_domElements.pdfDownloadBtn.classList.remove('slvcc-hidden');
}
}
function slvcc_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 slvcc_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."); return;
}
// Re-validate all data before generating PDF
let errorMessagesListPDF = [];
if (!slvcc_validateTab1()) { errorMessagesListPDF.push("Tab 1 (Expense & Term) has errors."); }
if (!slvcc_validateTab2()) { errorMessagesListPDF.push("Tab 2 (Student Loan) has errors."); }
if (!slvcc_validateTab3()) { errorMessagesListPDF.push("Tab 3 (Credit Card) has errors."); }
if (errorMessagesListPDF.length > 0) {
alert(`Please correct errors before generating PDF:\n- ${errorMessagesListPDF.join('\n- ')}`);
if (!slvcc_validateTab1()) slvcc_navigateToTab('slvcc-tab1');
else if (!slvcc_validateTab2()) slvcc_navigateToTab('slvcc-tab2');
else if (!slvcc_validateTab3()) slvcc_navigateToTab('slvcc-tab3');
return;
}
slvcc_calculateAndDisplayComparison(); // Ensure data is fresh for PDF
if (slvcc_domElements.resultsContainer && slvcc_domElements.resultsContainer.innerHTML.includes("slvcc-error-message")) {
alert("Cannot generate PDF due to errors in input or calculation."); return;
}
const ActualJsPDF = window.jspdf.jsPDF;
const doc = new ActualJsPDF();
const { expenseAmount, repaymentTermYears, studentLoan, creditCard } = slvcc_data;
const sl = studentLoan; const cc = creditCard;
doc.setFontSize(18);
const primaryColorRGB = slvcc_hexToRgb(getComputedStyle(document.documentElement).getPropertyValue('--slvcc-primary-color').trim()) || {r:63,g:81,b:181};
const secondaryColorRGB = slvcc_hexToRgb(getComputedStyle(document.documentElement).getPropertyValue('--slvcc-secondary-color').trim()) || {r:48,g:63,b:159};
doc.setTextColor(primaryColorRGB.r, primaryColorRGB.g, primaryColorRGB.b);
doc.text("Student Loan vs. Credit Card Cost Comparison", 105, 20, null, null, "center");
doc.setFontSize(11);
doc.setTextColor(33,33,33);
let startY = 30;
doc.text(`Expense Amount: ${slvcc_formatCurrency(expenseAmount)} | Repayment Term: ${repaymentTermYears} years`, 14, startY);
startY += 10;
const tableHeadFillColor = [secondaryColorRGB.r, secondaryColorRGB.g, secondaryColorRGB.b];
const studentLoanColorArrPDF = slvcc_hexToRgb(getComputedStyle(document.documentElement).getPropertyValue('--slvcc-student-loan-color').trim()) || {r:46,g:125,b:50};
const creditCardColorArrPDF = slvcc_hexToRgb(getComputedStyle(document.documentElement).getPropertyValue('--slvcc-credit-card-color').trim()) || {r:198,g:40,b:40};
const tableBodyPDF = [
["Est. Annual Interest Rate", slvcc_formatPercent(sl.rate), slvcc_formatPercent(cc.apr)],
["Origination/Upfront Fees", slvcc_formatCurrency(sl.totalFees), slvcc_formatCurrency(cc.totalFees)],
["Est. Monthly Payment", slvcc_formatCurrency(sl.calculated.emi), slvcc_formatCurrency(cc.calculated.emi)],
["Total Interest Paid", slvcc_formatCurrency(sl.calculated.totalInterestPaid), slvcc_formatCurrency(cc.calculated.totalInterestPaid)],
["Total Finance Charge", slvcc_formatCurrency(sl.calculated.totalFinanceCharge), slvcc_formatCurrency(cc.calculated.totalFinanceCharge)],
[{content:"Total Amount Repaid", styles:{fontStyle:'bold'}},
{content:slvcc_formatCurrency(sl.calculated.totalRepayment), styles:{fontStyle:'bold'}},
{content:slvcc_formatCurrency(cc.calculated.totalRepayment), styles:{fontStyle:'bold'}}]
];
doc.autoTable({
startY: startY,
head: [['Feature', 'Student Loan', 'Credit Card']],
body: tableBodyPDF,
theme: 'grid',
headStyles: { fillColor: tableHeadFillColor, textColor: 255, fontSize:10, fontStyle:'bold' },
styles: { fontSize: 9, cellPadding: 2.5 },
margin: { left: 14, right: 14 },
columnStyles: {
0: { fontStyle: 'bold', cellWidth: 55 },
1: { textColor: [studentLoanColorArrPDF.r, studentLoanColorArrPDF.g, studentLoanColorArrPDF.b], cellWidth: 'auto' },
2: { textColor: [creditCardColorArrPDF.r, creditCardColorArrPDF.g, creditCardColorArrPDF.b], cellWidth: 'auto' }
}
});
startY = doc.autoTable.previous.finalY + 12;
doc.setFontSize(11);
doc.setTextColor(secondaryColorRGB.r, secondaryColorRGB.g, secondaryColorRGB.b);
doc.text("Key Differences:", 14, startY); startY += 7;
doc.setFontSize(8.5);
doc.setTextColor(33,33,33);
const keyDifferencesTextPDF = [
"- Student Loans: Often lower, fixed rates; flexible repayment (IDR, deferment, forbearance); potential forgiveness; tax-deductible interest; grace period.",
"- Credit Cards: Typically very high, often variable APRs; rigid minimum payments; no significant borrower protections or forgiveness; interest generally not tax-deductible for education; immediate interest accrual if balance carried."
];
keyDifferencesTextPDF.forEach(item => {
const splitItem = doc.splitTextToSize(item, doc.internal.pageSize.width - 28);
doc.text(splitItem, 14, startY);
startY += (splitItem.length * (doc.getLineHeight() / doc.internal.scaleFactor * 0.8)) + 1.5;
});
startY += 5;
doc.setFontSize(10);
doc.setTextColor(creditCardColorArrPDF.r, creditCardColorArrPDF.g, creditCardColorArrPDF.b);
doc.setFont(undefined, 'bold');
doc.text("Strong Recommendation:", 14, startY); startY += 6;
doc.setFont(undefined, 'normal');
doc.setFontSize(8.5);
doc.setTextColor(33,33,33);
const guidanceTextPDF = "Credit cards are NOT recommended for financing education due to high costs and lack of protections. Student loans (especially federal) are designed for this purpose and offer better terms. Exhaust federal options first.";
const splitGuidance = doc.splitTextToSize(guidanceTextPDF, doc.internal.pageSize.width - 28);
doc.text(splitGuidance, 14, startY);
doc.setFontSize(9);
doc.setTextColor(120);
doc.text(`Report generated on: ${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}`, 14, doc.internal.pageSize.height - 10);
doc.save("StudentLoan_vs_CreditCard_Comparison.pdf");
}
window.slvcc_switchTab = slvcc_switchTab;
window.slvcc_navigateToTab = slvcc_navigateToTab;
window.slvcc_generatePdf = slvcc_generatePdf;
window.slvcc_updateTotalStudentLoanFeesDisplay = slvcc_updateTotalStudentLoanFeesDisplay;