const tableContent = document.querySelector('.table-content');
// HTML Elements
const isEmptyAlert = document.getElementById("noBalance");
const tableDiv = document.getElementById("balanceSheet");
const payTable = document.getElementById("payTable");
const tableCnt = document.getElementById("table-content");
const tableSum = document.getElementById("table-sum");
const modal_sum = document.getElementById("ModalSum");
const confirmModal = document.getElementById("confirmModal");
const btn_paynow = document.getElementById("paynow");
const btn_confirm = document.getElementById("confirmCheckout");
const btn_logout = document.getElementById("logout");

const table_old = document.getElementById("alltransactions");

errorIfAnyUndefined([isEmptyAlert, tableDiv, payTable, tableCnt, tableSum, modal_sum])

// Current user
let cookieUser = getCookie('user');

if(cookieUser == undefined) {
	createTemporaryNotification('Fehler: Nutzer nicht angemeldet.', 'is-danger');
	window.location.href = '/user_select';
}
table_old.setAttribute('data-filters', `{"user_id": ${cookieUser}}`);
refreshTable(table_old);
console.log("Table refreshed");

let transactionIds = [];

// Request outstanding transactions by user
async function pullData() {
	let data = await _api.get("transaction?user_id=" + parseInt(cookieUser) + "&paid=false");
	console.log(data)
	if(data.count == 0) {
		isEmptyAlert.classList.remove("is-hidden");
		tableDiv.classList.add("is-hidden");
		return;
	}
	// Write data to table
	const result = data.result;
	let priceSum = 0;
	for(var i = 0; i < data.count; i++) {
		const row = result[i];
		const newRow = tableCnt.insertRow();
		newRow.id = `row_${row.id}`;
		newRow.innerHTML = `
			<td>${formatTimestamp(row.createdAt)}</td>
			<td>${parseFloat(row.total).toFixed(2)} €</td>
		`;
		priceSum += parseFloat(row.total);
		transactionIds.push(row.id);
	}
	tableSum.innerText = priceSum.toFixed(2) + " €";
	modal_sum.innerText = priceSum.toFixed(2) + " €";
}

btn_paynow.onclick = () => {
	confirmModal.classList.add("is-active");
}

btn_confirm.onclick = () => {
	for(let i = 0; i < transactionIds.length; i++) {
		let res = _api.patch(`transaction`, {paid: true, id: transactionIds[i], user_id: parseInt(cookieUser)});
		console.log(res);
		if(res == -1 || res == undefined) {
			createTemporaryNotification('Fehler: Zahlung fehlgeschlagen.', 'is-danger');
			return;
		}
	}
	createTemporaryNotification('Zahlung erfolgreich.', 'is-success');
	setTimeout(() => {
		window.location.href = '/user_select';
	}, 1000);
}

btn_logout.onclick = () => {
	eraseCookie('user');
	window.location.href = '/user_select';
}

pullData()
