<?php
/* Copyright (C) 2026  Eduard Wisch  <data@data-it-solution.de>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 */

/**
 * \file    bankimport/statements.php
 * \ingroup bankimport
 * \brief   Page to fetch and display bank statements via FinTS
 */

// Load Dolibarr environment
$res = 0;
if (!$res && !empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) {
	$res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php";
}
$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME'];
$tmp2 = realpath(__FILE__);
$i = strlen($tmp) - 1;
$j = strlen($tmp2) - 1;
while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) {
	$i--;
	$j--;
}
if (!$res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1))."/main.inc.php")) {
	$res = @include substr($tmp, 0, ($i + 1))."/main.inc.php";
}
if (!$res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php")) {
	$res = @include dirname(substr($tmp, 0, ($i + 1)))."/main.inc.php";
}
if (!$res && file_exists("../main.inc.php")) {
	$res = @include "../main.inc.php";
}
if (!$res && file_exists("../../main.inc.php")) {
	$res = @include "../../main.inc.php";
}
if (!$res) {
	die("Include of main fails");
}

require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
dol_include_once('/bankimport/class/fints.class.php');
dol_include_once('/bankimport/class/banktransaction.class.php');
dol_include_once('/bankimport/class/bankimportcron.class.php');
dol_include_once('/bankimport/lib/bankimport.lib.php');

/**
 * @var Conf $conf
 * @var DoliDB $db
 * @var Translate $langs
 * @var User $user
 */

$langs->loadLangs(array("bankimport@bankimport", "banks"));

$action = GETPOST('action', 'aZ09');

// Security check
if (!$user->hasRight('bankimport', 'write')) {
	accessforbidden();
}

// Date filters
$date_fromday = GETPOSTINT('date_fromday');
$date_frommonth = GETPOSTINT('date_frommonth');
$date_fromyear = GETPOSTINT('date_fromyear');
$date_today = GETPOSTINT('date_today');
$date_tomonth = GETPOSTINT('date_tomonth');
$date_toyear = GETPOSTINT('date_toyear');

$dateFrom = 0;
$dateTo = 0;

if ($date_fromday && $date_frommonth && $date_fromyear) {
	$dateFrom = dol_mktime(0, 0, 0, $date_frommonth, $date_fromday, $date_fromyear);
}
if ($date_today && $date_tomonth && $date_toyear) {
	$dateTo = dol_mktime(23, 59, 59, $date_tomonth, $date_today, $date_toyear);
}

// Default: last 30 days
if (empty($dateFrom)) {
	$dateFrom = dol_time_plus_duree(dol_now(), -30, 'd');
}
if (empty($dateTo)) {
	$dateTo = dol_now();
}

/*
 * Actions
 */

$transactions = array();
$balance = array();
$error = 0;
$tanRequired = false;
$tanChallenge = '';
$importResult = null;

// Import transactions to database
if ($action == 'import' && !empty($_SESSION['fints_transactions'])) {
	$fints = new BankImportFinTS($db);
	$iban = $fints->getIban();

	$transImporter = new BankImportTransaction($db);
	$importResult = $transImporter->importFromFinTS($_SESSION['fints_transactions'], $iban, $user);

	if ($importResult['imported'] > 0) {
		setEventMessages($langs->trans("TransactionsImported", $importResult['imported']), null, 'mesgs');
	}
	if ($importResult['skipped'] > 0) {
		setEventMessages($langs->trans("TransactionsSkipped", $importResult['skipped']), null, 'warnings');
	}
	if (!empty($importResult['errors'])) {
		setEventMessages(implode('<br>', $importResult['errors']), null, 'errors');
	}

	// Clear session after import
	unset($_SESSION['fints_transactions']);
	unset($_SESSION['fints_balance']);
}

