<?php

$ID = $Rech_ID;
$Jahr = date("Y", time());
$pdf_type = "rechnung";

$sql = "SELECT *, DATE_FORMAT(Datum, '%d.%m.%Y') AS Datum, DATE_FORMAT(DATE_ADD(Datum, INTERVAL 14 DAY), '%d.%m.%Y') AS GUELTIG FROM 1001_Rechnungen WHERE (Jahr= \"" . $Jahr . "\" AND ID = \"" . $ID . "\");";
$result = $db->query($sql);
$nt = $result->fetch_assoc();
$sqlp = "SELECT * FROM 1001_Rechnung_Pos WHERE (Rechnung_ID = \"" . $ID . "\" AND Jahr = \"" . $Jahr . "\") ORDER BY Position ASC;";
$resultp = $db->query($sqlp);
$sqlk = "SELECT * FROM 1001_Kontakte WHERE ID = \"" . $nt['Kontakt_ID'] . "\";";
$resultk = $db->query($sqlk);
$ntk = $resultk->fetch_assoc();
$sqlab = "SELECT Preis_aus_Pos, Auftrag_Preis, DATE_FORMAT(A_Datum, '%d.%m.%Y') AS A_Datum FROM 1001_Auftraege WHERE ID = \"" . $nt['Auftrag_ID'] . "\";";
$resultab = $db->query($sqlab);
$ntab = $resultab->fetch_assoc();
$sqltext = "SELECT * FROM 1001_Texte WHERE Name = \"Rechnungen ohne Auftragsbestätigung\";";
$table = "full";
$resulttext = $db->query($sqltext);
$nttext = $resulttext->fetch_assoc();

while (strlen($nt['ID']) < 5)
{
	$nt['ID'] = "0" . $nt['ID'];
}

class PDF extends TCPDF
{

	function Header()
	{
		include __DIR__ . "/header_best.php";
	}

	function Footer()
	{
		include __DIR__ . "/footer_best.php";
	}

}

$pdf = new PDF();
$pdf->SetDisplayMode('fullpage');
$pdf->AddPage();

include __DIR__ . "/header0_best.php";


$pdf->SetY(95);
$pdf->Write(4, "Rechnung-Nr.:");
$pdf->SetX(45);
$pdf->Write(4, $nt['Jahr'] . "_" . $nt['ID']);
$pdf->SetX(138);
$pdf->Cell(15, 4, "Datum:", 0);
$pdf->Cell(47, 4, $nt['Datum'], 0, 1, 'R');
$pdf->SetRightMargin(10);
$pdf->SetY(107);
$pdf->SetFont('Helvetica', 'B', 14);
$pdf->SetTextColor(204, 0, 102);
$pdf->Write(10, "Rechnung\n");
$pdf->SetFont('Helvetica', '', 10);
$pdf->SetTextColor(0);

$var = $nttext['Text1'];
include __DIR__ . "/replace_token.php";
include __DIR__ . "/replace_rechnung.php";
include __DIR__ . "/replace_bi.php";

$pdf->SetFont('Helvetica', '', 10);
$pdf->Write(4, $var . "\n");


include __DIR__ . "/position_full.php";


include __DIR__ . "/berechnung.php";

$var = $nttext['Text2'];
include __DIR__ . "/replace_token.php";
include __DIR__ . "/replace_rechnung.php";
include __DIR__ . "/replace_bi.php";

$pdf->SetFont('Helvetica', '', 10);
$pdf->Write(4, $var);

if ("" != $nt['Text'])
{
	$pdf->Write(4, "\n" . $nt['Text'] . "\n");
}

$var = "Mit freundlichen Grüßen\nChristian Steinle";
include __DIR__ . "/replace_gruss.php";
$pdf->SetFont('Helvetica', '', 10);
$pdf->Write(4, "\n" . $var);

if(!is_dir(__DIR__ . "/1001/rechnung"))
{
	mkdir(__DIR__ . "/1001/rechnung", 0777, true);
}

$file = __DIR__ . "/1001/rechnung/R_" . $nt['Jahr'] . "_" . $nt['ID'] . ".pdf";
$pdf->Output($file, "F");

$var = $nttext['EMail'];
include __DIR__ . "/replace_token.php";
include __DIR__ . "/replace_rechnung.php";