<?php


require_once dirname(__FILE__) . '/../../' . 'Lib.php';


Lib::loadClass( 'Core_Database' );


class Core_Database_Mysql extends Core_Database {

	function __construct($host, $user, $password, $database, $names = '', $params = array()) {
		parent::__construct($host, $user, $password, $database, $names, $params);

		$this->_conn = @mysql_pconnect($host, $user, $password);
		if (!is_resource($this->_conn)) {
			$this->_set_error('CREATE CONNECTION FAILED');
			return;
		}
		if (false === mysql_select_db($database, $this->_conn)) {
			$this->_set_error('SELECT DATABASE FAILED');
			return;
		}

		if ($names != '') {
			$this->query(" SET NAMES '$names' ");
		}
	}

	function getConnection() {
		return $this->_conn;
	}

	function getVersion($version) {
		if (!$this->_version) {
			$sql = "SHOW VARIABLES LIKE 'version';";
			$res = $this->query($sql);
			if ($r = $this->fetch($res)) {
				// [Variable_name] => version, [Value] => 4.0.26-log
				$this->_version = $r->Value;
			}
		}
		return $this->_version;
	}

	/**
	 * Wykonuje podane zapytanie i zwraca wynik mysql_query().
	 */
	function query( $query, $msg = 'Query ERROR.' ) {
		$null = null;
		if (!$this->_conn) { return $null; }
		$res = mysql_query($query, $this->_conn);
		if (!$res) {
			$this->_set_error('SQL QUERY FAILED: '.mysql_error($this->_conn));
			return $null;
		}
		return $res;
	}

	function fetch( $res ) {
		$ret = null;
		if ($res) $ret = mysql_fetch_object( $res );
		return $ret;
	}

	function fetch_row( $res ) {
		$ret = null;
		if ($res) $ret = mysql_fetch_row( $res );
		return $ret;
	}

	function fetch_assoc( $res ) {
		$ret = null;
		if ($res) $ret = mysql_fetch_assoc( $res );
		return $ret;
	}

	function fetch_array($res) {
		$ret = null;
		if ($res) $ret = mysql_fetch_array($res);
		return $ret;
	}

	function count( $res ) {
		return mysql_num_rows( $res );
	}

	function num_rows( $res ) {
		return mysql_num_rows( $res );
	}

	function insert_id() {
		return mysql_insert_id( $this->_conn );
	}
	function show_tables() {
		$sql="show tables";
		$res = $this->query($sql);
		return $res;
	}
	
	function describe_table($table) {
		$sql='SHOW FIELDS FROM `'.$table.'`';
		$res = $this->query($sql);
		return $res;
	}
	
	function STRUCTURE_GENERATE($TABLES,$null=null,$TABLES_STRUCTURE_DATA,$flags=array()){
   				DEBUG_S(-3,'flags',$flags,__FILE__,__FUNCTION__,__LINE__);
   				//global $this;
   				//! try to create info for functions and procedures -> ['__SCHEMA_FUNCTIONS__ARRAY__']
   				$sql="show function status where Db='".$this->getDatabaseName()."';";
   					DEBUG_S(-3,'sql function detail :: ',$sql_,__FILE__,__FUNCTION__,__LINE__)	 ;
   				$result=$this->query($sql) or die1('\nProblem z '.$sql);       				
   				while($h=mysql_fetch_object($result)) {	
   					$sql_="show create function `{$h->Name}`" ;
   					DEBUG_S(-3,'sql function detail :: ',$sql_,__FILE__,__FUNCTION__,__LINE__)	 ;
   					$result_=$this->query($sql_) or die1('\nProblem z '.$sql);       			
   					while($h_=mysql_fetch_object($result_)) {	
   					$TABLES_IMPORT['__SCHEMA_FUNCTIONS__ARRAY__']['FUNCTION'][$h->Name]=$h_;
   					}
	   			}
	   			
	   			
	   			$sql="show PROCEDURE status where Db='".$this->getDatabaseName()."';";
   			   	DEBUG_S(-3,'sql function detail :: ',$sql_,__FILE__,__FUNCTION__,__LINE__)	 ;
   				$result=$this->query($sql) or die1('\nProblem z '.$sql);       				
   				while($h=mysql_fetch_object($result)) {	
   					$sql_="show create PROCEDURE `{$h->Name}`" ;
   					DEBUG_S(-3,'sql PROCEDURE detail :: ',$sql_,__FILE__,__FUNCTION__,__LINE__)	 ;
   					$result_=$this->query($sql_) or die1('\nProblem z '.$sql);       			
   					while($h_=mysql_fetch_object($result_)) {	
   					$TABLES_IMPORT['__SCHEMA_FUNCTIONS__ARRAY__']['PROCEDURE'][$h->Name]=$h_;
   					}
	   			}
	   				DEBUG_S(-3,'struktury funkcji: __SCHEMA_FUNCTIONS__ARRAY__ ',$TABLES_IMPORT['__SCHEMA_FUNCTIONS__ARRAY__'],__FILE__,__FUNCTION__,__LINE__)	 ;
   				//die1('stop function during dev.');
   				
		       		foreach($TABLES as $TABLE ){
		       				
		       				$sql="show tables like   '".$TABLE."' ;" ;
		       				DEBUG_S(-3,'//! Listing possible tables to write to config',$sql,__FILE__,__FUNCTION__,__LINE__);
		       				$result=$this->query($sql) or die1('\nProblem z '.$sql);       				
		       				if(mysql_num_rows($result)==0) {
		       				// nie ma tabeli - trzeba zapisac
		       				DEBUG_S(-3," BRAK TABELI ".$TABLE,null,__FILE__,__FUNCTION__,__LINE__);
		       				//die1();
		       				if(isset($TABLES_IMPORT[$TABLE])) {
			       				DEBUG_S(-3," Table already imported - problem in twice declared table ".$TABLE,null,__FILE__,__FUNCTION__,__LINE__);	
			       				die1();
		       				}
		       				} else {
		       				
		       				
		       						$sql="show full tables like   '".$TABLE."' ;" ;
			   						$result=$this->query($sql) or die1('\nProblem z '.$sql);     
			   						while($h=mysql_fetch_object($result)) {		       				
				   						$TABLES_IMPORT[$TABLE]['Table_type']=$h->{'Table_type'};
				       					DEBUG_S(-3,'//! Reading to conf if table is WIEV or not :sql/result',array($sql,$h->{'Table_type'}),__FILE__,__FUNCTION__,__LINE__);
					   				}
		       				
					   				$FLAG_CONTABLE=false;
		       				
					   				if( ($TABLES_IMPORT[$TABLE]['Table_type']=='BASE TABLE')
					   					|| ( in_array('with_view', $flags) && $TABLES_IMPORT[$TABLE]['Table_type']=='VIEW' )
					   				) {
				       						$FLAG_CONTABLE=true;
						       				$sql=" describe  `".$TABLE."` ;" ;
						       				//echo "\n ".$sql;
				       				       	$result=$this->query($sql) or die1('\nProblem z '.$sql);
						       				while($h=mysql_fetch_object($result)) {		       				
						       					$TABLES_IMPORT[$TABLE]['FIELDS'][]=$h;
						       				}
						       			    $sql=" show index from  `".$TABLE."` ;" ;
				       				       	$result=$this->query($sql) or die1('\nProblem z '.$sql);
											$TMP_KEYNAME=array();
						       						while($h=mysql_fetch_object($result)) {		
							       						if(isset($h->Column_name)) { $h->Column_name="`".$h->Column_name."`";       				
														if(!isset($TMP_KEYNAME[$h->Key_name])) $TMP_KEYNAME[$h->Key_name]=$h->Column_name;
														else $TMP_KEYNAME[$h->Key_name].=",".$h->Column_name;
														}
														//if(isset($TABLES_IMPORT[$TABLE]['INDEX'][$h->Key_name])) {
														//   $TABLES_IMPORT[$TABLE]['INDEX'][$h->Key_name]->Column_name.=", ".$h->Column_name." ";
														//} else {
														//}
														$TABLES_IMPORT[$TABLE]['INDEX'][$h->Key_name]=$h;
														$TABLES_IMPORT[$TABLE]['INDEX'][$h->Key_name]->Column_name=$TMP_KEYNAME[$h->Key_name];	
													}
						       				if(in_array($TABLE,$TABLES_STRUCTURE_DATA)) { //bedziemy dodawac dane tej tabeli
						       					 $sql=" select  * from  `".$TABLE."` ;" ;
				       				       		 $result=$this->query($sql) or die1('\nProblem z '.$sql);
				       				       		 while($h=mysql_fetch_object($result)) {
						       					 	$TABLES_IMPORT[$TABLE]['VALUES'][]=$h;
						       					 }
						       				}
				
						       				DEBUG_S(-3,"Dane tabeli KOMORKI ".$TABLE." ",$TABLES_IMPORT[$TABLE]['FIELDS'],__FILE__, __FUNCTION__, __LINE__);
						       				DEBUG_S(-3,"Dane tabeli INDEKSY ".$TABLE." ",$TABLES_IMPORT[$TABLE]['INDEX'],__FILE__, __FUNCTION__, __LINE__);
						       				if(isset($TABLES_IMPORT[$TABLE]['VALUES'])) DEBUG_S(-3,"Dane tabeli VALUES ".$TABLE." ",$TABLES_IMPORT[$TABLE]['VALUES'],__FILE__, __FUNCTION__, __LINE__);
							   				
							   				//! reading triggers to conf -> $TABLES_IMPORT[$TABLE]['TRIGGERS']
							   			    $sql=" show triggers like '".$TABLE."' ;" ;
				       				       	$result=$this->query($sql) or die1('\nProblem z '.$sql);
						       				while($h=mysql_fetch_object($result)) {		
						       					 $sql_="show create trigger {$h->Trigger} ;" ;
							   					 echo $sql_;
		    		       				         $result_=$this->query($sql_) or die1('\nProblem z '.$sql_);	
		    		       				         while($h_=mysql_fetch_object($result_)) {			       					 
							   					  DEBUG_S(-3,"Dane tabeli h_ ".$TABLE." ",$h_,__FILE__, __FUNCTION__, __LINE__);
						       					  $TABLES_IMPORT[$TABLE]['TRIGGERS'][$h->Trigger]=$h_; 
						       					 }
								   			}
								   			if(isset($TABLES_IMPORT[$TABLE]['TRIGGERS'])) DEBUG_S(-3,"Dane tabeli TRIGGERS ".$TABLE." ",$TABLES_IMPORT[$TABLE]['TRIGGERS'],__FILE__, __FUNCTION__, __LINE__);
		
						       			} 
						       			if(($TABLES_IMPORT[$TABLE]['Table_type']=='VIEW')) {
								   			 $FLAG_CONTABLE=true;
							       			 $sql_="show create view `{$TABLE}` ;" ;
							   					 //echo $sql_;
		    		       				         $result_=$this->query($sql_) or die1('\nProblem z '.$sql_);	
		    		       				         while($h_=mysql_fetch_object($result_)) {			       					 
							   					  DEBUG_S(-3,"//! trying to fetch create view fom".$TABLE." sql/res",array($sql_,$h_),__FILE__, __FUNCTION__, __LINE__);
						       					  $TABLES_IMPORT[$TABLE]['VIEW']=$h_; 
						       					 }
							       			
						       			} if(!$FLAG_CONTABLE) { 
						       			  DEBUG_S(-3,"Unknown table type ! ".$TABLE." ".$TABLES_IMPORT[$TABLE]['Table_type'],$TABLES_IMPORT[$TABLE],__FILE__, __FUNCTION__, __LINE__);
						       			  die1();
						       			}
				       			    	
						   			}
		            }
		            //print_r($TABLES_IMPORT);
		           
		           
		           
		            function func_sort_tables_import($a,$b){
		               if($a['Table_type']==$b['Table_type']) return 0;
		               else if($a['Table_type']=='VIEW') return 1;
		               else return -1;
                            }
                           
                           uasort($TABLES_IMPORT,'func_sort_tables_import');
		                                                                                                                                                         
		           DEBUG_S(-3,'Wygenerowane struktury (TABLES_IMPORT)',$TABLES_IMPORT,__FILE__,__FUNCTION__,__LINE__); 
		           return($TABLES_IMPORT);
         	}
	
	
	
