#!/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("/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

class FindCorelations {

	private $TABLE, $TABLE_REF, $TABLE_DEST, $DEPTH;
	public $results = [];

	private $corelations = [
		'nip' => ['nip'],
		'regon' => ['regon'],
		'krs' => ['krs'],
		'pesel' => ['pesel'],
		'adres' => ['TERYT_SYM', 'TERYT_SYM_UL', 'nrDomu', 'nrLokalu'],
	];

	function __construct($TABLE, $TABLE_REF, $TABLE_DEST, $DEPTH, $ID) {
		$this->TABLE = $TABLE;
		$this->TABLE_REF = $TABLE_REF;
		$this->TABLE_DEST = $TABLE_DEST;
		$this->DEPTH = $DEPTH;
		$this->findNodes($ID);
	}

	function findNodes($ID, $corelation = "", $path = []) {
//		echo "START: {$ID}\n";
		if (isset($path[$ID])) return null;
		$path[$ID] = $corelation;
//		echo implode("->", array_keys($path)) . "\n";
//		echo count($path) . ":";
		$query = "select * from {$this->TABLE} where ID = '{$ID}'";
		if (!($result = DB::query($query))) return null;
		$row = DB::fetch($result);
		if (in_array($row->REMOTE_TABLE, $this->TABLE_DEST)) {
			if ($row->REMOTE_TABLE == "BI_audit_KW_requested") implode("->", array_keys($path)) . "\n";
			$this->results[] = $path;
			return null;
		}

		if (count($path) > $this->DEPTH) return null;
		$nodes = [];
		foreach ($this->corelations as $name => $columns) {
			$ok = 0;
			$join = [];
			foreach ($columns as $column) {
				$join[] = "t1.{$column} = t2.{$column}";
				if ($row->$column) {
					$ok++;
				}
			}
			if ($ok / count($columns) > 0.5) {
				$query = "select t2.ID as ID from {$this->TABLE} t1 join {$this->TABLE} t2 on " . implode(" and ", $join) . " where t1.ID = '{$ID}' and t2.ID != '{$ID}'";
//				echo $name . ":" . $query . "\n";
				if ($result = DB::query($query)) {
					while ($item = DB::fetch($result)) {
						$nodes[$item->ID] = $name;
					}
				}
			}
		}

		$query = "select ID2 from {$this->TABLE_REF} where ID1 = '{$ID}'";
//		echo "REF:" . $query . "\n";
		if ($result = DB::query($query)) {
			while ($item = DB::fetch($result)) {
				$nodes[$item->ID2] = $row->REMOTE_TABLE;
			}
		}

		if ($nodes) {
			ksort($nodes);
			foreach ($nodes as $node => $corel) $this->findNodes($node, $corel, $path);
		}
//		print_r($nodes);
	}
}

$TABLE = "BI_audit_ALL";
$TABLE_REF = "BI_audit_ALL_ref";
$TABLE_DEST = ["BI_audit_ENERGA_RUM_KONTRAHENCI", "BI_audit_KW_requested"];

$query = "select ID from {$TABLE} where REMOTE_TABLE = 'BI_audit_ENERGA_PRACOWNICY'";// and ID not in (5131123, 5131126, 5131129, 5131131, 5131132, 5131133, 5131134, 5131135)";
$result = DB::query($query);
$results = [];
while ($row = DB::fetch($result)) {
//	echo $row->ID . "\n";
	$test = new FindCorelations($TABLE, $TABLE_REF, $TABLE_DEST, 5, $row->ID);
	if ($test->results) {
		$results = array_merge($results, $test->results);
//		echo "\n==========\nGOT IT!\n";
//		print_r($test->results);
//		echo "==========\n";
	}
}
//echo "\n\n============ RESULTS =======================\n";

$items_results = [];
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));
		$item_result = [$row['REMOTE_TABLE'] => (array) $obj];
		if ($rel) $item_result['relation_from'] = $rel;
		$item_results[] = $item_result;
		if ($row['REMOTE_TABLE'] == "BI_audit_ENERGA_RUM_KONTRAHENCI") {
			$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);
			$umowy = [];
			while ($obj = DB::fetch($res)) {
				$umowy[] = (array) $obj;
			}
			if ($umowy) {
				$item_results['umowy'] = $umowy;
			}
		}
	}
	$items_results[] = $item_results;
}
print_r($items_results);