// Resume pending cron TAN
if ($action == 'resumecron') {
	$cronJob = new BankImportCron($db);
	$result = $cronJob->resumePendingAction();

	if ($result > 0 || $result == 0) {
		if ($result > 0) {
			setEventMessages($langs->trans("TANConfirmedImportComplete"), null, 'mesgs');
		} else {
			setEventMessages($langs->trans("WaitingForSecureGoConfirmation"), null, 'warnings');
		}
	} else {
		setEventMessages($langs->trans("TANCheckFailed").': '.$cronJob->error, null, 'errors');
	}
}

if ($action == 'fetch') {
	$fints = new BankImportFinTS($db);

	if (!$fints->isConfigured()) {
		setEventMessages($langs->trans("FinTSNotConfigured"), null, 'errors');
		$error++;
	} elseif (!$fints->isLibraryAvailable()) {
		setEventMessages($langs->trans("FinTSLibraryNotFound"), null, 'errors');
		$error++;
	} else {
		// Login first
		$loginResult = $fints->login();

		if ($loginResult < 0) {
			setEventMessages($langs->trans("LoginFailed").': '.$fints->error, null, 'errors');
			$error++;
		} elseif ($loginResult == 0) {
			// TAN required
			$tanRequired = true;
			$tanChallenge = $fints->tanChallenge;

			// Check if decoupled (SecureGo Plus)
			if ($fints->selectedTanMode && $fints->selectedTanMode->isDecoupled()) {
				setEventMessages($langs->trans("SecureGoPlusConfirmRequired"), null, 'warnings');
				// Store state in session for polling
				$_SESSION['fints_state'] = $fints->persist();
				$_SESSION['fints_action'] = 'login';
			} else {
				setEventMessages($langs->trans("TANRequired").': '.$tanChallenge, null, 'warnings');
			}
		} else {
			// Login successful - log bank parameters for diagnostics
			$bankParams = $fints->getBankParameters();
			dol_syslog("BankImport: Bank parameters: ".json_encode($bankParams), LOG_DEBUG);

			// Check what statement methods are supported
			$hikazsVersions = $bankParams['HIKAZS'] ?? array();
			$hicazsVersions = $bankParams['HICAZS'] ?? array();
			$hiekaVersions = $bankParams['HIEKAS'] ?? array();
			dol_syslog("BankImport: HIKAZS versions: ".implode(',', $hikazsVersions)." | HICAZS: ".implode(',', $hicazsVersions)." | HIEKAS: ".implode(',', $hiekaVersions), LOG_DEBUG);

			// Fetch statements
			$result = $fints->fetchStatements($dateFrom, $dateTo);

			if ($result === 0) {
				// TAN required for statements
				$tanRequired = true;
				$tanChallenge = $fints->tanChallenge;
				// Store state in session for polling
				$_SESSION['fints_state'] = $fints->persist();
				$_SESSION['fints_pending_action'] = serialize($fints->getPendingAction());
				$_SESSION['fints_action'] = 'statements';
				$_SESSION['fints_datefrom'] = $dateFrom;
				$_SESSION['fints_dateto'] = $dateTo;
				setEventMessages($langs->trans("SecureGoPlusConfirmRequired"), null, 'warnings');
			} elseif ($result < 0) {
				setEventMessages($langs->trans("FetchFailed").': '.$fints->error, null, 'errors');
				// Show supported versions for diagnostics
				if (!empty($hikazsVersions) || !empty($hicazsVersions)) {
					$diagMsg = 'Bank unterstützt: HIKAZS v'.implode(',v', $hikazsVersions);
					if (!empty($hicazsVersions)) {
						$diagMsg .= ' | HICAZS v'.implode(',v', $hicazsVersions);
					}
					setEventMessages($diagMsg, null, 'warnings');
				}
				$error++;
			} elseif (is_array($result)) {
				$transactions = $result['transactions'] ?? array();
				$balance = $result['balance'] ?? array();
				$isPartial = $result['partial'] ?? false;
				$infoMsg = $result['info'] ?? '';

				if (empty($transactions)) {
					setEventMessages($langs->trans("NoTransactionsFound"), null, 'warnings');
				} else {
					setEventMessages($langs->trans("TransactionsFound", count($transactions)), null, 'mesgs');
					// Store in session for import
					$_SESSION['fints_transactions'] = $transactions;
					$_SESSION['fints_balance'] = $balance;

					// Show info about partial results (older data not available)
					if ($isPartial && !empty($infoMsg)) {
						setEventMessages($infoMsg, null, 'warnings');
					}
				}

				// Save session state for cronjob before closing
				$cronState = $fints->persist();
				if (!empty($cronState)) {
					dolibarr_set_const($db, 'BANKIMPORT_CRON_STATE', $cronState, 'chaine', 0, '', $conf->entity);
					dol_syslog("BankImport: Saved session state for cronjob", LOG_DEBUG);
				}

				// Only close on success
				$fints->close();
			}
			// NOTE: Don't call close() when TAN is required ($result === 0)
			// The connection must stay open for checkDecoupledTan()
		}
	}
}