	function SHOW_TABLE_STATUS_LIKE($table) {
		$records=$this->query("SHOW TABLE STATUS LIKE '".$table."'");
		if ($record = $this->fetch_assoc($records)) {
//		DEBUG_S(-3,'SHOW_TABLE_STATUS_LIKE',$record,__FILE__,__FUNCTION__,__LINE__);
		return $record;
		}
		
	}
	
	function affected_rows() {
		return mysql_affected_rows( $this->_conn );
	}

	function _( $str ) {
		return mysql_real_escape_string( $str, $this->_conn );
	}

	function error() {
		return "#".mysql_errno($this->_conn).": ".mysql_error($this->_conn);
	}

	function get_by_id( $table, $id ) {
		$null = null;
		$sql = "select p.*
			from `".$table."` as p
			where p.`ID`='".$id."'
		";
		$res = $this->query( $sql );
		if ($r = $this->fetch( $res )) {
			return $r;
		}
		return $null;
	}

	/**
	 * @returns int
	 *   1 - changed but without add hist
	 *   2 - changed and add hist
	 *   0 - nothing to change
	 *   -1 - sql errors
	 *   -2 - error id not exists in DB
	 *   -3 - error ID not set
	 * 
	 * TODO: sprawdzac czy w hist mozna odczytac aktualny stan, jesli nie to dodac caly rekord do HIST, jako 'procesy-fix-hist-data'
	 */
	public function UPDATE_OBJ($table, $sql_obj) {
		if (!isset($sql_obj->ID) || $sql_obj->ID <= 0) {
			return -3;
		}
		$id = $sql_obj->ID;

		// check id record $id exists
		if (($curr_obj = $this->get_by_id( $table, $sql_obj->ID )) == null) {
			return -2;
		}

		// check if enything changed
		$changed = false;
		$fields_to_change = get_object_vars($sql_obj);
		foreach ($fields_to_change as $k => $v) {
			if ($k == 'ID') continue;
			if ($v == $curr_obj->$k) {// === ?
				unset($sql_obj->$k);
			} else {
				$changed = true;
			}
		}
		if ($changed == false) {
			return 0;// record not changed
		}

		$sql_arr = array();
		// TODO: add admin columns if exists in table - search in session
		$admin_col = array();
		$admin_col []= 'A_RECORD_CREATE_DATE';
		$admin_col []= 'A_RECORD_CREATE_AUTHOR';
		// ...
		$sql_obj->A_RECORD_UPDATE_DATE = date('Y-m-d-H:i');
		$sql_obj->A_RECORD_UPDATE_AUTHOR = User::getName();
		foreach (get_object_vars($sql_obj) as $k => $v) {
			if (strtoupper($v) == 'NOW()') {
				$v = 'NOW()';
			} else if (strtoupper($v) == 'NULL') {
				$v = 'NULL';
			} else if (substr($v, 0, strlen('GeomFromText')) == 'GeomFromText') {
				
			} else {
				$v = $this->_($v);
				$v = "'{$v}'";
			}
			$sql_arr [] = "`{$k}`={$v}";
		}
		$sql = "update `{$table}` set ".implode(",", $sql_arr)." where `ID`='{$id}' limit 1; ";
		$this->query($sql);

		if ($this->has_errors()) {
			return -1;
		}

		$ret = $this->affected_rows();
		if ($ret) {
			$sql_obj->ID_USERS2 = $sql_obj->ID;
			unset($sql_obj->ID);
			$new_id = $this->ADD_NEW_OBJ("{$table}_HIST", $sql_obj);
			if ($new_id) {
				$ret += 1;
			}
		}
		return $ret;
	}

