<?php

error_reporting(E_ALL & ~E_NOTICE);

define('DS', DIRECTORY_SEPARATOR);
define('APP_PATH_ROOT', dirname(__FILE__));
define('APP_PATH_WWW', dirname(__FILE__));
define('APP_PATH_CONFIG', APP_PATH_ROOT . DS . 'config');

//session_save_path("../session") ;
session_start();

date_default_timezone_set('Europe/Warsaw');// PHP 5 >= 5.1.0 required by date functions

if (file_exists(".config.php")) include(".config.php");

//SEF('DEBUG_S');
require_once dirname(__FILE__) . '/' . 'se-lib' . '/' . 'Lib.php';
Lib::loadClass('V');
Lib::loadClass('User');
Lib::loadClass('Config');
Lib::loadClass('App');
Lib::loadClass('DB');
Lib::loadClass('S');


echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n";
echo "<HTML><HEAD><meta http-equiv=\"content-type\" content=\"text/html; charset=iso-8859-2\"/>";
	echo '<script type="text/javascript" src="stuff/jquery.js"></script>';
	echo "\n".'<link rel="stylesheet" type="text/css" href="stuff/main.css" />'."\n";
echo '</head>';
echo '<body>';

Lib::loadClass('DB_Dump');

if (!User::logged()) {
	die("Require login!");
}

if (User::get('ADM_ADMIN_LEVEL') != 0) {
	die("Access denied!");
}

$conf = Config::getZasobConf('Xdb_structupdater');
if (!$conf) {
	die("Error config for 'Xdb_structupdater' not exists!");
}

$db_allowed = V::get('allowed_db', '', $conf);
if (empty($db_allowed)) {
	die("Error in config - no allowe db set!");
}
$db_allowed = explode(",", $db_allowed);

$tbl_prefix_allowed = V::get('allowed_tbl_prefix', '', $conf);
$tbl_prefix_allowed = (!empty($tbl_prefix_allowed))? explode(",", $tbl_prefix_allowed) : array('%');

$struct1_source = V::get('_s1', 'default', $_GET);
$struct2_source = V::get('_s2', '', $_GET);
$_tbl_prefix = V::get('_tbl_prefix', '', $_GET);
if (!in_array($struct1_source, $db_allowed)) $struct1_source = '';
if (!in_array($struct2_source, $db_allowed)) $struct2_source = '';

echo '<form action="" method="get">';
echo "Source 1: ";
echo '<select name="_s1">';
	echo '<option value="">' . " ... " . '</option>';
	foreach ($db_allowed as $db_name) {
		$sel = ($struct1_source == $db_name)? ' selected="selected"' : '';
		echo '<option value="' . $db_name . '"' . $sel . '>' . $db_name . '</option>';
	}
echo '</select>';
echo "Source 2: ";
echo '<select name="_s2">';
	echo '<option value="">' . " ... " . '</option>';
	foreach ($db_allowed as $db_name) {
		$sel = ($struct2_source == $db_name)? ' selected="selected"' : '';
		echo '<option value="' . $db_name . '"' . $sel . '>' . $db_name . '</option>';
	}
echo '</select>';
echo "Tbl prefix: ";
echo '<select name="_tbl_prefix">';
	echo '<option value="">' . " ... " . '</option>';
	foreach ($tbl_prefix_allowed as $tbl_prefix) {
		$sel = ($_tbl_prefix == $tbl_prefix)? ' selected="selected"' : '';
		echo '<option value="' . $tbl_prefix . '"' . $sel . '>' . $tbl_prefix . '</option>';
	}
echo '</select>';
echo " " . '<input type="submit" value="' . "Wyślij" . '" />';
echo '</form>';

if (empty($struct1_source) || empty($struct2_source) || empty($_tbl_prefix)) {
	die('<p>' . "Wybierz bazy danych i prefix tabel" . '</p>');
}

$db = DB::getDB($struct1_source);
if (!$db) {
	die("No db '" . $struct1_source . "'");
} else if ($db->has_errors()) {
	echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">'."Errors db '" . $struct1_source . "':\n";print_r($db->get_errors());echo'</pre>';
	return;
}
$db2 = DB::getDB($struct2_source);// main db - sowa
if (!$db2) {
	die("No db '" . $struct2_source . "'");
} else if ($db2->has_errors()) {
	echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">'."Errors db '" . $struct2_source . "':\n";print_r($db2->get_errors());echo'</pre>';
	return;
}

Lib::loadClass('DB_Util');
$tbl_name = 'CRM_LISTA_ZASOBOW';
$ret = DB_Util::get_table_struct($db, $tbl_name);
//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">ret: ';print_r($ret);echo'</pre>';
$ret = DB_Util::get_table_struct($db2, $tbl_name);
//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">ret2: ';print_r($ret);echo'</pre>';
$ret = DB_Util::compare_db_table($db, $db2, $tbl_name);
//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">ret3: ';print_r($ret);echo'</pre>';
if ($ret === null || !is_array($ret)) {
	echo 'diff null';
} else if (empty($ret)) {
	echo 'diff empty';
} else {
	$sqls = DB_Util::compare_db_table_to_sql($tbl_name, $ret);
	//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">sqls: ';print_r($sqls);echo'</pre>';
}
echo '<hr />';