// Check decoupled TAN status (SecureGo Plus polling)
if ($action == 'checktan') {
	if (!empty($_SESSION['fints_state']) && !empty($_SESSION['fints_pending_action'])) {
		$fints = new BankImportFinTS($db);
		$fints->restore($_SESSION['fints_state']);
		$fints->setPendingAction(unserialize($_SESSION['fints_pending_action']));

		$result = $fints->checkDecoupledTan();

		if ($result > 0) {
			// TAN confirmed
			$savedAction = $_SESSION['fints_action'] ?? 'statements';
			$savedDateFrom = $_SESSION['fints_datefrom'] ?? $dateFrom;
			$savedDateTo = $_SESSION['fints_dateto'] ?? $dateTo;

			unset($_SESSION['fints_state']);
			unset($_SESSION['fints_pending_action']);
			unset($_SESSION['fints_action']);
			unset($_SESSION['fints_datefrom']);
			unset($_SESSION['fints_dateto']);

			// Fetch statements after TAN confirmation
			$result = $fints->fetchStatements($savedDateFrom, $savedDateTo);

			if ($result === 0) {
				// Another TAN required (unlikely but possible)
				$_SESSION['fints_state'] = $fints->persist();
				$_SESSION['fints_action'] = 'statements';
				$_SESSION['fints_datefrom'] = $savedDateFrom;
				$_SESSION['fints_dateto'] = $savedDateTo;
				setEventMessages($langs->trans("SecureGoPlusConfirmRequired"), null, 'warnings');
			} elseif (is_array($result)) {
				$transactions = $result['transactions'] ?? array();
				$balance = $result['balance'] ?? array();
				setEventMessages($langs->trans("TransactionsFound", count($transactions)), null, 'mesgs');

				// Store transactions for import
				$_SESSION['fints_transactions'] = $transactions;
				$_SESSION['fints_balance'] = $balance;

				// Save session state for cronjob before closing
				$cronState = $fints->persist();
				if (!empty($cronState)) {
					dolibarr_set_const($db, 'BANKIMPORT_CRON_STATE', $cronState, 'chaine', 0, '', $conf->entity);
					dol_syslog("BankImport: Saved session state for cronjob after TAN confirmation", LOG_DEBUG);
				}

				$fints->close();
			} else {
				setEventMessages($langs->trans("FetchFailed").': '.$fints->error, null, 'errors');
			}
		} elseif ($result == 0) {
			// Still waiting
			setEventMessages($langs->trans("WaitingForSecureGoConfirmation"), null, 'warnings');
			$_SESSION['fints_state'] = $fints->persist();
		} else {
			setEventMessages($langs->trans("TANCheckFailed").': '.$fints->error, null, 'errors');
			unset($_SESSION['fints_state']);
		}
	} else {
		setEventMessages("Keine aktive Session. Bitte erneut abrufen.", null, 'errors');
		unset($_SESSION['fints_state']);
		unset($_SESSION['fints_pending_action']);
	}
}

