<?php

include "functions.php";
require_once __DIR__ . "/app/ledger.php";

$pdo = app_db_pdo();
$saasUser = saas_current_user($pdo);
$tenantId = 0;
$hasAccess = false;

function kaffeeliste_money(int $cents): string
{
	return saas_format_money_cents($cents) . ' €';
}

if ($saasUser !== null && saas_user_has_role(['owner', 'admin', 'treasurer'], $saasUser)) {
	$tenantId = (int)$saasUser['tenant_id'];
	$hasAccess = true;
}

if (!$hasAccess && $saasUser === null && checkKaffeelisteAdmin($conn, $mailadress)) {
	$tenant = ledger_fetch_default_tenant($pdo);
	if ($tenant !== null) {
		$tenantId = (int)$tenant['id'];
		$hasAccess = true;
	}
}

$participants = $hasAccess
	? ledger_fetch_participant_summaries($pdo, $tenantId, ['active_only' => true])
	: [];

include "header.php";
include "headerline.php";
include "nav.php";
?>

<section id="banner">
	<div class="content">
<?php
if ($hasAccess) {
?>
		<h2>Aktive Mitarbeiter mit Gesamtstand</h2>
		<br>
		<ul class="actions">
			<li>
				<form action="exportKaffeeliste.php" method="get">
					<button type="submit">Kaffeeliste exportieren</button>
				</form>
			</li>
			<li>
				<form action="letzteneintraege.php" method="get">
					<button type="submit">Letzten Einträge</button>
				</form>
			</li>
			<li>
				<form action="csvupload.php" method="get">
					<button type="submit">CSV Upload</button>
				</form>
			</li>
		</ul>

		<br>
		<table border="1" class="table table-striped table-bordered">
			<tr>
				<th>Name</th>
				<th>E-Mail</th>
				<th>Aktueller Stand</th>
				<th>Gesamtausgabe (€)</th>
				<th>Gesamtstriche</th>
				<th>Gesamteinzahlungen</th>
			</tr>
<?php
	foreach ($participants as $participant) {
		$legacyId = $participant['legacy_mitarbeiter_id'];
		$name = saas_html($participant['display_name']);
		$email = saas_html((string)($participant['email'] ?? ''));
		$balance = kaffeeliste_money((int)$participant['balance_cents']);
		$totalCosts = kaffeeliste_money((int)$participant['total_costs_cents']);
		$totalMarks = number_format((int)$participant['total_marks'], 0, ',', '.');
		$totalPayments = kaffeeliste_money((int)$participant['total_payments_cents']);

		echo "<tr>";
		if ($legacyId !== null) {
			echo "<td><a href=\"teilnehmerauswertung.php?user_id=" . (int)$legacyId . "\">{$name}</a></td>";
		} else {
			echo "<td>{$name}</td>";
		}
		echo "<td>{$email}</td>";
		echo "<td>{$balance}</td>";
		echo "<td>{$totalCosts}</td>";
		echo "<td>{$totalMarks}</td>";
		echo "<td>{$totalPayments}</td>";
		echo "</tr>";
	}
?>
		</table>
		<br><br>

		<form action="mailversenden.php" method="get">
			<button type="submit">Info-Mail versenden</button>
		</form>
<?php
} else {
	echo "<h2>Kein Zugriff</h2>";
}
?>
	</div>
</section>

<?php include "footer.php"; ?>