	function ADD_NEW_OBJ( $table, $sql_obj ) {
		$sql_arr = array();
		// TODO: add admin columns if exists in table - search in session
		$admin_col = array();
		$admin_col []= 'ID';
		$admin_col []= 'A_RECORD_CREATE_DATE';
		$admin_col []= 'A_RECORD_CREATE_AUTHOR';
		$admin_col []= 'A_RECORD_UPDATE_DATE';
		$admin_col []= 'A_RECORD_UPDATE_AUTHOR';
		// ...
		$sql_arr["`ID`"] = "NULL";// add default value for ID, NULL in all inserts
		if (substr($table, 0, -5) == '_HIST') {
			$sql_obj->A_RECORD_UPDATE_DATE = date('Y-m-d-H:i');
			$sql_obj->A_RECORD_UPDATE_AUTHOR = User::getName();
		} else {
			$sql_obj->A_RECORD_CREATE_DATE = date('Y-m-d-H:i');
			$sql_obj->A_RECORD_CREATE_AUTHOR = User::getName();
		}

		foreach (get_object_vars($sql_obj) as $k => $v) {
			if (strtoupper($v) == 'NOW()') {
				$v = 'NOW()';
			} else if (strtoupper($v) == 'NULL' && substr($table, -5) != '_HIST') {
				$v = 'NULL';
			} else {
				$v = $this->_($v);
				$v = "'{$v}'";
			}
			$sql_arr ["`{$k}`"] = $v;
		}
		$sql = "insert into `{$table}` (".implode(",", array_keys($sql_arr)).") values (".implode(",", array_values($sql_arr))."); ";
		$this->query($sql);

		if ($this->has_errors()) {
			//echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">db errors: (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this->get_errors());echo'</pre>';
		}

		$ret_id = $this->insert_id();
		if (substr($table, -5) == '_HIST') {
			return $ret_id;
		}
		if ($ret_id) {
			$sql_obj->ID_USERS2 = $ret_id;
			unset($sql_obj->ID);
			$new_id_hist = $this->ADD_NEW_OBJ($table . '_HIST', $sql_obj);
			// error jesli nie udalo sie dodac rekordu do tabeli _HIST
		}
		return $ret_id;
	}

	function add_index($tbl,$column) {
		$sql="alter table `".$tbl."` add index(`".$column."`) ; ";
		self::query($sql);
		
	}

