<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

//include_once '../../config.inc.php';
include_once '/srv/www/vhosts/vgr-vertrieb.de/httpdocs/config.inc.php';

$db = new mysqli(
	$config_shop_system['db_host'],
	$config_shop_system['db_user'],
	$config_shop_system['db_password'],
	$config_shop_system['db_name']
);

$db->query("SET NAMES 'utf8'");

// get exported orders
$sql = "SELECT shipping_list_number, order_number FROM orders WHERE export_to_shipping=1";
$result = $db->query($sql);
$exported_orders = array();
while ($obj = $result->fetch_object()) {
	if (!$obj->shipping_list_number) {
		$obj->shipping_list_number = $obj->order_number;
	}
	$exported_orders[] = $obj->shipping_list_number;
}

// get sendet orders from external database
/*
$db_extern = new mysqli(
		$config_shop_system['db_host'],
		$config_shop_system['db_user'],
		$config_shop_system['db_password'],
		$config_shop_system['db_name']
);
*/
$db_extern = new mysqli(
		'rottlerlogistik.dyndns.org',
		'U10VGR',
		'vgRwa10',
		'U10VGR',
		32751
);

if (!$db_extern->connect_errno) {
	$db_extern->query("SET NAMES 'utf8'");
	
	$sql = "SELECT * FROM versandliste WHERE lieferscheinNr IN ('" . implode("','", $exported_orders) . "')";
	$result = $db_extern->query($sql);
	$sended_objects = array();
	while ($obj = $result->fetch_object()) {
		if (isset($sended_objects[$obj->lieferscheinNr])) {
			$sended_objects[$obj->lieferscheinNr]->paketnummer .= '; '.$obj->paketnummer;
		}
		else {
			$sended_objects[$obj->lieferscheinNr] = $obj;
		}
	}
	
	// update orders
	foreach ($sended_objects as $sendobject) {
		$trackingcode = $sendobject->paketnummer;
		$order_number = $sendobject->lieferscheinNr;
		$sql = "UPDATE orders SET export_to_shipping=2, trackingcode='$trackingcode' WHERE order_number='$order_number' OR shipping_list_number='$order_number'";
		$db->query($sql);
	}
}
else {
	echo "connection error";
}
	
exit();

