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

$query = "select ID, NIP, REGON, KRS from BI_audit_ENERGA_RUM_KONTRAHENCI where (NIP is null or REGON is null or KRS is null) and not (NIP is null and REGON is null and KRS is null)";
$result = DB::query($query);
while ($row = DB::fetch($result)) {
	$query = "select nip, regon, krs from BI_audit_KRS where nip = '{$row->NIP}' or regon = '{$row->REGON}' or krs = '{$row->KRS}'";
	if ($items = DB::getPDO()->fetchAll($query)) {
		list($nip, $regon, $krs) = [$items[0]["nip"], $items[0]["regon"], $items[0]["krs"]];
		if (count($items) > 1) {
			for ($i = 1; $i < count($items); $i++) {
				if ($nip != $items[$i]["nip"]) $nip = null;
				if ($regon != $items[$i]["regon"]) $regon = null;
				if ($krs != $items[$i]["krs"]) $krs = null;
			}
		}
		if (!($nip || $regon || $krs)) {
			echo "ERROR!\n";
			echo $query . "\n";
		} else {
			$set = [];
			if ($nip && $nip != $row->NIP) $set[] = "NIP = '{$nip}'";
			if ($regon && $regon != $row->REGON) $set[] = "REGON = '{$regon}'";
			if ($krs && $krs != $row->KRS) $set[] = "KRS = '{$krs}'";
			if ($set) {
				$query = "update BI_audit_ENERGA_RUM_KONTRAHENCI set " . implode(', ', $set) . " where ID = '{$row->ID}'";
				DB::query($query);
				echo $query . "\n";
			}
		}
	}
}

$query = "select ID, NIP, REGON from BI_audit_ENERGA_RUM_KONTRAHENCI where (NIP is null or REGON is null) and not (NIP is null and REGON is null)";
$result = DB::query($query);
while ($row = DB::fetch($result)) {
	$query = "select nip, regon from BI_audit_CEIDG where nip = '{$row->NIP}' or regon = '{$row->REGON}'";
	if ($items = DB::getPDO()->fetchAll($query)) {
		list($nip, $regon) = [$items[0]["nip"], $items[0]["regon"]];
		if (count($items) > 1) {
			for ($i = 1; $i < count($items); $i++) {
				if ($nip != $items[$i]["nip"]) $nip = null;
				if ($regon != $items[$i]["regon"]) $regon = null;
			}
		}
		if (!($nip || $regon)) {
			echo "ERROR!\n";
			echo $query . "\n";
		} else {
			$set = [];
			if ($nip && $nip != $row->NIP) $set[] = "NIP = '{$nip}'";
			if ($regon && $regon != $row->REGON) $set[] = "REGON = '{$regon}'";
			if ($set) {
				$query = "update BI_audit_ENERGA_RUM_KONTRAHENCI set " . implode(', ', $set) . " where ID = '{$row->ID}'";
				DB::query($query);
				echo $query . "\n";
			}
		}
	}
}