/*
 * View
 */

$form = new Form($db);

$title = $langs->trans("BankStatements");
llxHeader('', $title, '', '', 0, 0, '', '', '', 'mod-bankimport page-statements');

print load_fiche_titre($title, '', 'bank');

// Check configuration
$fints = new BankImportFinTS($db);
if (!$fints->isConfigured()) {
	print '<div class="error">';
	print $langs->trans("FinTSNotConfigured");
	print ' <a href="'.dol_buildpath('/bankimport/admin/setup.php', 1).'">'.$langs->trans("GoToSetup").'</a>';
	print '</div>';
	llxFooter();
	$db->close();
	exit;
}

// Check for pending cron TAN notification
$cronNotification = BankImportCron::getNotification();
if ($cronNotification !== null) {
	$notifType = $cronNotification['type'];
	$notifDate = $cronNotification['date'];

	if ($notifType === 'tan_required') {
		print '<div class="warning">';
		print '<strong>'.$langs->trans("AutoImportTANRequired").'</strong><br>';
		print $langs->trans("AutoImportTANRequiredDesc");
		print ' <a class="button buttongen" href="'.$_SERVER["PHP_SELF"].'?action=resumecron&token='.newToken().'">'.$langs->trans("CheckSecureGoStatus").'</a>';
		print '</div><br>';
	} elseif (in_array($notifType, array('login_error', 'fetch_error', 'config_error', 'error'))) {
		print '<div class="error">';
		print '<strong>'.$langs->trans("AutoImportError").'</strong><br>';
		print $langs->trans("AutoImportErrorDesc", dol_print_date($notifDate, 'dayhour'));
		print '</div><br>';
	}
}

// Check for old data warning
$lastFetch = getDolGlobalInt('BANKIMPORT_LAST_FETCH');
if ($lastFetch > 0 && (time() - $lastFetch) > 14 * 86400) {
	print '<div class="warning">';
	print $langs->trans("LastFetchWarning", dol_print_date($lastFetch, 'day'));
	print '</div><br>';
}

if (!$fints->isLibraryAvailable()) {
	print '<div class="error">';
	print $langs->trans("FinTSLibraryNotFound");
	print '<br><code>cd '.dirname(__FILE__).' && composer install</code>';
	print '</div>';
	llxFooter();
	$db->close();
	exit;
}

// Filter form
print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="action" value="fetch">';

print '<div class="fichecenter">';
print '<table class="border centpercent">';

// IBAN display
print '<tr>';
print '<td class="titlefield">'.$langs->trans("Account").'</td>';
print '<td><strong>'.dol_escape_htmltag($fints->getIban()).'</strong></td>';
print '</tr>';

// Date from
print '<tr>';
print '<td>'.$langs->trans("DateFrom").'</td>';
print '<td>';
print $form->selectDate($dateFrom, 'date_from', 0, 0, 0, '', 1, 1);
print '</td>';
print '</tr>';

// Date to
print '<tr>';
print '<td>'.$langs->trans("DateTo").'</td>';
print '<td>';
print $form->selectDate($dateTo, 'date_to', 0, 0, 0, '', 1, 1);
print '</td>';
print '</tr>';

print '</table>';
print '</div>';

print '<div class="center">';
print '<input type="submit" class="button" value="'.$langs->trans("FetchStatements").'">';

// SecureGo Plus polling button
if (!empty($_SESSION['fints_state'])) {
	print ' <a class="button" href="'.$_SERVER["PHP_SELF"].'?action=checktan&token='.newToken().'">'.$langs->trans("CheckSecureGoStatus").'</a>';
}
print '</div>';

print '</form>';

