#!/usr/bin/env php
<?php
//$_SERVER['SERVER_NAME'] = "biuro.biall-net.pl";
//require("/Library/Server/Web/Data/Sites/Default/dev-bzyk/se-lib/bootstrap.php");
require("config_inc.php"); //generated by build_BI_audit.xml

#require("/Library/Server/Web/Data/Sites/SE-producition-git/SE/se-lib/bootstrap.php");
date_default_timezone_set('Europe/Warsaw');// PHP 5 >= 5.1.0 required by date functions
Lib::loadClass('V');

if (!isset($argv[1])) die("Missing parameter\n");
if ($argv[1] == "-") $data = stream_get_contents(STDIN);
else {
	if (!is_file($argv[1])) die("File {$argv[1]} not found\n");
	$data = @file_get_contents($argv[1]);
	if (!$data) die("Error loading file\n");
}
//preg_match('/.*\.([[:alpha:]]*)$/', $argv[1], $match);
//switch ($match[1]) {
//	case "data":
		$results = @json_decode(gzuncompress(base64_decode($data)), true);
//		break;
//	case "txt":
//		$results = unserialize($data);
//		break;
//	default:
//		die("Unknown file type\n");
//}


if (!$results) die("Error loading data\n");
$TABLE = "BI_audit_ALL";

$query = "select * from BI_audit_ALL_ref_RELATIONS";
$result = DB::getPDO()->fetchAll($query);
foreach ($result as $row) $relations[$row['ID']] = $row['RELATION'];


//$query = "select `DATA` from BI_audit_ALL_results where ID=4";
//$data = DB::getPDO()->fetchvalue($query);
//$results = json_decode(gzuncompress(base64_decode($data)), true);

$xmlRoot = "RelatedFeatureRoot";
$xmlRoot2 = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA";
$xmlElements = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row";

$items_results = [];
$items_kontrahenci = [];
$items_kw_person = [];
$kontrahenci = [];
$kw_person = [];
foreach ($results as $result) {
	$item_results = [];
	foreach ($result as $ID => $rel) {
		$query = "select REMOTE_TABLE, REMOTE_ID from {$TABLE} where ID = '{$ID}'";
		$row = DB::getPDO()->fetchFirst($query);
		$query = "select * from `{$row['REMOTE_TABLE']}` where ID = '{$row['REMOTE_ID']}'";
		$obj = DB::fetch(DB::query($query));
		//if ($row['REMOTE_TABLE'] == 'BI_audit_ENERGA_PRACOWNICY') unset($obj->source);
		$item_result = [$row['REMOTE_TABLE'] => (array) $obj];
		if (is_array($rel)) $rel = implode(", ", $rel);
		elseif (is_numeric($rel)) $rel = $relations[$rel];
		if ($rel) $item_result['relation_from'] = $rel;
		$item_results['object'][] = $item_result;
		if ($row['REMOTE_TABLE'] == "BI_audit_ENERGA_RUM_KONTRAHENCI" && (!in_array($row['REMOTE_ID'], $kontrahenci))) {
			$kontrahenci[] = $row['REMOTE_ID'];
			$query = "select umowy.* from BI_audit_ENERGA_RUM_UMOWY umowy join `CRM__#REF_TABLE__23` ref on umowy.ID = ref.PRIMARY_KEY where ref.REMOTE_PRIMARY_KEY = '{$row['REMOTE_ID']}'";
			$res = DB::query($query);
			if (mysql_num_rows($res)) {
				$umowy = [];
				while ($obj = DB::fetch($res)) $umowy[] = (array) $obj;
				$item_kontrahenci['ID'] = $row['REMOTE_ID'];
				$item_kontrahenci['BI_audit_ENERGA_RUM_UMOWY'] = $umowy;
				$items_kontrahenci[] = $item_kontrahenci;
			}
		} elseif ($row['REMOTE_TABLE'] == "BI_audit_KW_requested_person" && (!in_array($row['REMOTE_ID'], $kw_person))) {
			$kw_person[] = $row['REMOTE_ID'];
			$query = "select kw.* from BI_audit_KW_requested kw join `CRM__#REF_TABLE__24` ref on kw.ID = ref.PRIMARY_KEY where ref.REMOTE_PRIMARY_KEY = '{$row['REMOTE_ID']}'";
			$res = DB::query($query);
			if (mysql_num_rows($res)) {
				$kw = [];
				while ($obj = DB::fetch($res)) $kw[] = (array) $obj;
				$item_kw_person['ID'] = $row['REMOTE_ID'];
				$item_kw_person['BI_audit_KW_requested'] = $kw;
				$items_kw_person[] = $item_kw_person;
			}
		}
	}
	$items_results[$xmlRoot2][$xmlElements][] = $item_results;
}
$items_results[$xmlRoot2]['BI_audit_ENERGA_RUM_KONTRAHENCI'] = $items_kontrahenci;
$items_results[$xmlRoot2]['BI_audit_KW_requested_person'] = $items_kw_person;

//print_r($items_results[$xmlRoot2]['BI_audit_KW_requested_person']);
//die();
$test = V::arrayToXML($items_results, true, $xmlRoot);
echo $test;
