<?php
/**
 * TODO: columns in $_SESSION['columns'][ Table ][ Field ] = array(Type, Type_value, Default, Null)
 *     legacy: $_SESSION[ Table . '_COLUMN'][ TYPE ], ...
 *   $_SESSION['columns'][ Table ]
 * 
 * add column config to config/.cnf--column_init_{TBL_NAME}.ini.php
 * @see method is_allowed
 */


class Column {


var $_table;
var $_data;
var $_initialized;


function __construct( $table, &$col_data ) {
	$this->_table = $table;
	$this->_data = $col_data;
	$this->_initialized = (V::get('_checked', '', $col_data))? true : false;
}


function initialized() {
	return $this->_initialized;
}


function type($field_name) {
	$type = V::get($field_name, '', $this->_data['TYPESPECIAL']);
	if (!$type) $type = V::get($field_name, '', $this->_data['TYPE']);
	return $type;
}


function desc($field_name) {
	return V::get($field_name, '', $this->_data['DESC_TO_LANG']);
}


function perm($field_name) {
	return V::get($field_name, '', $this->_data['PERMEDIT']);
}


function allowWrite($field_name) {
	return (strpos($this->perm($field_name), 'W') !== false)? true : false;
}


function allowRead($field_name) {
	return (strpos($this->perm($field_name), 'R') !== false)? true : false;
}


function allowCreate($field_name) {
	return (strpos($this->perm($field_name), 'C') !== false)? true : false;
}


/**
 * @returns array to store in session
 */
function toArray() {
	return $this->_data;
}


/**
 * Initialize column and store data i session.
 * 
 * static
 */
public static function init( $table, $force = false ) {

	$col = Column::getInstance($table);
	if ($col && $col->initialized() && $force == false) {
		return;
	}

	Lib::loadClass('Config');
	$tbl_config = Config::getColumnConf($table);
	/**
	 * conf_file(CRM_PROCES): Array(
	 *     [CONFIG] => Array(
	 *             [database] => default
	 *             [table] => CRM_PROCES
	 *             [hist_table] => CRM_PROCES_HIST
	 *             [extra_column] => 
	 *             [perm_mask] => 
	 *         )
	 *     [DESC_TO_LANG] => Array(
	 *             [ID] => 
	 *         )
	 *     [DEFAULT_VALUE] => Array(
	 *             [A_STATUS] => WAITING
	 *         )
	 *     [PERMEDIT] => Array(
	 *             [ID] => R
	 *         )
	 *     [TYPESPECIAL] => Array(
	 *         )
	 */
	if (!$tbl_config) {
		return;
	}

	if (!self::is_allowed( $table )) {
		return;
	}

	$col_data = self::get_table_struct( $table, $tbl_config );

	// DESC_TO_LANG
	$col_data['DESC_TO_LANG'] = V::get('DESC_TO_LANG', array(), $tbl_config);

	// TYPESPECIAL
	$col_data['TYPESPECIAL'] = V::get('TYPESPECIAL', array(), $tbl_config);

	$col_data['_checked'] = true;
	self::saveColumn($table, $col_data);
}


function init_old(){
	return;

	// wymagane struktura tabeli `CRM_LISTA_ZASOBOW` w tej wersji aplikacji:
	$column_struct = array();
	//ZAP_SQL("show fields from $COLUMN");// Field, Type, Null, Key, Default, Extra
	//$column_struct[ Field ] = array( Type, Type_value, Default, Null, Extra );
	function column_struct_create_type_obj($type, $type_value=null, $default=null, $null=null, $extra=null) {
		return (object)array('Type'=>$type, 'Type_value'=>$type_value, 'Default'=>$default, 'Null'=>$null, 'Extra'=>$extra);
	}
	$column_struct['ID'] = column_struct_create_type_obj('int', 11, null, 'NO', 'auto_increment');
	$column_struct['TYPE'] = column_struct_create_type_obj('enum', array('KONTO-KSIEGOWE-OLD', 'KONTO-KSIEGOWE-ZESPOL', 'KONTO-KSIEGOWE', 'KONTO-KSIEGOWE-GRUPA', 'DANE', 'WYNIK_ZAPYTANIA', 'NARZEDZIE', 'PLIK', 'ZASOB_PLIKOW', 'TABELA', 'KOMORKA', 'BAZA_DANYCH', 'DATABASE_MYSQL', 'SERWER', 'DOKUMENTY', 'MAGAZYN', 'SEGREGATOR', 'POMIESZCZENIE', 'MATERIAL_REKLAMOWY', 'DZIAL', 'STANOWISKO', 'INNE', 'CZYNNOSC', 'PODMIOT', 'ALARM-SATEL', 'NOTATKA'), 'INNE');
	$column_struct['DESC'] = column_struct_create_type_obj('varchar', 255, '');
	$column_struct['OPIS'] = column_struct_create_type_obj('text');
	$column_struct['SORT_PRIO'] = column_struct_create_type_obj('int', 11, 0);
	$column_struct['PARENT_ID'] = column_struct_create_type_obj('int', 11, 0);

echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;">';
	$table = "CRM_LISTA_ZASOBOW";
	echo"column `$table`:\n";
	ZAP_SQL("show fields from `$table`;");// Field, Type, Null, Key, Default, Extra
	while ($h = mysql_fetch_object($result)) {
/*  [Field] => ID
    [Type] => int(11)
    [Null] => NO
    [Key] => PRI
    [Default] => 
    [Extra] => auto_increment
*/
		if (array_key_exists($h->Field, $column_struct)) {
			echo'<b>ok Field in struct "'.$h->Field.'"</b> ' . "\n";;
			$d =& $column_struct[$h->Field];// application definition
			$h->Type_value = '';
			if (substr($h->Type, 0, 3) == 'int') {
				$h->Type_value = (int)str_replace(array(' ','(',')'), '', substr($h->Type, 4));
				$h->Type = 'int';
			} else if (substr($h->Type, 0, 7) == 'varchar') {
				$h->Type_value = (int)str_replace(array(' ','(',')'), '', substr($h->Type, 8));
				$h->Type = 'varchar';
			} else if (substr($h->Type, 0, 4) == 'enum') {
				$h->Type_value = explode(',', str_replace(array('(',')',"'",'"'), '', substr($h->Type, 5)));
				$h->Type = 'enum';
			} else if (substr($h->Type, 0, 4) == 'text') {
				$h->Type = 'text';
			} else echo'unknown Type "'.$h->Type.'"';
			//} else if (substr($h->Type, 0, 3) == 'int') $h->Type_value = '';

			// $sql = "ALTER TABLE  `".$table."` CHANGE  `ID`  `ID` INT NOT NULL AUTO_INCREMENT; ";
			if ($h->Type != $d->Type) {
				echo'<b style="color:red">Field Type error - "'.$h->Type.'" expected "'.$d->Type.'"</b>'."\n";
				//TODO: try convert type ? float->double, int->float, varchar->text, ...
			} else if ($h->Type_value != $d->Type_value) {
				echo'<b style="color:red">Field Type_value error - "'.$h->Type_value.'" expected "'.$d->Type_value.'"</b>'."\n";
				//TODO: try to alter table
			} else if ($h->Default != $d->Default) {
				echo'<b style="color:red">Field Type_value error - "'.$h->Type_value.'" expected "'.$d->Type_value.'"</b>'."\n";
				//TODO: try to alter table
			}

			print_r($h);
		} else {
			echo'<em>Unknown Field "'.$h->Field.'"</em> ';
			//print_r($h);
		}
		echo "\n";
	}
echo'</pre>';
//$_SESSION['CRM_LISTA_ZASOBOW_COLUMN']['_checked'] = true;

	$COLUMN="CRM_LISTA_ZASOBOW";
	ZAP_SQL("show fields from $COLUMN");
	$KEY=0;
	while ($h=mysql_fetch_row($result)) {
		$_SESSION[$COLUMN."_COLUMN"]['DESC']["$KEY"] = $h[0];
		$_SESSION[$COLUMN."_COLUMN"]['TYPE'][$_SESSION[$COLUMN."_COLUMN"]['DESC']["$KEY"]] = $h[1];
		if(!isset($_SESSION[$COLUMN."_COLUMN"]['PERMEDIT'][$h[0]])) $_SESSION[$COLUMN."_COLUMN"]['PERMEDIT'][$h[0]] = "RW" ;
		$_SESSION[$COLUMN."_COLUMN"]['DESC_TO_KEY'][$h[0]] = $KEY;
		$_SESSION[$COLUMN."_COLUMN"]['ID']["$KEY"]=$KEY;
		if($_SESSION['USER_PROFILE'][$COLUMN."_COLUMN"]["$KEY"] == "HIDE") {  
			$_SESSION[$COLUMN."_COLUMN"]['HIDE']["$KEY"]='HIDE';
		}
		$KEY++;
	}
//	echo "<br>Zainicjalizowano kolumne $COLUMN<br>";
}


public static function get_table_struct( $tbl_name, $tbl_conf ) {
	$col = array();

	//$COLUMN = $INIT_TABLE;
	// clean session data
	//$_SESSION[$COLUMN."_COLUMN"] = array();
	//$EXTRACOLUMN=" ";
	//$EXTRACOLUMN = (!empty($EXTRACOLUMN))? explode(" ", $EXTRACOLUMN) : array();

	//TODO2006-03 zapytanie w foreach
	//inicjalizacja podrecznikowych zapytan do tabel dla jednej sesji
	//if ($_SESSION['USERS2_MARKETING_COLUMN']['RELATIVEDB']['SQL_QUERY'][1]) {
	//	foreach ($_SESSION['USERS2_MARKETING_COLUMN']['RELATIVEDB']['SQL_QUERY'] as $value_key => $value) {
			// echo "<br> Zainicjalizowano zapytanie value $value key $value_key <br> ";
	//		ZAP_SQL($value);
	//	}
	//}

	$database = V::get('database', null, $tbl_config['CONFIG']);
	$db = DB::getDB($database);
	$res = $db->query("show fields from `$tbl_name` ");

	$KEY = 0;

	$col['PERMEDIT']['ID'] = "R";
	$col['PERMEDIT']['A_RECORD_CREATE_DATE'] = "R";
	$col['PERMEDIT']['A_RECORD_UPDATE_DATE'] = "R";
	$col['PERMEDIT']['A_RECORD_UPDATE_AUTHOR'] = "R";
	$col['PERMEDIT']['A_RECORD_CREATE_AUTHOR'] = "R";

	while ($h = $db->fetch_row($res)) {

		$field_name = $h[0];
		$field_type = $h[1];
		if (empty($tbl_conf['PERMEDIT'][$field_name])) {
			continue;
		}

		$col['DESC']["$KEY"] = $field_name;
		$col['TYPE'][ $col['DESC']["$KEY"] ] = $field_type;
		//if (!isset($tbl_conf['PERMEDIT'][$field_name])) {
		$col['PERMEDIT'][ $field_name ] = $tbl_conf['PERMEDIT'][$field_name];
		//}
		$col['DESC_TO_KEY'][ $field_name ] = $KEY;
		$col['ID']["$KEY"] = $KEY;
		//if ($_SESSION['USER_PROFILE'][$COLUMN."_COLUMN"]["$KEY"] == "HIDE") {
		//	$col['HIDE']["$KEY"] = 'HIDE';
		//}
		$KEY++;
	}

if(0){
	foreach ($EXTRACOLUMN as $h) {
		$col['DESC']["$KEY"] = $h;
		$col['DESC_TO_KEY'][$h] = $KEY;
		if (!isset($col['PERMEDIT'][$h])) {
			$col['PERMEDIT'][$h] = "N";
		}
		$col['ID']["$KEY"] = $KEY;
		$TEMP1 = $col['DESC']["$KEY"];
		$col['TYPE'][$_SESSION[$COLUMN."_COLUMN"]['DESC']["$KEY"]] = "varchar(245)";
		if ($col["$KEY"] == "HIDE") {
			$col['HIDE']["$KEY"] = 'HIDE';
		}
		$KEY++;
	}
}

	return $col;
}


function get_table_hist_struct( $tbl_name ) {
	$col = array();
	$tbl_hist_name = $tbl_name . "_HIST";
	$res = DB::query("show fields from `$tbl_hist_name` ");
	$KEY = 0;
	while ($h = mysql_fetch_row($res)) {
		$col['DESC']["$KEY"] = $h[0];
		$col['TYPE'][ $col['DESC']["$KEY"] ] = $h[1];
		if (!isset($col['PERMEDIT'][ $h[0] ])) {
			$col['PERMEDIT'][ $h[0] ] = "RW";
		}
		$col['DESC_TO_KEY'][ $h[0] ] = $KEY;
		$col['ID']["$KEY"] = $KEY;
		//if ($_SESSION['USER_PROFILE'][$COLUMN."_COLUMN"]["$KEY"] == "HIDE") {
		//	$_SESSION[$COLUMN."_COLUMN"]['HIDE']["$KEY"] = 'HIDE';
		//}
		$KEY++;
	}
	return $col;
}


/**
 * TODO: read from config file for column! @see sew
 * @return Boolean
 */
public static function is_allowed($column_name) {
	if (empty($column_name)) {
		return false;
	}
	switch ($column_name) {
		case 'CRM_PROCES':
		case 'CRM_LISTA_ZASOBOW':
		case 'CRM_TESTY':
			return true;
			break;
		default:
			return true;// TODO: use zasoby
			if (is_numeric($column_name)) {
				// TODO: pobierz dane ProcesLog_ID
				return false;
			}
	}
	return false;
}


function getVisibleFieldList() {
	$cols = array();
	foreach ($this->_data['ID'] as $field_id) {
		$field_name = $this->_data['DESC'][ $field_id ];
		if (User::getProfileColumn($this->_table, $field_id) == 'HIDE') {
			continue;
		}
		$cols[ $field_id ] = $field_name;
	}
	return $cols;
}


function getFieldList() {
	$cols = array();
	foreach ($this->_data['ID'] as $field_id) {
		$field_name = $this->_data['DESC'][ $field_id ];
		$cols[ $field_id ] = $field_name;
	}
	return $cols;
}


/**
 * Get column object. Not initialize
 * @returns object - column instance if exists else null
 * 
 * static
 */
public static function getInstance($table) {
	static $_cache;
	if (!$_cache) $_cache = array();
	if (array_key_exists($table, $_cache)) {
		return $_cache[$table];
	}
	if (!empty($_SESSION['columns'][$table])) {
		$col = new Column($table, $_SESSION['columns'][$table]);
		if ($col->initialized()) {
			$_cache[$table] = $col;
			return $_cache[$table];
		}
	}
	return null;
}


/**
 * static
 */
function saveColumn($table, $data) {
	// TODO: is_allowed
	if (is_numeric($table)) {
		// TODO: $_SESSION['PROCES_LOG'][$column_name] = $data;
	} else {
		$_SESSION['columns'][$table] = $data;
	}
	if(User::isAdmin())
		self::saveToAcl($table,$data); //@2014-03-17 nalezy admina permy nadpisac do ACLi jezeli jest adminem
}


function saveToAcl($table,$data) {
	//wykrywamy czy ma dostepny proces do jakiejs komorki w tej tabeli
		$userAcl = User::getAcl();
		$tblAcl = $userAcl->getTableAcl(ProcesHelper::getZasobTableID($table));
	if($tblAcl)
	foreach($data['PERMEDIT'] as $FIELD=>$PERM) {
		$tblAcl->setFieldPerms($tblAcl->getFieldIdByName($FIELD),$PERM);
	}
	
	
}



}
