document.addEventListener('DOMContentLoaded', function () { const overrideBtn = document.getElementById('override-btn'); if (overrideBtn) { overrideBtn.addEventListener('click', function () { const projectId = this.dataset.projectId; const month = this.dataset.month; if (this.textContent.trim() === 'Override') { this.textContent = 'Save'; this.classList.remove('btn-warning'); this.classList.add('btn-success'); makeEditable('WIP', month); makeEditable('Opening-Balance', month); makeEditable('Billings', month); makeEditable('Expenses', month); makeEditable('Cost', month); } else if (this.textContent.trim() === 'Save') { const wip = document.getElementById(`wip-${month}-input`).value; const openingBalance = document.getElementById(`opening-balance-${month}-input`).value; const billings = document.getElementById(`billings-${month}-input`).value; const expenses = document.getElementById(`expenses-${month}-input`).value; const cost = document.getElementById(`cost-${month}-input`).value; const formData = new FormData(); formData.append('projectId', projectId); formData.append('month', month); formData.append('wip', wip); formData.append('openingBalance', openingBalance); formData.append('billings', billings); formData.append('expenses', expenses); formData.append('cost', cost); fetch('save_override.php', { method: 'POST', body: formData }) .then(response => response.json()) .then(data => { if (data.success) { this.textContent = 'Overridden'; this.classList.remove('btn-success'); this.classList.add('btn-secondary'); this.disabled = true; updateMetricCell('WIP', month, wip); updateMetricCell('Opening-Balance', month, openingBalance); updateMetricCell('Billings', month, billings); updateMetricCell('Expenses', month, expenses); updateMetricCell('Cost', month, cost); updateMetricCell('NSR', month, data.nsr); updateMetricCell('Margin', month, data.margin); } else { alert('Error saving override: ' + data.error); } }) .catch(error => { console.error('Error:', error); alert('An unexpected error occurred.'); }); } }); } function makeEditable(metric, month) { const cellId = `${metric.toLowerCase().replace(/\s/g, '-')}-${month}`; const cell = document.getElementById(cellId); if (cell) { let value = cell.textContent.replace(/[€%]/g, '').replace(/,/g, '').trim(); let numericValue = parseFloat(value); if (isNaN(numericValue)) { numericValue = 0; } if (metric === 'Margin') { numericValue = numericValue / 100; } cell.innerHTML = ``; } } function updateMetricCell(metric, month, value) { const cellId = `${metric.toLowerCase().replace(/\s/g, '-')}-${month}`; const cell = document.getElementById(cellId); if (cell) { const numericValue = value === '' ? 0 : parseFloat(value); if (metric === 'Margin') { cell.innerHTML = `${(numericValue * 100).toFixed(2)}%`; } else { cell.innerHTML = `€${numericValue.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`; } } } });