<script lang="ts">
	import type { PageProps } from "./$types";

	import { enhance } from "$app/forms";

	import { isoToLocalDate, padInt } from "$lib/util";

	let { data, form } : PageProps = $props();

</script>

<div>
<h1>Dokumente</h1>

<form method="POST" id="create_est" action="?/create_estimate" use:enhance></form>
<form method="POST" id="create_rec" action="?/create_record" use:enhance></form>

<table>
	<caption>Dokument erstellen</caption>
	<tbody>
		<tr>
			<td>Stundenliste</td>
			<td>
				<input form="create_rec" style:width="2ch" name="month" /> -
				<input form="create_rec" style:width="4ch" name="year" placeholder="Jahr" value={new Date().getFullYear()} />
			</td>
			<td>
				<button form="create_rec" type="submit">Erstellen</button>
			</td>
		</tr>
		<tr>
			<td>Stundenschätzung</td>
			<td>
				<input form="create_est" style:width="1ch" name="quarter" />. Quartal
				<input form="create_est" style:width="4ch" name="year" placeholder="Jahr" value={new Date().getFullYear()} />
			</td>
			<td>
				<button form="create_est" type="submit">Erstellen</button>
			</td>
		</tr>
	</tbody>
</table>

<div style:width="100%" style="text-align: center;">{!(form?.success) ? form?.message : "Dokument erstellt."}</div>

<div style:height="20px"></div>

<table>

	<caption>Erstellte Dokumente</caption>
	
	<thead>
		<tr>
			<th style:width="30ch">Dateiname</th>
			<th style:width="15ch">Erstellt</th>
			<th style:width="12ch">Aktion</th>
		</tr>
	</thead>
	
	<tbody>
		{#each data.documents as doc}
			<tr>
				<td>{doc.name}</td>
				<td>{`${isoToLocalDate(doc.timestamp.toISOString())} um ${padInt(doc.timestamp.getHours(), 2)}:${padInt(doc.timestamp.getMinutes(), 2)}:${padInt(doc.timestamp.getSeconds(), 2)}`}</td>
				<td>
					<form method="GET" action={`dokumente/${doc.path}`}>
						<button type="submit">Download</button>
					</form>
				</td>
			</tr>
		{/each}
		<tr></tr>
	</tbody>

	{#if data.documents.length === 0}
		<tfoot>
			<tr>
				<td class="td-no-elements" colspan="999">Noch keine Dokumente</td>
			</tr>
		</tfoot>
	{/if}
</table>

</div>

<style>


h1 {
	width: 100%;
	text-align: center;
	font-size: 25px;
	font-weight: bold;
}

form {
	width: fit-content;
	border: none;
}

table {
	width: auto;
	margin: auto;

	border-collapse: collapse;
	border: 1px solid;
}

tbody > tr > td {
	text-align: center;
}

tbody > tr:nth-child(odd) {
	background: gray;
}

tbody > tr:nth-child(even) {
	background: lightgray;
}

tbody > tr > td:last-of-type {
	display: inline-flex;
}

tfoot {	
	border-top: 1px solid black;
}

.td-no-elements {
	text-align: center;
}
</style>
