<?php
//$_POST["list_invoice"] = '262216171536-1761277632016';
if(isset($_POST["list_invoice"])){
$order_id = $_POST["list_invoice"];
$s_email = '';
}
if(isset($_POST['s_orderid'])){
$order_id = $_POST['s_orderid'];
$s_email = $_POST['s_email'];
}



if(isset($_POST["list_invoice_send"])){
	$order_id = strstr($_POST["list_invoice_send"], '|', true);
	$send_email = substr(strrchr($_POST["list_invoice_send"], "|"), 1);
}

		require_once ('../../../includes/connection_home_mysqli.php');	
		require_once ('../../../dompdf/dompdf_config.inc.php');
		require_once ('../class/class.phpmailer.php');
		require_once ('../class/class.smtp.php');
		$db->set_charset("utf8");
	
// GET SETTINGS
		$sql_2 = ("SELECT id,parent_id,name,wert FROM lex_settings"); 
		if(!$result = $db->query($sql_2)){
		die('There was an error running the query [' . $db->error . ']');
		}
		while($row = $result->fetch_array()){
			$settings_id = $row["id"];
			$settings_source[$settings_id] = $row["wert"];	
		}
			$firma = $settings_source['11-04-01'];
			$inhaber = $settings_source['11-04-02'];
			$straße = $settings_source['11-04-03'];
			$plz = $settings_source['11-04-04'];
			$ort = $settings_source['11-04-05'];
			$ort_short = $settings_source['11-04-06'];
			$ust_id = $settings_source['11-04-07'];
			$shopdomain = $settings_source['11-04-08'];
			$ust = $settings_source['11-04-09'];
			$phone = $settings_source['11-04-10'];
			$fax = $settings_source['11-04-11'];
			$email = $settings_source['11-04-12'];
			$country = $settings_source['11-04-13'];
			$bank_name = $settings_source['11-04-14'];
			$iban = $settings_source['11-04-15'];
			$bic = $settings_source['11-04-16'];
			$vat_id = $settings_source['11-04-17'];
			$logo = $settings_source['11-04-18'];

