`;
}
// Add event listeners to new buttons
sbpContainer.querySelectorAll('.sbp-btn-edit').forEach(btn => {
btn.addEventListener('click', (e) => startEditItem(Number(e.target.dataset.id)));
});
sbpContainer.querySelectorAll('.sbp-btn-delete').forEach(btn => {
btn.addEventListener('click', (e) => deleteItem(Number(e.target.dataset.id)));
});
}
function handleFormSubmit() {
const name = itemNameInput.value.trim();
const amount = parseFloat(itemAmountInput.value);
const type = itemTypeSelect.value;
const id = Number(editItemIdInput.value);
if (!name || isNaN(amount) || amount <= 0) {
alert('Please enter a valid name and a positive amount.');
return;
}
if (id) {
// Updating existing item
const itemIndex = budgetItems.findIndex(item => item.id === id);
if (itemIndex > -1) {
budgetItems[itemIndex] = { id, name, amount, type };
}
} else {
// Adding new item
const newId = budgetItems.length > 0 ? Math.max(...budgetItems.map(item => item.id)) + 1 : 1;
budgetItems.push({ id: newId, name, amount, type });
}
resetForm();
renderDashboard();
showTab('sbp-tab-dashboard'); // Go back to dashboard after adding
}
function startEditItem(id) {
const item = budgetItems.find(item => item.id === id);
if (!item) return;
if (formTitle) formTitle.textContent = 'Edit Item';
if (editItemIdInput) editItemIdInput.value = item.id;
if (itemNameInput) itemNameInput.value = item.name;
if (itemAmountInput) itemAmountInput.value = item.amount;
if (itemTypeSelect) itemTypeSelect.value = item.type;
if (addItemBtn) addItemBtn.textContent = 'Update Item';
if (cancelEditBtn) cancelEditBtn.style.display = 'block';
showTab('sbp-tab-config');
}
function resetForm() {
if (formTitle) formTitle.textContent = 'Add New Item';
if (editItemIdInput) editItemIdInput.value = '';
if (itemNameInput) itemNameInput.value = '';
if (itemAmountInput) itemAmountInput.value = '';
if (itemTypeSelect) itemTypeSelect.value = 'income';
if (addItemBtn) addItemBtn.textContent = 'Add Item';
if (cancelEditBtn) cancelEditBtn.style.display = 'none';
}
function deleteItem(id) {
if (confirm('Are you sure you want to delete this item?')) {
budgetItems = budgetItems.filter(item => item.id !== id);
renderDashboard();
}
}
// --- PDF Download ---
async function downloadPDF() {
if (!window.jspdf || !window.html2canvas) {
alert('PDF generation libraries are not loaded.');
return;
}
const content = sbpContainer.querySelector('#sbp-pdf-content');
if (!content) {
alert('Error: Could not find PDF content to download.');
return;
}
if (downloadPdfBtn) {
downloadPdfBtn.textContent = 'Generating...';
downloadPdfBtn.disabled = true;
}
// Show the hidden content so html2canvas can capture it
content.style.display = 'block';
try {
const canvas = await window.html2canvas(content, {
scale: 2, // Increase resolution
useCORS: true,
backgroundColor: '#ffffff'
});
// Hide the content again
content.style.display = 'none';
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF({
orientation: 'portrait',
unit: 'px',
format: [canvas.width, canvas.height]
});
pdf.addImage(imgData, 'PNG', 0, 0, canvas.width, canvas.height);
pdf.save('My_Budget_Plan.pdf');
} catch (error) {
console.error('Error generating PDF:', error);
alert('An error occurred while generating the PDF.');
} finally {
if (downloadPdfBtn) {
downloadPdfBtn.textContent = 'Download Budget as PDF';
downloadPdfBtn.disabled = false;
}
}
}
// --- Initialization ---
function initSampleData() {
budgetItems = [
{ id: 1, name: 'Monthly Salary', amount: 4500.00, type: 'income' },
{ id: 2, name: 'Freelance Gig', amount: 600.00, type: 'income' },
{ id: 3, name: 'Apartment Rent', amount: 1600.00, type: 'expense' },
{ id: 4, name: 'Car Payment', amount: 350.00, type: 'expense' },
{ id: 5, name: 'Groceries', amount: 400.00, type: 'expense' },
{ id: 6, name: 'Utilities (Electric/Water)', amount: 150.00, type: 'expense' },
{ id: 7, name: 'Internet', amount: 60.00, type: 'expense' }
];
}
function init() {
// Null checks for essential elements
if (!addItemBtn || !cancelEditBtn || !downloadPdfBtn) {
console.error("SBP: Critical form elements not found. Tool may not function.");
return;
}
// Add Event Listeners
addItemBtn.addEventListener('click', handleFormSubmit);
cancelEditBtn.addEventListener('click', resetForm);
downloadPdfBtn.addEventListener('click', downloadPDF);
// Load data and render
initSampleData();
renderDashboard();
showTab('sbp-tab-dashboard'); // Ensure dashboard is default
}
init();
});