// JavaScript for automatic TAN polling
if (!empty($_SESSION['fints_state'])) {
	print '<script type="text/javascript">
	var tanPollingInterval = null;
	var tanPollingCount = 0;
	var tanPollingMaxAttempts = 60; // 3 minutes at 3 second intervals

	function startTanPolling() {
		if (tanPollingInterval) return;

		document.getElementById("tan-status-container").style.display = "block";
		updateTanStatus("Warte auf Bestätigung in SecureGo Plus App...", "info");

		tanPollingInterval = setInterval(checkTanStatus, 3000);
		// First check immediately
		checkTanStatus();
	}

	function stopTanPolling() {
		if (tanPollingInterval) {
			clearInterval(tanPollingInterval);
			tanPollingInterval = null;
		}
	}

	function updateTanStatus(message, type) {
		var statusEl = document.getElementById("tan-status-message");
		statusEl.innerHTML = message;
		statusEl.className = "tan-status-" + type;
	}

	function checkTanStatus() {
		tanPollingCount++;

		if (tanPollingCount > tanPollingMaxAttempts) {
			stopTanPolling();
			updateTanStatus("Zeitüberschreitung. Bitte erneut versuchen.", "error");
			return;
		}

		updateTanStatus("Prüfe Status... (" + tanPollingCount + "/" + tanPollingMaxAttempts + ")", "info");

		fetch("'.dol_buildpath('/bankimport/ajax/checktan.php', 1).'?token='.newToken().'", {
			method: "GET",
			headers: {
				"Accept": "application/json"
			}
		})
		.then(response => response.json())
		.then(data => {
			if (data.status === "success") {
				stopTanPolling();
				updateTanStatus("Erfolgreich! " + data.count + " Buchungen abgerufen.", "success");

				// Display balance and transactions
				displayBalance(data.balance);
				if (data.transactions && data.transactions.length > 0) {
					displayTransactions(data.transactions);
				}

				// Hide polling container after success
				setTimeout(function() {
					document.getElementById("tan-status-container").style.display = "none";
				}, 3000);

			} else if (data.status === "waiting") {
				updateTanStatus("Warte auf Bestätigung in SecureGo Plus App... (" + tanPollingCount + "/" + tanPollingMaxAttempts + ")", "info");

			} else if (data.status === "tan_required") {
				// Another TAN required, keep polling
				updateTanStatus("Weitere TAN erforderlich - bitte erneut bestätigen", "warning");

			} else {
				stopTanPolling();
				updateTanStatus("Fehler: " + data.message, "error");
			}
		})
		.catch(error => {
			console.error("Error:", error);
			// Don\'t stop on network errors, just retry
			updateTanStatus("Netzwerkfehler, versuche erneut...", "warning");
		});
	}

	function displayBalance(balance) {
		if (!balance || !balance.amount) return;

		var color = balance.amount >= 0 ? "green" : "red";
		var date = balance.date || "";
		var html = "<br><div class=\"info\" style=\"padding: 10px; background: #e8f4e8; border: 1px solid #4CAF50; border-radius: 4px; margin-bottom: 15px;\">";
		html += "<strong>'.$langs->trans("AccountBalance").':</strong> ";
		html += "<span style=\"color: " + color + "; font-size: 1.2em; font-weight: bold;\">" + formatCurrency(balance.amount) + " " + (balance.currency || "EUR") + "</span>";
		html += " <span class=\"opacitymedium\">('.$langs->trans("AsOf").' " + date + ")</span>";
		html += "</div>";

		document.getElementById("balance-container").innerHTML = html;
	}

	function displayTransactions(transactions) {
		var html = "<br><h3>'.$langs->trans("Transactions").' (" + transactions.length + ")</h3>";
		html += "<table class=\"noborder centpercent\">";
		html += "<tr class=\"liste_titre\">";
		html += "<th>'.$langs->trans("Date").'</th>";
		html += "<th>'.$langs->trans("Name").'</th>";
		html += "<th>'.$langs->trans("Description").'</th>";
		html += "<th class=\"right\">'.$langs->trans("Amount").'</th>";
		html += "</tr>";

		var totalCredit = 0;
		var totalDebit = 0;

		transactions.forEach(function(trans) {
			var date = new Date(trans.date * 1000);
			var dateStr = date.toLocaleDateString("de-DE");
			var amountClass = trans.amount >= 0 ? "green" : "red";
			var amountPrefix = trans.amount >= 0 ? "+" : "";

			if (trans.amount >= 0) {
				totalCredit += trans.amount;
			} else {
				totalDebit += Math.abs(trans.amount);
			}

			html += "<tr class=\"oddeven\">";
			html += "<td class=\"nowraponall\">" + dateStr + "</td>";
			html += "<td>" + escapeHtml(trans.name || "") + "</td>";
			html += "<td class=\"small\">" + escapeHtml((trans.reference || "").substring(0, 80)) + "</td>";
			html += "<td class=\"right nowraponall\"><span style=\"color: " + amountClass + ";\">" + amountPrefix + formatCurrency(trans.amount) + " EUR</span></td>";
			html += "</tr>";
		});

		// Totals row
		var balance = totalCredit - totalDebit;
		var balanceColor = balance >= 0 ? "green" : "red";
		html += "<tr class=\"liste_total\">";
		html += "<td colspan=\"3\" class=\"right\">'.$langs->trans("Total").'</td>";
		html += "<td class=\"right nowraponall\">";
		html += "<span style=\"color: green;\">+" + formatCurrency(totalCredit) + " EUR</span>";
		html += " / ";
		html += "<span style=\"color: red;\">-" + formatCurrency(totalDebit) + " EUR</span>";
		html += " = ";
		html += "<strong style=\"color: " + balanceColor + ";\">" + formatCurrency(balance) + " EUR</strong>";
		html += "</td>";
		html += "</tr>";

		html += "</table>";

		// Import button
		html += "<div class=\"center\" style=\"margin-top: 15px;\">";
		html += "<form method=\"POST\" action=\"" + window.location.pathname + "\">";
		html += "<input type=\"hidden\" name=\"token\" value=\"'.newToken().'\">";
		html += "<input type=\"hidden\" name=\"action\" value=\"import\">";
		html += "<input type=\"submit\" class=\"button button-save\" value=\"'.$langs->trans("ImportTransactions").'\">";
		html += " <a class=\"button\" href=\"'.dol_buildpath('/bankimport/list.php', 1).'\">'.$langs->trans("ViewImportedTransactions").'</a>";
		html += "</form>";
		html += "</div>";

		document.getElementById("transactions-container").innerHTML = html;
	}

	function escapeHtml(text) {
		var div = document.createElement("div");
		div.textContent = text;
		return div.innerHTML;
	}

	function formatCurrency(amount) {
		return amount.toFixed(2).replace(".", ",").replace(/\B(?=(\d{3})+(?!\d))/g, ".");
	}

	// Start polling automatically when page loads
	document.addEventListener("DOMContentLoaded", function() {
		startTanPolling();
	});
	</script>

	<style>
	#tan-status-container {
		margin: 20px 0;
		padding: 15px;
		border: 1px solid #ccc;
		border-radius: 5px;
		background: #f9f9f9;
	}
	.tan-status-info { color: #0066cc; }
	.tan-status-success { color: #008800; font-weight: bold; }
	.tan-status-warning { color: #cc6600; }
	.tan-status-error { color: #cc0000; }
	#tan-status-spinner {
		display: inline-block;
		width: 20px;
		height: 20px;
		border: 2px solid #f3f3f3;
		border-top: 2px solid #3498db;
		border-radius: 50%;
		animation: spin 1s linear infinite;
		margin-right: 10px;
		vertical-align: middle;
	}
	@keyframes spin {
		0% { transform: rotate(0deg); }
		100% { transform: rotate(360deg); }
	}
	</style>

	<div id="tan-status-container" style="display: none;">
		<div id="tan-status-spinner"></div>
		<span id="tan-status-message" class="tan-status-info">Initialisiere...</span>
	</div>';
}

print '<div id="balance-container"></div>';
print '<div id="transactions-container">';

// Display account balance from bank
if (!empty($balance)) {
	print '<br>';
	print '<div class="info" style="padding: 10px; background: #e8f4e8; border: 1px solid #4CAF50; border-radius: 4px; margin-bottom: 15px;">';
	print '<strong>'.$langs->trans("AccountBalance").':</strong> ';
	$balColor = $balance['amount'] >= 0 ? 'green' : 'red';
	print '<span style="color: '.$balColor.'; font-size: 1.2em; font-weight: bold;">'.price($balance['amount'], 0, $langs, 1, -1, 2, $balance['currency']).'</span>';
	print ' <span class="opacitymedium">('.$langs->trans("AsOf").' '.dol_print_date(strtotime($balance['date']), 'day').')</span>';
	print '</div>';
}

// Display transactions
if (!empty($transactions)) {
	print '<br>';
	print '<h3>'.$langs->trans("Transactions").' ('.count($transactions).')</h3>';

	print '<table class="noborder centpercent">';
	print '<tr class="liste_titre">';
	print '<th>'.$langs->trans("Date").'</th>';
	print '<th>'.$langs->trans("Name").'</th>';
	print '<th>'.$langs->trans("Description").'</th>';
	print '<th class="right">'.$langs->trans("Amount").'</th>';
	print '</tr>';

	$totalCredit = 0;
	$totalDebit = 0;

	foreach ($transactions as $trans) {
		print '<tr class="oddeven">';
		print '<td class="nowraponall">'.dol_print_date($trans['date'], 'day').'</td>';
		print '<td>'.dol_escape_htmltag($trans['name']).'</td>';
		print '<td class="small">'.dol_escape_htmltag(dol_trunc($trans['reference'], 80)).'</td>';
		print '<td class="right nowraponall">';

		if ($trans['amount'] >= 0) {
			$totalCredit += $trans['amount'];
			print '<span class="amount" style="color: green;">+'.price($trans['amount'], 0, $langs, 1, -1, 2, 'EUR').'</span>';
		} else {
			$totalDebit += abs($trans['amount']);
			print '<span class="amount" style="color: red;">'.price($trans['amount'], 0, $langs, 1, -1, 2, 'EUR').'</span>';
		}

		print '</td>';
		print '</tr>';
	}

	// Totals
	print '<tr class="liste_total">';
	print '<td colspan="3" class="right">'.$langs->trans("Total").'</td>';
	print '<td class="right nowraponall">';
	print '<span style="color: green;">+'.price($totalCredit, 0, $langs, 1, -1, 2, 'EUR').'</span>';
	print ' / ';
	print '<span style="color: red;">-'.price($totalDebit, 0, $langs, 1, -1, 2, 'EUR').'</span>';
	print ' = ';
	$balance = $totalCredit - $totalDebit;
	$balanceColor = $balance >= 0 ? 'green' : 'red';
	print '<strong style="color: '.$balanceColor.';">'.price($balance, 0, $langs, 1, -1, 2, 'EUR').'</strong>';
	print '</td>';
	print '</tr>';

	print '</table>';

	// Import button
	print '<div class="center" style="margin-top: 15px;">';
	print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
	print '<input type="hidden" name="token" value="'.newToken().'">';
	print '<input type="hidden" name="action" value="import">';
	print '<input type="submit" class="button button-save" value="'.$langs->trans("ImportTransactions").'">';
	print ' <a class="button" href="'.dol_buildpath('/bankimport/list.php', 1).'">'.$langs->trans("ViewImportedTransactions").'</a>';
	print '</form>';
	print '</div>';
}

print '</div>'; // End transactions-container

llxFooter();
$db->close();