$struct1 = DB_Dump::get_db_structure_by_table_prefix($db, $_tbl_prefix);
//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">$struct1: ';print_r($struct1);echo'</pre>';
if (!$struct1) {
	die("No struct for '" . $struct1_source . "'.");
}

$struct2 = DB_Dump::get_db_structure_by_table_prefix($db2, $_tbl_prefix);
//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">$struct2: ';print_r($struct2);echo'</pre>';
if (!$struct2) {
	die("No struct for '" . $struct2_source . "'.");
}
echo '<p>'."generating struct diff...".'</p>';

Lib::loadClass('DB_StructUpdater');


if (V::get('test', '', $_GET) == '123') {
	$file_struct1 = dirname(__FILE__) . '/../../sources/sowa.sql-bup-last/dump-diff-test.1.sql';
	$file_struct2 = dirname(__FILE__) . '/../../sources/sowa.sql-bup-last/dump-diff-test.2.sql';

	if (!file_exists($file_struct1)) {
		die("file struct1.sql not exists!");
	}
	if (!file_exists($file_struct2)) {
		die("file struct2.sql not exists!");
	}
	$struct1 = file_get_contents($file_struct1);
	$struct2 = file_get_contents($file_struct2);
}


echo '<table width="100%">';
echo '<tr>';
	echo '<td width="50%">';
		echo '<p style="margin:0;padding:10px 0 0 0;">'."struct1.sql (" . $struct1_source . ")".'</p>';
		echo '<textarea style="width:100%;height:300px;border:1px solid #333">';
			echo $struct1;
		echo '</textarea>';
	echo '</td>';
	echo '<td width="50%">';
		echo '<p style="margin:0;padding:10px 0 0 0;">'."struct2.sql (" . $struct2_source . ")".'</p>';
		echo '<textarea style="width:100%;height:300px;border:1px solid #333">';
			echo $struct2;
		echo '</textarea>';
	echo '</td>';
echo '</tr>';
echo '</table>';

$updater = new DB_StructUpdater();

$res = $updater->getUpdates($struct2, $struct1);
db_structupdater_print($res, "sync struct2 ($struct2_source) to struct1 ($struct1_source)");

$res = $updater->getUpdates($struct1, $struct2);
db_structupdater_print($res, "sync struct1 ($struct1_source) to struct2 ($struct2_source)");

?>
<style type="text/css">
.collapse {margin:0; padding:0;}
 .collapse dt {display:block; margin:0; padding:0 10px; cursor:pointer;}
 .collapse dd {display:block; margin:0; padding:0; overflow:auto;}
	.collapse dt em {color:#777; font-size:small;}
	.collapse dd .box {display:block; float:left; width:98px; height:120px; text-align:center; font-size:11px; color:#999;}
	.collapse dd .box img {clear:both; margin:0 0 3px 0;}
	.collapse dd .tbl-view {background:#fff;}
  .collapse dt .add-show,
  .collapse dt .add-hidden {font-size:normal; font-family:monospace; font-weight:bold;}
.collapse-row-0 dt {background:#BFBFBF; color:black;}
.collapse-row-0 dd {background:#BFBFBF; color:black; border:1px solid #BFBFBF;}
.collapse-row-1 dt {background:#E5E5E5; color:black;}
.collapse-row-1 dd {background:#E5E5E5; color:black; border:1px solid #E5E5E5;}
.collapse-hide dd {display:none;}
 .collapse dt .add-show {display:inline;}
 .collapse dt .add-hidden {display:none;}
 .collapse-hide dt .add-show {display:none;}
 .collapse-hide dt .add-hidden {display:inline;}
.collapse .tbl-view th,
.collapse .tbl-view td {font-size:small;}
</style>
<?php
?>
<script type="text/javascript">
jQuery(document).ready(function(){
	jQuery(".collapse dt").click(function(){
		jQuery(this).parent().toggleClass('collapse-hide');
		return false
	});
});
</script>
<?php

function db_structupdater_print($sql_arr, $title) {
	$total = count($sql_arr);
	echo '<p>' . $title . " (" . $total . ")" . '</p>';
	if ($total > 0) {
		$t = 0;
		foreach ($sql_arr as $line_nr => $line) {
			$sql_first_line = substr($line, 0, min(80, strpos($line . "\n", "\n")));
			echo '<dl class="collapse collapse-hide collapse-row-' . ($t = 1 - $t) . '">';
			echo '<dt>' . "-- " . $title . " (SQL " . ($line_nr + 1) . ")";
				echo '<span class="add-show">' . " (- ukryj)" . '</span>';
				echo '<span class="add-hidden">' . " (+ pokaż) " . '<em>' . $sql_first_line . " ..." . '</em>' . '</span>';
			echo '</dt>';
			echo '<dd>';
				$out_rows = min(10, count(explode("\n", $line)));
				echo '<textarea rows="'.$out_rows.'" style="margin:0 0 0 2%;width:97%;border:1px solid #333;background:#fff;">';
					echo $line;
				echo '</textarea>';
			echo '</dd>';
			echo '</dl>';// .collapse
		}
	}
}
