<?php
$test = explode("_", $_POST['ID']);
$ID = $test['1'];
$Jahr = $test['0'];

$sql = "SELECT *, DATE_FORMAT(Datum, '%d.%m.%Y') AS Datum FROM " . PREFIX . "_Rechnungen WHERE (Jahr = \"" . $Jahr . "\" AND ID = \"" . $ID . "\");";
$resultr = $db->query($sql);
$ntr = $resultr->fetch_assoc();

$sql = "SELECT * FROM " . PREFIX . "_Kontakte WHERE (ID = \"" . $ntr['Kontakt_ID'] . "\");";
$resultk = $db->query($sql);
$ntk = $resultk->fetch_assoc();

$sql = "SELECT *, DATE_FORMAT(Bezahlt_am, '%d.%m.%Y') AS Datum FROM " . PREFIX . "_Teilzahlungen WHERE (Referenz_Jahr = \"" . $Jahr . "\" AND Referenz_ID = \"" . $ID . "\") ORDER BY Bezahlt_am ASC;";
$resultt = $db->query($sql);

echo "<fieldset>\n";
echo "	<legend>Teilzahlungen zu Rechnung " . $Jahr . "_" . $ID . " vom " . $ntr['Datum'] . "</legend>\n";
echo "	<label>Kunde</label>\n";
echo "	<label>" . $ntk['Nachname'] . ", " . $ntk['Firma'] . "</label><br class=\"fix\" />\n";
echo "	<label>Rechnungsbetrag</label>\n";
echo "	<label>" . number_format($ntr['Preis'] * (1 + $ntr['MwSt'] / 100), '2', ',', '.') . " €</label>\n";
echo "	<br class=\"fix\" />\n";
echo "	<br class=\"fix\" />\n";
echo "	<fieldset>\n";
echo "		<legend class=\"sub\">Verzeichnete Teilzahlungen</legend>\n";
$Summe = 0;
while ($ntt = $resultt->fetch_assoc())
{
	$Summe = $Summe + round($ntt['Preis'] * (1 + $ntt['MwSt'] / 100), 2);
	echo "		<label>Datum</label>\n";
	echo "		<label>" . $ntt['Datum'] . "</label>\n";
	echo "		<label>Betrag inkl. MwSt</label>\n";
	echo "		<label>" . number_format($ntt['Preis'] * (1 + $ntt['MwSt'] / 100), '2', ',', '.') . " €</label><br class=\"fix\" >\n";
}
echo "		<label>Gesamt inkl. MwSt</label>\n";
echo "		<label>&nbsp;</label>\n";
echo "		<label>&nbsp;</label>\n";
echo "		<label>" . number_format($Summe, '2', ',', '.') . " €</label>\n";
echo "	</fieldset>\n";
echo "	<br />\n";
if ($Summe < $ntr['Preis'] * (1 + $ntr['MwSt'] / 100))
{
	echo "	<label>Restbetrag</label>\n";
	echo "	<label>" . number_format($ntr['Preis'] * (1 + $ntr['MwSt'] / 100) - $Summe, '2', ',', '.') . " €</label>\n";
}
else
{
	echo "	<p>Der Rechnungsbetrag wurde vollständig bezahlt. Sie können die Rechnung nun in den offenen Posten <i>als bezahlt</i> eintragen</p>\n";
}
echo "</fieldset>\n";