	function STRUCTURE_GENERATE_PARSE($config_base_structure_unserialized) {

					foreach($config_base_structure_unserialized as $TABLE=>$ARR_TABLE) { //dla kazdej tabeli 
					set_time_limit(36000);
					//! if($TABLE<>'_CRM_PROCES_USER_STATS_wiev') continue; //trigger development
					//! try to sync __SCHEMA_FUNCTIONS__ARRAY__
					if($TABLE=='__SCHEMA_FUNCTIONS__ARRAY__') {	
						DEBUG_S(-3,'Try to synchronize functions and procedures',$ARR_TABLE,__FILE__,__FUNCTION__,__LINE__);

													//BEGIN PROCEDURE
													$sql=" SHOW PROCEDURE STATUS; ;" ; //listujemy nasze procedury
									       			DEBUG_S(-3,'Looking for PROCEDURE ',$sql,__FILE__,__FUNCTION__,__LINE__);
									       				$result=$this->query($sql) or die1('\nProblem z '.$sql);
								       			   	     while($h=mysql_fetch_object($result)) {		       				
		 								   			     if($h->Db<>$this->getDatabaseName()) continue;

								       				     set_time_limit(36000);       				
	 							       					 $sql_="show create PROCEDURE {$h->Name} ;" ;
	 								   					 //echo $sql_;
	 								   					 $result_=$this->query($sql_) or die1('\nProblem z '.$sql_);	
	 								   					 	while($h_=mysql_fetch_object($result_)) {			       					 
		 								   					 $FIELDS_CHECKED['FOUNDS'][$h->Name]=$h_;
	 							       					     
	 							       					     if(!isset($ARR_TABLE['PROCEDURE'][$h->Name])) {
	 							       					       DEBUG_S(-3,'We have some more functions - we will not delete them:'.$h->Name,null,__FILE__,__FUNCTION__,__LINE__);
	 							       					       //$FIELDS_CHECKED['TO_DELETE'][$h->Name]=$h_;
	 							       					       }
		 								   					 }
	 							       					   
								       				    }
									       				DEBUG_S(-3,'Try to unserialize PROCEDURE and install to db:',$ARR_TABLE['PROCEDURE'],__FILE__,__FUNCTION__,__LINE__);
								       				
								       				foreach($ARR_TABLE['PROCEDURE'] as $TRIGGER_INDEX=>$TRIGGER_OBJECT) {
										   				if(!isset($FIELDS_CHECKED['FOUNDS'][$TRIGGER_INDEX])) { $FIELDS_CHECKED['TO_CREATE'][$TRIGGER_INDEX]=$TRIGGER_OBJECT;
										   				DEBUG_S(-3,'We have object to create '.$TRIGGER_INDEX,$TRIGGER_OBJECT,__FILE__,__FUNCTION__,__LINE__);
										   				}
								       				}


									   				//staramy sie zaktualizowac stare triggery, pod warunkiem, ze sie roznia
								       				foreach($FIELDS_CHECKED['FOUNDS'] as $TRIGGER_INDEX=>$TRIGGER_OBJECT) {
									       				DEBUG_S(-3,'OBJ/OBJ for '.$TRIGGER_INDEX,array($TRIGGER_OBJECT->{'Create Procedure'},$ARR_TABLE['PROCEDURE'][$TRIGGER_INDEX]->{'Create Procedure'}),__FILE__, __FUNCTION__, __LINE__);
									       				if(isset($ARR_TABLE['PROCEDURE'][$TRIGGER_INDEX])) //we first try to find if this trigger exists or delete it
									       				if($TRIGGER_OBJECT->{'Create Procedure'}<>$ARR_TABLE['PROCEDURE'][$TRIGGER_INDEX]->{'Create Procedure'} )  { 
									       					DEBUG_S(-3,"Data are different ({$TRIGGER_INDEX}). We add object to be created as new.",__FILE__, __FUNCTION__, __LINE__);
										   					$FIELDS_CHECKED['TO_CREATE'][$TRIGGER_INDEX]=$ARR_TABLE['PROCEDURE'][$TRIGGER_INDEX];
										   					$FIELDS_CHECKED['TO_DELETE'][$TRIGGER_INDEX]=true;

										   				}
								       				}
								       				
								       				
								       				if(isset($FIELDS_CHECKED['TO_DELETE']))  {
								       					DEBUG_S(-3,'We have some data to delete',$FIELDS_CHECKED['TO_DELETE'],__FILE__,__FUNCTION__,__LINE__);
									   					foreach($FIELDS_CHECKED['TO_DELETE'] as $TRIGGER_INDEX=>$TRIGGER_OBJECT ) {
										   					$sql="DROP PROCEDURE IF EXISTS `{$TRIGGER_INDEX}`; ";
										   				    DEBUG_S(-3,' sql to delete  '.$TRIGGER_INDEX,$sql,__FILE__,__FUNCTION__,__LINE__);
										   				    	$result=$this->query($sql) or DEBUG_S(-3,'Problem ze SQL:',$sql,__FILE__, __FUNCTION__, __LINE__)  or die1(); 

									   					}
								       				}
								       				
								       				
								       				//tworzymy brakujace procedury
								       				foreach ($FIELDS_CHECKED['TO_CREATE'] as $TRIGGER_INDEX=>$TRIGGER_OBJECT) {
									       				$sql=$TRIGGER_OBJECT->{'Create Procedure'};
									       				DEBUG_S(-3,'Try to add new  '.$TRIGGER_INDEX,$sql,__FILE__,__FUNCTION__,__LINE__);
									       					$result=$this->query($sql) or DEBUG_S(-3,'Problem ze SQL:',$sql,__FILE__, __FUNCTION__, __LINE__)  or die1(); 
									       				
								       				}
									   				unset($FIELDS_CHECKED);
									   				//EOF PROCEDURE
									   				
									   				
									   				//BEGIN FUNCTION
													$sql=" SHOW FUNCTION STATUS ;" ; //listujemy nasze procedury
									       			DEBUG_S(-3,'Looking for FUNCTION ',$sql,__FILE__,__FUNCTION__,__LINE__);
									       				$result=$this->query($sql) or die1('\nProblem z '.$sql);
								       			   	     while($h=mysql_fetch_object($result)) {		       				
								       				     set_time_limit(36000);       				
	 							       					 $sql_="show create FUNCTION {$h->Name} ;" ;
	 								   					 //echo $sql_;
	 								   					 $result_=$this->query($sql_) or die1('\nProblem z '.$sql_);	
	 								   					 	while($h_=mysql_fetch_object($result_)) {			       					 
		 								   					 $FIELDS_CHECKED['FOUNDS'][$h->Name]=$h_;
	 							       					       if(!isset($ARR_TABLE['FUNCTION'][$h->Name])) {
	 							       					          DEBUG_S(-3,'We have some more functions - we will not delete them:'.$h->Name,null,__FILE__,__FUNCTION__,__LINE__);
	 							       					         // $FIELDS_CHECKED['TO_DELETE'][$h->Name]=$h_;
	 							       					       }
		 								   					 }
	 							       					   
								       				    }
									       				DEBUG_S(-3,'Try to unserialize FUNCTION and install to db:',$ARR_TABLE['FUNCTION'],__FILE__,__FUNCTION__,__LINE__);
								       				
								       				foreach($ARR_TABLE['FUNCTION'] as $TRIGGER_INDEX=>$TRIGGER_OBJECT) {
										   				if(!isset($FIELDS_CHECKED['FOUNDS'][$TRIGGER_INDEX])) { $FIELDS_CHECKED['TO_CREATE'][$TRIGGER_INDEX]=$TRIGGER_OBJECT;
										   				DEBUG_S(-3,'We have object to create '.$TRIGGER_INDEX,$TRIGGER_OBJECT,__FILE__,__FUNCTION__,__LINE__);
										   				}
								       				}


									   				//staramy sie zaktualizowac stare triggery, pod warunkiem, ze sie roznia
								       				foreach($FIELDS_CHECKED['FOUNDS'] as $TRIGGER_INDEX=>$TRIGGER_OBJECT) {
									       				DEBUG_S(-3,'OBJ/OBJ for '.$TRIGGER_INDEX,array($TRIGGER_OBJECT->{'Create Function'},$ARR_TABLE['FUNCTION'][$TRIGGER_INDEX]->{'Create Function'}),__FILE__, __FUNCTION__, __LINE__);
									       				if(isset($ARR_TABLE['FUNCTION'][$TRIGGER_INDEX])) //we first try to find if this trigger exists or delete it
									       				if($TRIGGER_OBJECT->{'Create Function'}<>$ARR_TABLE['FUNCTION'][$TRIGGER_INDEX]->{'Create Function'} )  { 
									       					DEBUG_S(-3,"Data are different ({$TRIGGER_INDEX}). We add object to be created as new.",__FILE__, __FUNCTION__, __LINE__);
										   					$FIELDS_CHECKED['TO_CREATE'][$TRIGGER_INDEX]=$ARR_TABLE['FUNCTION'][$TRIGGER_INDEX];
										   					$FIELDS_CHECKED['TO_DELETE'][$TRIGGER_INDEX]=true;

										   				}
								       				}
								       				
								       				
								       				if(isset($FIELDS_CHECKED['TO_DELETE']))  {
								       					DEBUG_S(-3,'We have some data to delete',$FIELDS_CHECKED['TO_DELETE'],__FILE__,__FUNCTION__,__LINE__);
									   					foreach($FIELDS_CHECKED['TO_DELETE'] as $TRIGGER_INDEX=>$TRIGGER_OBJECT ) {
										   					$sql="DROP FUNCTION IF EXISTS `{$TRIGGER_INDEX}`; ";
										   				    DEBUG_S(-3,' sql to delete  '.$TRIGGER_INDEX,$sql,__FILE__,__FUNCTION__,__LINE__);
										   				    	$result=$this->query($sql) or DEBUG_S(-3,'Problem ze SQL:',$sql,__FILE__, __FUNCTION__, __LINE__)  or die1(); 

									   					}
								       				}
								       				
								       				
								       				//tworzymy brakujace procedury
								       				foreach ($FIELDS_CHECKED['TO_CREATE'] as $TRIGGER_INDEX=>$TRIGGER_OBJECT) {
									       				$sql=$TRIGGER_OBJECT->{'Create Function'};
									       				DEBUG_S(-3,'Try to add new  '.$TRIGGER_INDEX,$sql,__FILE__,__FUNCTION__,__LINE__);
									       					$result=$this->query($sql) or DEBUG_S(-3,'Problem ze SQL:',$sql,__FILE__, __FUNCTION__, __LINE__)  or die1(); 
									       				
								       				}
									   				unset($FIELDS_CHECKED);
									   				//EOF FUNCTION
									   				
									   				//die1('app in devel');




						 continue; //no go to another table in loop
					} //eof 
					
						//! detect if src table is TABLE or VIEW
					  
					//	foreach($TABLES as $TABLE ){
       										$sql="show full tables like   '".$TABLE."' ;" ;

											DEBUG_S(-3,'SQL:'.$this->getDatabaseName(),$sql,__FILE__, __FUNCTION__, __LINE__) ;

       										$result=$this->query($sql) or die1('\nProblem z '.$sql);       				
       										while($h=mysql_fetch_object($result))  {
	       										$FIELDS_CHECKED['Table_type']=$h->{'Table_type'};
       										}
       										    			
       										    				
       										if(mysql_num_rows($result)==0) {
       										// nie ma tabeli - trzeba zapisac
		       									if($ARR_TABLE['Table_type']=='BASE TABLE') {
		       										//DEBUG_S(-3,"\n BRAK TABELI  dodajemy : ".$TABLE."!!!",null,__FILE__,__FUNCTION__,__LINE__);
		       									
		       										 $sql="create table ".$TABLE." ( ".$ARR_TABLE['FIELDS'][0]->Field." ".$ARR_TABLE['FIELDS'][0]->Type ; //  ID int(11) NOT NULL AUTO_INCREMENT,
														 if($ARR_TABLE['FIELDS'][0]->Null=='NO') $sql.=" not null "; else $sql.=" null ";
														 //if($ARR_TABLE['FIELDS'][0]->Extra=='auto_increment') $sql.=" AUTO_INCREMENT "; else $sql.="  ";
														$sql.=" )  DEFAULT CHARSET=latin2  ";
														 DEBUG_S(-3,"Brak tabeli: ".$TABLE." dodajemy sql:",$sql,__FILE__,__FUNCTION__,__LINE__) ;
														 $this->query($sql) or die1('\nProblem z CREATE '.$sql);
		
														 if($TABLE=='CRM_LISTA_ZASOBOW') {
														 		$sql=" alter table `".$TABLE."` AUTO_INCREMENT=1000 ";
														 		 $this->query($sql) or die1('\nProblem z AUTO INCREMENT '.$sql);
		
														 }
		       									} else if($ARR_TABLE['Table_type']=='VIEW') {
		       										$sql=$ARR_TABLE['VIEW']->{'Create View'};
			       									DEBUG_S(-3,"Brak widoku: ".$TABLE." dodajemy sql:",$sql,__FILE__,__FUNCTION__,__LINE__) ;
			       									 $this->query($sql) or die1('\nProblem ze '.$sql);
		       									}
		       										
       										
       										} else {
	       										//try to detect if types are the same
	       										if($ARR_TABLE['Table_type']<>$FIELDS_CHECKED['Table_type']) die1('Todo: ERROR  VIEW/TABLE different types ');
	       										if($ARR_TABLE['Table_type']=='VIEW') {
		       										if(isset($ARR_TABLE['VIEW'])) {
			       										
					       										
					       									$sql_="show create view `{$TABLE}` ;" ;
						   									echo $sql_;
						   									$result_=$this->query($sql_) or die1('\nProblem z '.$sql_);	
						   									while($h_=mysql_fetch_object($result_)) {			       					 
							   									DEBUG_S(-3,"//! get current view info ".$TABLE." sql/res",array($sql_,$h_),__FILE__, __FUNCTION__, __LINE__);
							   									$FIELDS_CHECKED['VIEW']=$h_; 
							   								}
							   								//ereg_replace(, , )
									   					    if(strtolower($FIELDS_CHECKED['VIEW']->{'Create View'})<>strtolower($ARR_TABLE['VIEW']->{'Create View'})) {
										   					    $sql="drop view `{$TABLE}`";
										   					     $this->query($sql) or die1('\nProblem ze '.$sql);
										   					    $sql_=$ARR_TABLE['VIEW']->{'Create View'};
										   					    DEBUG_S(-3,"//! Views are different for ".$TABLE." . Dropping old view and adding  new  (old/new/sql/sql):",array(strtolower($FIELDS_CHECKED['VIEW']->{'Create View'}),$ARR_TABLE['VIEW']->{'Create View'},$sql,$sql_,$h_),__FILE__, __FUNCTION__, __LINE__);
										   					     $this->query($sql_) or die1('\nProblem ze '.$sql_);

									   					    }
					       										
			       										
			       										
		       										}
		       										
		       										
	       										}
	       										
       										}
       										
       										//always create
       										if($ARR_TABLE['Table_type']=='BASE TABLE') {
       										set_time_limit(36000);
								       				$sql=" describe  `".$TABLE."` ;" ;
													DEBUG_S(-3,'SQL:describe '.$TABLE,$sql,__FILE__, __FUNCTION__, __LINE__) ;
       										       	$result=$this->query($sql) or die1('\nProblem z '.$sql);
       										       	$FIELDS_CHECKED=""; unset($FIELDS_CHECKED);
       										       	foreach($ARR_TABLE['FIELDS'] as $TSTIND=>$TST_VAL) { //tu robie tabelke do odhaczania z niej zmiennych
								       					$FIELDS_CHECKED['FIELD_IN_CONFIG_TO_BE_PASSED'][$TST_VAL->Field]=1;
								       					$FIELDS_CHECKED['FIELD_IN_CONFIG_THAT_EXISTS'][$TST_VAL->Field]=1;
								       				}
								       				DEBUG_S(-3,'FIELDS_CHECKED',$FIELDS_CHECKED,__FILE__, __FUNCTION__, __LINE__) ;
								       				$var_passed=false;
								       				while($h=mysql_fetch_object($result)) {		       				
								       					//tu sprawdzamy czy sa wszystkie kolumny i maja takie same typy
								       					$FIELDS_CHECKED['FIELD_FROM_DB'][$h->Field]=1;
								       						if(!isset($FIELDS_CHECKED['FIELD_IN_CONFIG_THAT_EXISTS'][$h->Field])) {
																DEBUG_S(-3,'Za duzo o komorke '.$h->Field,$FIELDS_CHECKED,__FILE__, __FUNCTION__, __LINE__) ;
																$FIELDS_CHECKED['FIELD_IN_CONFIG_THAT_NOT_EXISTS'][$h->Field]=1;
														 	}
								       					foreach($ARR_TABLE['FIELDS'] as $TSTIND=>$TST_VAL) { //tu sprawdzam czy kolumna jest i jaka
								       					 // echo "\n Tst ".$TST_VAL->Field." ==? ".$h->Field;
	
								       					  if($TST_VAL->Field==$h->Field) {
								       					  	 $FIELDS_CHECKED['FIELD_FOUND_IN_REMOTE_DB'][$h->Field]=1;
								       					  	 if(isset($FIELDS_CHECKED['FIELD_IN_CONFIG_TO_BE_PASSED'][$h->Field])) //jezeli byla komorka ramowa
																 unset($FIELDS_CHECKED['FIELD_IN_CONFIG_TO_BE_PASSED'][$h->Field]);
								       					  	 }
								       					}
														
								       					//$TABLES_IMPORT[$TABLE]['FIELDS']=$h;
								       					
								       					
								       					
								       				}
								       				
								       				if(!empty($FIELDS_CHECKED['FIELD_IN_CONFIG_TO_BE_PASSED'])) DEBUG_S(-3,'Brakuje komorek dla '.$TABLE." ",array($FIELDS_CHECKED['FIELD_IN_CONFIG_TO_BE_PASSED']),__FILE__, __FUNCTION__, __LINE__);													
													DEBUG_S(-3,'FIELDS_CHECKED',$FIELDS_CHECKED,__FILE__, __FUNCTION__, __LINE__) ;
								       				//dodajemy brakujace komorki
								       				if(count($FIELDS_CHECKED['FIELD_IN_CONFIG_TO_BE_PASSED'])>0) {
								       						foreach($FIELDS_CHECKED['FIELD_IN_CONFIG_TO_BE_PASSED'] as $FIELD_TO_ADD=>$VAL ){
								       					set_time_limit(36000);
								       								//echo "\n Trying to add column: ".$FIELD_TO_ADD;
								       										if(isset($INDEX_OF_CONFIG_TABLE)) unset($INDEX_OF_CONFIG_TABLE);
								       								foreach($ARR_TABLE['FIELDS'] as $TSTIND=>$TST_VAL) { //trzeba znalezc numer ID indeksu brakujacej komorki
								       										if($TST_VAL->Field==$FIELD_TO_ADD) $INDEX_OF_CONFIG_TABLE=$TSTIND;
								       								}
								       								
								       								// $sql="create table ".$TABLE." ( ".$ARR_TABLE['FIELDS'][0]->Field." ".$ARR_TABLE['FIELDS'][0]->Type ; //  ID int(11) NOT NULL AUTO_INCREMENT,
																 //if($ARR_TABLE['FIELDS'][0]->Extra=='auto_increment') $sql.=" AUTO_INCREMENT "; else $sql.="  ";
								       								$sql="alter table `".$TABLE."` add `".$FIELD_TO_ADD."` ".$ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Type." ";
								       								if(($ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Default)) {
								       								   if(($ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Default=='NULL')||($ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Default=='CURRENT_TIMESTAMP'))
								       									 $sql.=" DEFAULT ".$ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Default." ";//   (".$INDEX_OF_CONFIG_TABLE.")";
								       									else $sql.=" DEFAULT '".$ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Default."' ";//   (".$INDEX_OF_CONFIG_TABLE.")";
								       									 }
								       							    if($ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Null=='NO') $sql.=" not null "; else $sql.=" null ";
								       							    $sql.=" ;";
								       								echo "\n ".$sql;
								       								 $this->query($sql) or  DEBUG_S(-3,'Problem z sql',$sql,__FILE__, __FUNCTION__, __LINE__)  or die1();

								       								
								       						}
								       				} //eof dodajemy brakujace komorki
								       				
								       				
								       				//Sprawdzamy czy sa zgodne typy komorek...
								       				$sql=" describe  `".$TABLE."` ;" ;
								       				DEBUG_S(-3,'describe '.$TABLE,$sql,__FILE__, __FUNCTION__, __LINE__) ;
								       				$result=$this->query($sql) or die1('\nProblem z '.$sql);
								       				while($h=mysql_fetch_object($result)) {		       				
								       				set_time_limit(36000);       				
														$FIELDS_CHECKED['FIELD_FOUND_IN_REMOTE_DB_PROFILE'][$h->Field]=$h;

								       				}		
								       				DEBUG_S(-3,'FIELDS_CHECKED',$FIELDS_CHECKED,__FILE__, __FUNCTION__, __LINE__) ;

								       						foreach($FIELDS_CHECKED['FIELD_FOUND_IN_REMOTE_DB_PROFILE'] as $FIELD_TO_CHK=>$VAL) {
								       									if(isset($INDEX_OF_CONFIG_TABLE)) unset($INDEX_OF_CONFIG_TABLE);
								       								foreach($ARR_TABLE['FIELDS'] as $TSTIND=>$TST_VAL) { //trzeba znalezc numer ID indeksu brakujacej komorki
								       									if($TST_VAL->Field==$FIELD_TO_CHK) $INDEX_OF_CONFIG_TABLE=$TSTIND;
								       								}
								       								if(isset($FIELDS_CHECKED['FIELD_IN_CONFIG_THAT_NOT_EXISTS'][$FIELD_TO_CHK])) continue; //jezeli komorki nie ma i jest tylko lokalnie - ignorujemy!
								       								// to jakis glupi warunek ?
								       								if(!isset($INDEX_OF_CONFIG_TABLE)) die1('Nie znaleziono indeksu w konfiguracji dla '.$TABLE.' i komorki '.$FIELD_TO_CHK);
								       							//	echo "\nsprawdzamy wszystkie wlasciwosci dla db ".$TABLE." ".$FIELD_TO_CHK." col ".$INDEX_OF_CONFIG_TABLE;
																	$CHK_TYPES_ARS=array('Type','Null','Default');
																	$sql="";
																//	 echo "\n if ".$VAL->Type." =? ".$ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Type ;
																	if($VAL->Type!=$ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Type) {
																	 //!  aktualizujemy typy
																	 	  $sql=" alter table `".$TABLE."` CHANGE `".$FIELD_TO_CHK."` `".$FIELD_TO_CHK."` ".$ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Type." ; ";

																	      if(strstr($ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Type, 'char(')&& strstr($VAL->Type, 'char(')){
																		      $src_char_len=ereg_replace('[^0-9]', '',$ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Type ); 
																		      $dst_char_len=ereg_replace('[^0-9]', '',$VAL->Type );

																		      if($src_char_len>$dst_char_len) {  
																		      	  DEBUG_S(-3,'Aktualizacja rozszerzajaca zakres pola CHAR : CUR_CHAR_LEN ='.$src_char_len." and dest=".$dst_char_len ,$sql,__FILE__, __FUNCTION__, __LINE__);
																				  	$result=$this->query($sql) or DEBUG_S(-3,'Problem ze SQL:',$sql,__FILE__, __FUNCTION__, __LINE__)  or die1('\nProblem z '.$sql);

																		      } else {
																			         DEBUG_S(-3,'celowe pominiecie - aktualizacja moze skasowac dane w bazie!!! :',$sql,__FILE__, __FUNCTION__, __LINE__);
																					// die1();  
																		      }
																	      } else if(strstr($VAL->Type, 'enum(') && strstr($ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Type, 'enum('  )) { //jezeli zmienia sie ENUM na inne ENUM
																	      
																		  	  preg_match('/^enum\((.*)\)$/', $ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Type, $src_char_len);
																			  preg_match('/^enum\((.*)\)$/', $VAL->Type, $dst_char_len);
																			  
																			  $src_char_len=explode(',', $src_char_len[1]);$dst_char_len=explode(',', $dst_char_len[1]);
																			  foreach($src_char_len as $var) {
																				  if( !in_array($var, $dst_char_len)) $dst_char_len[]=$var;
																				  
																			  } 
																			  $dst_char_len="enum(".implode(",", $dst_char_len).")";
 																	 	      $sql=" alter table `".$TABLE."` CHANGE `".$FIELD_TO_CHK."` `".$FIELD_TO_CHK."` ".$dst_char_len." ; ";

																	          DEBUG_S(-3,'Uzupelniamy strukture o ewentualnie brakujace elementy (sql,wynik polaczenia,import.strukt.,akt_strukt.)',array($sql,$dst_char_len,$ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Type,$VAL->Type),__FILE__, __FUNCTION__, __LINE__);
																		   	  
																		   	  	$result=$this->query($sql) or DEBUG_S(-3,'Problem ze SQL:',$sql,__FILE__, __FUNCTION__, __LINE__)  or die1('\nProblem z '.$sql);
																	      
																	      } else if(strstr($VAL->Type, 'set(') && strstr($ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Type, 'set('  )) { //jezeli zmienia sie ENUM na inne ENUM
																	      
																		  	  preg_match('/^set\((.*)\)$/', $ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Type, $src_char_len);
																			  preg_match('/^set\((.*)\)$/', $VAL->Type, $dst_char_len);
																			  
																			  $src_char_len=explode(',', $src_char_len[1]);$dst_char_len=explode(',', $dst_char_len[1]);
																			  foreach($src_char_len as $var) {
																				  if( !in_array($var, $dst_char_len)) $dst_char_len[]=$var;
																				  
																			  } 
																			  $dst_char_len="set(".implode(",", $dst_char_len).")";
 																	 	      $sql=" alter table `".$TABLE."` CHANGE `".$FIELD_TO_CHK."` `".$FIELD_TO_CHK."` ".$dst_char_len." ; ";

																	          DEBUG_S(-3,'Uzupelniamy strukture o ewentualnie brakujace elementy (sql,wynik polaczenia,import.strukt.,akt_strukt.)',array($sql,$dst_char_len,$ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Type,$VAL->Type),__FILE__, __FUNCTION__, __LINE__);
																		   	  	$result=$this->query($sql) or DEBUG_S(-3,'Problem ze SQL:',$sql,__FILE__, __FUNCTION__, __LINE__)  or die1('\nProblem z '.$sql);
																	      
																	      } else if(strstr($VAL->Type, 'int(') && strstr($ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Type, 'int('  )) {
																	          preg_match('/^int\((.*)\)$/', $ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Type, $src_char_len);
																			  preg_match('/^int\((.*)\)$/', $VAL->Type, $dst_char_len);
																			  if($src_char_len[1]>$dst_char_len[1]) {
																			      $sql=" alter table `".$TABLE."` CHANGE `".$FIELD_TO_CHK."` `".$FIELD_TO_CHK."` ".$ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Type." ; ";
																				  DEBUG_S(-3,'Aktualizacja rozszerzajaca zakres pola INT ma byc ='.$src_char_len[1]." byla dest=".$dst_char_len[1] ,$sql,__FILE__, __FUNCTION__, __LINE__);
																				 // 	$result=$this->query($sql) or DEBUG_S(-3,'Problem ze SQL:',$sql,__FILE__, __FUNCTION__, __LINE__)  or die1('\nProblem z '.$sql);
																			  } else {
																				  DEBUG_S(-3,'Pominieta Aktualizacja zawiezajaca zakres pola INT ma byc ='.$src_char_len[1]." byla dest=".$dst_char_len[1] ,$sql,__FILE__, __FUNCTION__, __LINE__);
																			  }
																	      
																	      } else if( ( strstr($VAL->Type, 'char(') || strstr($VAL->Type, 'varchar(')  ) && strstr($ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Type, 'text'  )
																	      			|| ( strstr($VAL->Type, 'bigint(')  ) && strstr($ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Type, 'longblob'  )
																	      			|| ( strstr($VAL->Type, 'mediumtext')  ) && strstr($ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Type, 'longblob'  )
																	      			|| ( strstr($VAL->Type, 'decimal(42')  ) && strstr($ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Type, 'decimal(41'  )
																	      			|| ( strstr($VAL->Type, 'decimal(43')  ) && strstr($ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Type, 'decimal(41'  )

																	      			) {
																	          
																			      $sql=" alter table `".$TABLE."` CHANGE `".$FIELD_TO_CHK."` `".$FIELD_TO_CHK."` ".$ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Type." ; ";
																				  DEBUG_S(-3,'Aktualizacja rozszerzajaca zakres pola varchar/char() do text()',$sql,__FILE__, __FUNCTION__, __LINE__);
																				  	$result=$this->query($sql) or DEBUG_S(-3,'Problem ze SQL:',$sql,__FILE__, __FUNCTION__, __LINE__)  or die1('\nProblem z '.$sql);
																				 // DEBUG_S(-3,'Pominieta Aktualizacja zawiezajaca zakres pola INT ma byc ='.$src_char_len[1]." byla dest=".$dst_char_len[1] ,$sql,__FILE__, __FUNCTION__, __LINE__);
																			  
																	      
																	      } else {
																		  	  DEBUG_S(-3,'Celowe zabicie z uwagi na niebezpieczenstwo zmiany typu: sql/old/new',array($sql,$VAL->Type,$ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Type),__FILE__, __FUNCTION__, __LINE__);
																		  	  die1();
																		   	  	$result=$this->query($sql) or DEBUG_S(-3,'Problem ze SQL:',$sql,__FILE__, __FUNCTION__, __LINE__)  or die1('\nProblem z '.$sql);
																		    }
																	    }
																	if($VAL->Null!=$ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Null) 
																	  	if($ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Null=='YES') { 
																		  $sql=" alter table `".$TABLE."` CHANGE `".$FIELD_TO_CHK."` `".$FIELD_TO_CHK."` ".$ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Type." NULL ; ";
																		    	$result=$this->query($sql) or DEBUG_S(-3,'Problem ze SQL ',$sql,__FILE__, __FUNCTION__, __LINE__) or DIE();
																		  } else  { 
																	     	$sql=" alter table `".$TABLE."` CHANGE `".$FIELD_TO_CHK."` `".$FIELD_TO_CHK."` ".$ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Type." NOT NULL ; ";
																	     		$result=$this->query($sql) or DEBUG_S(-3,'Problem ze SQL ',$sql,__FILE__, __FUNCTION__, __LINE__) or DIE();

																	       }
																	if($VAL->Default!=$ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Default) {
																		if($ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Default=='CURRENT_TIMESTAMP')
												 						 $sql=" alter table `".$TABLE."` CHANGE `".$FIELD_TO_CHK."` `".$FIELD_TO_CHK."`  ".$ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Type."  DEFAULT ".str_replace("'","",$ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Default)."  ; ";
												 						else if(empty($ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Default))
												 						 $sql=" alter table `".$TABLE."` CHANGE `".$FIELD_TO_CHK."` `".$FIELD_TO_CHK."`  ".$ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Type." ; ";
												 						 else $sql=" alter table `".$TABLE."` CHANGE `".$FIELD_TO_CHK."` `".$FIELD_TO_CHK."`  ".$ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Type."  DEFAULT '".$ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Default."'  ; ";
																			$result=$this->query($sql) or  DEBUG_S(-3,'Problem ze SQL ',$sql,__FILE__, __FUNCTION__, __LINE__) or DIE();
																		
																	}
																	//autoincrement:
																	if(($VAL->Extra!=$ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Extra)&&$ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Extra=='auto_increment' ) {
																		//sprawdzmy czy nie ma w tabeli klucza z PRIMARY z ID
																		$sql="show keys from  `".$TABLE."`";
																		$result=$this->query($sql) or DEBUG_S(-3,'Problem ze SQL ',$sql,__FILE__, __FUNCTION__, __LINE__) or DIE();
																		 $TEST_IF_HAS_PRIMARY=false;
																		 while($tst=mysql_fetch_object($result)) { //dla kazdego klucza
																		   if($tst->Column_name==$FIELD_TO_CHK) //sprawdz czy jest klucz do tej kolumny
																		    if($tst->Key_name=='PRIMARY') $TEST_IF_HAS_PRIMARY=true; //jezeli jest primary, to flagujemy
																		 }
																		
																		if($TEST_IF_HAS_PRIMARY==false) { //bedziemy dodawac primary key 
																		  $sql="ALTER TABLE  `".$TABLE."` ADD PRIMARY KEY (  `".$FIELD_TO_CHK."` )";
																		  $result=$this->query($sql) or DEBUG_S(-3,'Problem ze SQL ',$sql,__FILE__, __FUNCTION__, __LINE__) or DIE();
																		 } 
																		$sql=" alter table `".$TABLE."` CHANGE `".$FIELD_TO_CHK."` `".$FIELD_TO_CHK."`  ".$ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Type."    ".$ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE]->Extra." ; ";
																		echo "\n SQL auto_increment ".$sql ;
																			$result=$this->query($sql) or DEBUG_S(-3,'Problem ze SQL ',$sql,__FILE__, __FUNCTION__, __LINE__) or DIE();
																		
																	}
								       								//foreach($ARR_TABLE['FIELDS'][$INDEX_OF_CONFIG_TABLE] as $TST_FIELD_IND=>$TST_FIELD_VAL) {
								       								//   echo "\n TST2 ".$TST_FIELD_IND." ?= ".$FIELDS_CHECKED['FIELD_FOUND_IN_REMOTE_DB_PROFILE'][$TST_FIELD_IND]->$TST_FIELD_IND;
								       								//}
								       								

								       						}
								       				//print_r($FIELDS_CHECKED);
								       				
								       			    $sql=" show index from  `".$TABLE."` ;" ;
								       			    echo "\n ".$sql;
       										       	$result=$this->query($sql) or die1('\nProblem z '.$sql);
								       				while($h=mysql_fetch_object($result)) {		       				
								       				set_time_limit(36000);       				
								       					$FIELDS_CHECKED['INDEX_FOUND_IN_TABLES'][$h->Key_name]=$h;
								       				}
													foreach($ARR_TABLE['INDEX'] as $FOUND_INDEX_NAME=>$FOUND_INDEX_ARR){
														$FIELDS_CHECKED['INDEX_TO_BE_FOUND_IN_TABLES'][$FOUND_INDEX_NAME]=$FOUND_INDEX_ARR;
													}
								       				DEBUG_S(-3,'Znaleziono indeksy w tabeli '.$TABLE." FOUND/TO_BE_FOUND",array($FIELDS_CHECKED['INDEX_FOUND_IN_TABLES'],$FIELDS_CHECKED['INDEX_TO_BE_FOUND_IN_TABLES']),__FILE__, __FUNCTION__, __LINE__);													
													//teraz wygaszam znalezione indeksy
													foreach($ARR_TABLE['INDEX'] as $FOUND_INDEX_NAME=>$FOUND_INDEX_ARR){
														echo "\n If jest ".$FOUND_INDEX_NAME;
															if(isset($FIELDS_CHECKED['INDEX_FOUND_IN_TABLES'][$FOUND_INDEX_NAME])) 
													           unset($FIELDS_CHECKED['INDEX_TO_BE_FOUND_IN_TABLES'][$FOUND_INDEX_NAME]);
								       				}
													//print_r($FIELDS_CHECKED['INDEX_TO_BE_FOUND_IN_TABLES']);
													//brakujace klucze dodajemy
													foreach($FIELDS_CHECKED['INDEX_TO_BE_FOUND_IN_TABLES'] as $FOUND_INDEX_NAME=>$FOUND_INDEX_ARR) {
														if($FOUND_INDEX_NAME=='PRIMARY') {
															$FOUND_INDEX_ARR->Column_name=str_replace('`','',$FOUND_INDEX_ARR->Column_name);
														    $sql="ALTER TABLE  `".$TABLE."` ADD PRIMARY KEY (  `".$FOUND_INDEX_ARR->Column_name."` ) ;";
														    echo "\n 927: ".$sql;
														    	$result=$this->query($sql) or  print_r($FIELDS_CHECKED) &&  die1('\nProblem z '.$sql);
														    $sql="ALTER TABLE  `".$TABLE."` CHANGE  `".$FOUND_INDEX_ARR->Column_name."`  `".$FOUND_INDEX_ARR->Column_name."` ".$FIELDS_CHECKED['FIELD_FOUND_IN_REMOTE_DB_PROFILE'][$FOUND_INDEX_ARR->Column_name]->Type." AUTO_INCREMENT ; ";
														    echo "\n ".$sql;
														    	$result=$this->query($sql) or  print_r($FIELDS_CHECKED) &&  die1('\nProblem z '.$sql);

														    	$result=$this->query($sql) or  print_r($FIELDS_CHECKED) &&  die1('\nProblem z '.$sql);
														 } else if($FOUND_INDEX_ARR->Non_unique==1) {
														    $sql="ALTER TABLE  `".$TABLE."` ADD KEY `".$FOUND_INDEX_ARR->Key_name."`  (  ".$FOUND_INDEX_ARR->Column_name." ) ;" ;
														    echo "\n ".$sql; 
														    	$result=$this->query($sql) or DEBUG_S(-3,'Problem ze SQL:',$sql,__FILE__, __FUNCTION__, __LINE__)  or die1();
														 } else {
														 set_time_limit(36000);
														 	//@2013-01-17 poprawka do kluczy bledu w stylu  ALTER TABLE  `IN7_PRODUKTY_CECHY` ADD UNIQUE `UNIK_CECHY_PRODUKTU`  (  CECHA_ID, PRODUKT_ID , DESC  ) ;
															$CORRECT_INDEX_FOUNDKEY="";
															if(!strstr($FOUND_INDEX_ARR->Column_name,'`')) {
																$explode=explode(' ',$FOUND_INDEX_ARR->Column_name);
																foreach($explode as $exploded) {
																	$exploded=str_replace(',','',$exploded); //wywalenie przecinkow
																	if((!strstr($exploded,' '))&&(strlen($exploded)>1))
																	if($CORRECT_INDEX_FOUNDKEY) $CORRECT_INDEX_FOUNDKEY.=" , `".$exploded."` ";
																	else $CORRECT_INDEX_FOUNDKEY.=" `".$exploded."` ";
																}
															} else $CORRECT_INDEX_FOUNDKEY=$FOUND_INDEX_ARR->Column_name;
//															$CORRECT_INDEX_FOUNDKEY=$FOUND_INDEX_ARR->Column_name;
														    $sql="ALTER TABLE  `".$TABLE."` ADD UNIQUE `".$FOUND_INDEX_ARR->Key_name."`  (  ".$CORRECT_INDEX_FOUNDKEY." ) ;" ;
														    echo "\n ".$sql; 

														    	$result=$this->query($sql) or DEBUG_S(-3,'Problem ze SQL:',$sql,__FILE__, __FUNCTION__, __LINE__)  or die1(); 
														 }
													} 
													flush();
													
								       				//print_r($FIELDS_CHECKED);
								       				unset($FIELDS_CHECKED);
								       				$sql=" show triggers like '".$TABLE."' ;" ; //listujemy nasze triggery z tej tabeli
									       			DEBUG_S(-3,'Looking for triggers in '.$TABLE,$sql,__FILE__,__FUNCTION__,__LINE__);
									       				$result=$this->query($sql) or die1('\nProblem z '.$sql);
								       			   	     while($h=mysql_fetch_object($result)) {		       				
								       				     set_time_limit(36000);       				
	 							       					 $sql_="show create trigger {$h->Trigger} ;" ;
	 								   					 //echo $sql_;
	 								   					 $result_=$this->query($sql_) or die1('\nProblem z '.$sql_);	
	 								   					 	while($h_=mysql_fetch_object($result_)) {			       					 
		 								   					 $FIELDS_CHECKED['TRIGGER_FOUNDS'][$h->Trigger]=$h_;
	 							       					     if(!isset($ARR_TABLE['TRIGGERS'][$h->Trigger]))  $FIELDS_CHECKED['TRIGGER_TO_DELETE'][$h->Trigger]=$h_;
		 								   					 }
	 							       					   
								       				    }
									       				DEBUG_S(-3,'Try to unserialize trigger and install to db:',$ARR_TABLE['TRIGGERS'],__FILE__,__FUNCTION__,__LINE__);
								       				//! try to synchronize triggers $TABLE=>$ARR_TABLE
								       				foreach($ARR_TABLE['TRIGGERS'] as $TRIGGER_INDEX=>$TRIGGER_OBJECT) {
										   				if(!isset($FIELDS_CHECKED['TRIGGER_FOUNDS'][$TRIGGER_INDEX]))  $FIELDS_CHECKED['TRIGGER_TO_CREATE'][$TRIGGER_INDEX]=$TRIGGER_OBJECT;
								       				}
								       				
								       				//staramy sie zaktualizowac stare triggery, pod warunkiem, ze sie roznia
								       				foreach($FIELDS_CHECKED['TRIGGER_FOUNDS'] as $TRIGGER_INDEX=>$TRIGGER_OBJECT) {
									       				DEBUG_S(-3,'TRIGGER_OBJECT/$TRIGGER_OBJECT for '.$TRIGGER_INDEX,array($TRIGGER_OBJECT,$ARR_TABLE['TRIGGERS'][$TRIGGER_INDEX]),__FILE__, __FUNCTION__, __LINE__);
									       				if(isset($ARR_TABLE['TRIGGERS'][$TRIGGER_INDEX])) //we first try to find if this trigger exists or delete it
									       				if($TRIGGER_OBJECT->{'SQL Original Statement'}<>$ARR_TABLE['TRIGGERS'][$TRIGGER_INDEX]->{'SQL Original Statement'} )  { 
									       					DEBUG_S(-3,"Triggers are different ({$TRIGGER_INDEX}). We add object to be created as new.",__FILE__, __FUNCTION__, __LINE__);
										   					$FIELDS_CHECKED['TRIGGER_TO_CREATE'][$TRIGGER_INDEX]=$ARR_TABLE['TRIGGERS'][$TRIGGER_INDEX];
										   					$FIELDS_CHECKED['TRIGGER_TO_DELETE'][$TRIGGER_INDEX]=true;

										   				}
								       				}
								       				
								       				
								       				if(isset($FIELDS_CHECKED['TRIGGER_TO_DELETE']))  {
								       					DEBUG_S(-3,'We have some triggers to delete',$FIELDS_CHECKED['TRIGGER_TO_DELETE'],__FILE__,__FUNCTION__,__LINE__);
									   					foreach($FIELDS_CHECKED['TRIGGER_TO_DELETE'] as $TRIGGER_INDEX=>$TRIGGER_OBJECT ) {
										   					$sql="DROP TRIGGER IF EXISTS `{$TRIGGER_INDEX}`; ";
										   				    DEBUG_S(-3,' sql to delete trigger '.$TRIGGER_INDEX,$sql,__FILE__,__FUNCTION__,__LINE__);
										   				    	$result=$this->query($sql) or DEBUG_S(-3,'Problem ze SQL:',$sql,__FILE__, __FUNCTION__, __LINE__)  or die1(); 

									   					}
								       				}
								       				
								       				
								       				//tworzymy brakujace procedury
								       				foreach ($FIELDS_CHECKED['TRIGGER_TO_CREATE'] as $TRIGGER_INDEX=>$TRIGGER_OBJECT) {
									       				//$sql="DROP TRIGGER IF EXISTS `{$TRIGGER_INDEX}`; ";
									       				//DEBUG_S(-3,'Delete old trigger '.$TRIGGER_INDEX,$sql,__FILE__,__FUNCTION__,__LINE__);
									       				//	$result=$this->query($sql) or DEBUG_S(-3,'Problem ze SQL:',array($sql,mysql_error() ),__FILE__, __FUNCTION__, __LINE__)  or die1(); 
										   				//	$result=$this->query("show create trigger {$TRIGGER_INDEX}") or DEBUG_S(-3,'Problem ze SQL:'.mysql_error(),$sql,__FILE__, __FUNCTION__, __LINE__)  or die1(); 		
									       				$sql=$TRIGGER_OBJECT->{'SQL Original Statement'};
									       				DEBUG_S(-3,'Try to add new trigger '.$TRIGGER_INDEX,$sql,__FILE__,__FUNCTION__,__LINE__);
									       					$result=$this->query($sql) or DEBUG_S(-3,'Problem ze SQL:',$sql,__FILE__, __FUNCTION__, __LINE__)  or die1(); 
									       				
								       				}
								       				
								       			
								       				
       										}
       										
       										
       				//tu bedziemy dodawac wartosci insert : 
       				$sql="select count(*) as ilosc from `".$TABLE."` ;" ;

					DEBUG_S(-3,'SQL: licze czy cos jest w tabeli ',$sql,__FILE__, __FUNCTION__, __LINE__) ;

       				$result=$this->query($sql) or die1('\nProblem z '.$sql);   
       				$ilosc=0;
       						//while($h=mysql_fetch_object($result)) {
       						//	$ilosc=$h->ilosc;
       						//} 				
       						//if($ilosc>0) {
       						//	DEBUG_S(-2,'Nie trzeba dodawac rekordow - juz jakies sa w tabeli: ilosc : ',$ilosc,__FILE__,__FUNCTION__,__LINE__);
       						//	continue ; 
       						//} else {
       						    if(!empty($ARR_TABLE['VALUES']))
	       						foreach($ARR_TABLE['VALUES'] as $ROW) {
									$sql="insert ignore into `".$TABLE."` values ( ";
									$vals="";
									foreach($ROW as $FIELD=>$VAL) {
										if(!$vals) $vals.="'".$VAL."'" ; else $vals.=" , '".$VAL."' ";
									}
									$sql.=$vals." ) ;";
										 $this->query($sql) or die1('\nProblem z '.$sql);   
									DEBUG_S(-3,'Dodanie rekordu do tabeli ',$sql,__FILE__,__FUNCTION__,__LINE__);
									
									
	       						}
	       					//}						
       										
        			}

	}




}