$sql_invoice_content = ("SELECT Orders,extend_informations FROM lex_orders WHERE OrderID = '$order_id'"); 
		if(!$result = $db->query($sql_invoice_content)){
			die('There was an error running the query [' . $db->error . ']');
			}
			while($row = $result->fetch_array()){
			$invoice_json[] = $row['Orders'];
			$information_json[] = $row['extend_informations'];
			}

	$invoice_array = json_decode ($invoice_json[0],true);	
	$information_array = json_decode ($information_json[0],true);	
	//ABSENDE DATEN
	//print_r ($invoice_array);
	//EBAY INFORMATION
	$kunde_name = $invoice_array['ShippingAddress']['Name'];
	$kunde_straße = $invoice_array['ShippingAddress']['Street1'];
	$kunde_plz = $invoice_array['ShippingAddress']['PostalCode'];
	$kunde_ort = $invoice_array['ShippingAddress']['CityName'];
	$ebay_name = $invoice_array['BuyerUserID'];
	$orderid = $invoice_array['OrderID'];
		$createtime_iso = $invoice_array['CreatedTime'];
		$createtime = strstr($createtime_iso, 'T', true);
		//BILLNO.
		$suchen   = array( '-','t',':','z','.');
		$ersetzen = array( '','','','','');
		$billno= str_replace( $suchen, $ersetzen, strtolower( $createtime_iso ) );
	
	//ZAHLUNGSART
	$payment_method = $invoice_array['CheckoutStatus']['PaymentMethod'];
	if($payment_method == 'Paypal'){
		$payment_method = 'Paypal';
	}
	if($payment_method == 'MoneyXferAcceptedInCheckout'){
		$payment_method = 'Vorkasse';	
	}
	if($payment_method == 'None'){
	$payment_method = 'unbekannt';
	}
		
	//DATETIME
	$t = microtime(true);
    $micro = sprintf("%03d",($t - floor($t)) * 1000);
    $datetime = gmdate('d-m-Y', $t);
	//PAYMENT TIME
	$last = mktime(0,0,0, date("m"), date("d")+15,  date("Y"));
	$payment_time = date("d-m-Y",$last);
	
	//TABLE_CONSTRUCTION
	if(isset($invoice_array['TransactionArray']['Transaction'][0])){
		$count_orders = count ($invoice_array['TransactionArray']['Transaction']);
		$table_listing_array = array ();
		for($i=0;$i < ($count_orders);$i++){
		
		$storage = $information_array[$i]['storage'];
		$lexid = $information_array[$i]['lexid'];
		$qantity = $invoice_array['TransactionArray']['Transaction'][$i]['QuantityPurchased'];
		$itemid = $invoice_array['TransactionArray']['Transaction'][$i]['Item']['ItemID'];
		$discription = $invoice_array['TransactionArray']['Transaction'][$i]['Item']['Title'];
		$single_price = $invoice_array['TransactionArray']['Transaction'][$i]['TransactionPrice'];
		$single_price_total = $single_price * $qantity;
		$subtotal_price = $invoice_array['Subtotal'];
		$subtotal_price_netto = round ((($subtotal_price*100)/119),2);
		$vat_of_price = round (($subtotal_price - $subtotal_price_netto),2);
		$shipping_cost = $invoice_array['ShippingServiceSelected']['ShippingServiceCost'];
		$total_price = $invoice_array['Total'];
		$total_price_plus_shippingcost = ($total_price + $shipping_cost);
		
		$table_listing_array[] = '<tr><td class="t_quantity">'.$qantity.'</td>
							<td class="t_artnum">'.$itemid.'-('.$lexid.'-'.$storage.')'.'<br/>'.
												'</td>	
							<td class="t_discription">'.$discription.'</td>	
							<td class="t_ust">'.$ust.'</td>
							<td class="t_single_price">'.$single_price.' EUR</td>
							<td class="t_total_price">'.$single_price_total.' EUR</td></tr>';
		
		//echo $itemid.'<br/>';
		
		}
	}else{
		$storage = $information_array['storage'];
		$lexid = $information_array['lexid'];
		$qantity = $invoice_array['TransactionArray']['Transaction']['QuantityPurchased'];
		$itemid = $invoice_array['TransactionArray']['Transaction']['Item']['ItemID'];
		$discription = $invoice_array['TransactionArray']['Transaction']['Item']['Title'];
		$single_price = $invoice_array['TransactionArray']['Transaction']['TransactionPrice'];
		$single_price_total = $single_price * $qantity;
		$subtotal_price = $invoice_array['Subtotal'];
		$subtotal_price_netto = round ((($subtotal_price*100)/119),2);
		$vat_of_price = round (($subtotal_price - $subtotal_price_netto),2);
		$shipping_cost = $invoice_array['ShippingServiceSelected']['ShippingServiceCost'];
		$total_price = $invoice_array['Total'];	
		$total_price_plus_shippingcost = ($total_price + $shipping_cost);
		
		$table_listing_array[] = '<tr><td class="t_quantity">'.$qantity.'</td>
							<td class="t_artnum">'.$itemid.'<br/>('.$lexid.'-'.$storage.')</td>	
							<td class="t_discription">'.$discription.'</td>	
							<td class="t_ust">'.$ust.'</td>
							<td class="t_single_price">'.$single_price.' EUR</td>
							<td class="t_total_price">'.$single_price_total.' EUR</td></tr>';
	}

		array_push($table_listing_array, '
		<tr>
			<td class="line"></td>
			<td class="line"></td>
			<td class="line"></td>
			<td class="line"></td>
			<td class="line"></td>
			<td class="line"></td>
		</tr>
		<tr>
			<td></td>
			<td></td>
			<td id="end_netto_content">Summe Artikel (netto)</td>
			<td></td>
			<td></td>
			<td id="sub_total_netto">'.$subtotal_price_netto.' EUR</td>
		</tr>
		<tr>
			<td></td>
			<td></td>
			<td id="vat_content">zzgl. MwSt. '.$ust.'%</td>
			<td></td>
			<td></td>
			<td id="vat_of_price">'.$vat_of_price.' EUR</td>
		</tr>
		<tr>
			<td></td>
			<td></td>
			<td id="total_price_content">Summe Artikel (brutto)</td>
			<td></td>
			<td></td>
			<td id="total_price">'.$subtotal_price.' EUR</td>
		</tr>
		<tr>
			<td></td>
			<td></td>
			<td class="line" id="shipping_cost_content">Versandkosten</td>
			<td class="line" ></td>
			<td class="line" ></td>
			<td class="line" id="spipping_cost">'.$shipping_cost.' EUR</td>
		</tr>
		<tr>
			<td></td>
			<td></td>
			<td class="bold" id="total_cost_content">Gesamtsumme (brutto)</td>
			<td class="bold"></td>
			<td class="bold"></td>
			<td class="bold" class="bold" id="spipping_cost">'.$total_price.' EUR</td>
		</tr>
		');						
		
		$table_listing_string = implode ('',$table_listing_array);	
		
$content = '
	
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="dompdf.view" content="XYZ,0,0,1" />
<link href="../css/ebay_invoice.css" rel="stylesheet" type="text/css" />
<link href="ebay_invoice.css" rel="stylesheet" type="text/css" />
</head>
<body>

	
<div id="invoice_logo"><img src="../gfx/'.$logo.'"/></div>

	<div id="absender_box">
		<div id="absender-Firma">'.$firma.' - </div>
		<div id="absender-name">Inh. '.$inhaber.' - </div>
		<div id="absender-strasse">'.$straße.' - </div>
		<div id="absender-plz">'.$plz.'</div>
		<div id="absender-ort">'.$ort.'</div>
	</div>
 </tbody>
	</table>
	<div id="shipping_adress">
		<div id="shipping_name">'.$kunde_name.'</div>
		<div id="shipping_straße">'.$kunde_straße.'</div>
		<div id="shipping_ort">'.$kunde_plz.' '.$kunde_ort.'</div>
	</div>

	<div id="kundennummer">
		<div id="ebay_info">Bitte bei Zahlungen immer angeben.</div>
		<div id="ebay_name">Kunde: '.$ebay_name.'</div>
	</div>
	
	<div id="headline_rechnung">Rechnung</div>

	<div id="bestellnummer">
		<div id="bestellnummer_content">Bestellnr.:</div>
		<div id="OrderID">'.$orderid.'</div>
	</div>

	<div id="bill_informations">
		<div id="ort_datum">'.$ort_short.', den: '.$datetime.'</div>
		<div id="ust">USt.-ID-Nr.: '.$ust_id.'</div>
		<div id="billno">Rechn-Nr.: '.$billno.'</div>
	</div>
	
	<div id="youre_order">
	Ihre Bestellung vom '.$createtime.' bei '.$shopdomain.'
	</div>
	
	<table id="table" class="tablesorter">
	  <colgroup>
		<col id="col_quantity"/>
		<col id="col_artnum"/>
		<col id="col_discription"/>
		<col id="col_ust"/>
		<col id="col_single_price"/>
		<col id="col_total_price"/>
	  
	  </colgroup>
	  <thead>
		<tr>
		  <th class="h_quantity">Menge</th>
		  <th class="h_artnum">Art-Nr.</th>
		  <th class="h_discription">Beschreibung</th>
		  <th class="h_ust">UST %</th>
		  <th class="h_single_price">Einzelpreis</th>
		  <th class="h_total_price">Gesamtpreis</th>
		</tr>
	  </thead>
		<tbody id="tbody">
			'.$table_listing_string.'
		
		
		<tr>
		 <th id="payment_method" colspan="6">
		 Ihre gewählte Zahlungsweise: '.$payment_method.'
		 </th>
		</tr>
		<tr>
		<th id="payment_time" colspan="6">
		 Zahlbar bis zum: '.$payment_time.'
		 </th>
		</tr>
		<tr>
		<th id="thanks" colspan="6">
		 Herzlichen Dank für Ihre Bestellung! Bitte empfehlen Sie uns weiter.
		 </th>
		</tr>
		<tr>
		<th id="lex_thanks" colspan="6">
		 Ihre gekauften Artikel wurden eingestellt mit lexington-software.de
		 </th>
		</tr>
		
		</tbody>
	</table>	
	
	<table id="footer" class="">
	  <colgroup>
		<col id="col_1" />
		<col id="col_2"/>
		<col id="col_3"/>
	  </colgroup>
	  <tr>
		<td id="f_1">
			'.$firma.' <br/>
			'.$inhaber.'<br/>
			'.$straße.'<br/>
			'.$plz.' '.$ort.'<br/>
			'.$country.'
		</td>
		<td id="f_2">
			fon: '.$phone.'<br/>
			fax: '.$fax.'<br/>
			shop: '.$shopdomain.'<br/>
			email: '.$email.'<br/><br/>
		</td>
		<td id="f_3">
			Bank: '.$bank_name.'<br/>
			IBAN: '.$iban.'<br/>
			BIC: '.$bic.'<br/>
			USTID: '.$ust_id.'<br/>
			Stuernummer: '.$vat_id.'
		</td>

	  </tr>
	</table>

	';

		/*	
			$dompdf = new DOMPDF();
			$dompdf->load_html(ob_get_clean()); 
			$dompdf->set_base_path('../css/');
			$dompdf->load_html($content);
			$dompdf->set_paper('a4','portrait');
			$dompdf->render();
			$dompdf->stream('file.pdf',array('Attachment' =>0));
			
			echo $content;
		*/
if($s_email == ''){
	$dompdf = new DOMPDF();
			$dompdf->load_html(ob_get_clean()); 
			$dompdf->set_base_path('../css/');
			$dompdf->load_html($content);
			$dompdf->set_paper('a4','portrait');
			$dompdf->render();
			$dompdf->stream('file.pdf',array('Attachment' =>0));
}else{
	$dompdf = new DOMPDF();
				$dompdf->load_html(ob_get_clean()); 
				$dompdf->set_base_path('../css/');
				$dompdf->load_html($content);
				$dompdf->set_paper('a4','portrait');
				$dompdf->render();
				$output = $dompdf->output();
				file_put_contents('tmp/'.$order_id.'.pdf', $output);
	
				$mail = new PHPMailer;

				$mail->isSMTP();
				$mail->SMTPAuth = true;
				$mail->CharSet = "UTF-8";
				//$mail->SMTPDebug = 4;
				//$mail->Debugoutput = 'html';
				$mail->Host = $settings_source['13-03'];
				$mail->Username = $settings_source['13-04'];
				$mail->Password = $settings_source['13-05'];
				$mail->SMTPSecure = $settings_source['13-06'];
				$mail->Port = $settings_source['13-02'];
				//$mail->SMTPDebug = 3;
				$mail->From = $settings_source['13-01'];
				$mail->isHTML();
	
				//SEND EMAIL WITH INVOICE
				$mail->Subject = "Ihre Rechnung";
				$mail->Body = "Mit dieser Email erhalten Sie Ihre Rechnung im PDF Dokument";
				$mail->FromName = $firma;
				$mail->addAddress($s_email, $kunde_name);
				$mail->AltBody = $firma.'Ihre Rechnung im PDF Format';     //Plain Text Body
				$mail->AddAttachment('tmp/'.$order_id.'.pdf');
				if(!$mail->Send()){
				echo "Mailer Error: " . $mail->ErrorInfo;
				} else {
				
				}
				unlink('tmp/'.$order_id.'.pdf');

}

		
?>
