<?php
class MyWeb_File_Model_Model extends MyWeb_File_Model_Abstract
{
	private $_nameController;
	private $_addContent;
	private $_foreigenTable;
	private $_fromForeigenTable;
	
	private $_selectColumnAll;
	private $_selectColumn;
	private $_selectForeignColumn;
	
	private $_selectForeignColumnForeigenTable;
	private $_selectColumnForeigenTable;
	private $_selectAllColumnForeigenTable;
	
	private $_hiddenIndex = 'Value';
	private $_hiddenIndexInputValue = 'InputValue';
	private $_hiddenIndexInputName = 'InputName';
	/*
	 * metoda selectState by mela byt soucasti knihovny takze ji neni potreba generovat
	 */
	private function defaultSettings()
	{
		if (is_null($this->_describeTable)){
			$this->_describeTable = $this->_dbTable->get_describeTable();
		}
		if (is_null($this->_nameController)){
			$this->_nameController = $this->_dbTable->get_modelName();
		}
		
		$this->set_defaultColumn();
	}
	
	
	
	
	public function __construct($dbTable,$path = null)
	{
		$this->_dbTable = $dbTable;
		$this->defaultSettings();
		$this->_path = $path;	//*** pridano zajistuje pouziti nove cesty od uzivatele misto default
		$this->defaultSettingsPath($this->_default_path_model_php);
		$this->set_typeFile('php');
		$this->_currentPrefix = 0;
		if (0 === strcmp($this->_filename, 'none')){
			$this->_filename = ucfirst($this->_dbTable->get_modelName());
		}
		//echo $this->create_join();
	}
	
	/**
	 * metoda vytvari retezce where pro fetchEntries
	 */
	private function createWhere()
	{
		$where = '';
		foreach ($this->_selectColumn as $key => $value){
			
			if (strcmp(strtolower($value), strtolower('State_id_state')) === 0){
				// overeni existence tabulky
				$query1 = "SHOW TABLES LIKE '".'state'."'";
				$query2 = "SHOW TABLES LIKE '".'namestate'."'";
				$query3 = "SHOW TABLES LIKE '".'TableDatabase'."'";
				$db = $this->get_dbTables()->get_db();
				$result1 = $db->fetchAll($query1,'FETCH_NUM');
				$result2 = $db->fetchAll($query2,'FETCH_NUM');
				$result3 = $db->fetchAll($query3,'FETCH_NUM');
				//echo "<p>"." count ".var_dump(count($result))."</p>";
				if( count($result1)>0 && count($result2)>0 && count($result3)>0) {
				// nalezeni primarniho klice cizy tabulky
				$pk_ftable = "";
				$foreignTable = explode('_', $this->_selectColumn[$key]);
				$foreignTable = strtolower($foreignTable[0]);
				
				$columnForm = $this->_selectColumn[$key].$this->_hiddenIndex;
				$columnFormHiddenName = $this->_selectColumn[$key].$this->_hiddenIndexInputName;
				$columnFormHiddenValue = $this->_selectColumn[$key].$this->_hiddenIndexInputValue;
				$where .= 
				"\n\t".	'if (array_key_exists(\''.$columnForm.'\', $data) && !empty($data[\''.$columnForm.'\'])){'	. "\n" .
        		"\t\t".		'if ((array_key_exists(\''.$columnFormHiddenName.'\', $data)) && (array_key_exists(\''.$columnFormHiddenValue.'\', $data))){'	. "\n" .
       			"\t\t\t".		'if (!empty($data[\''.$columnFormHiddenName.'\']) && (strcmp($data[\''.$columnFormHiddenName.'\'],"none") !== 0) && (strcmp($data[\''.$columnFormHiddenName.'\'],"") !== 0)){' . "\n" .
				"\t\t\t\t".			'if (!empty($data[\''.$columnFormHiddenValue.'\']) && (strcmp($data[\''.$columnFormHiddenValue.'\'],"none") !== 0) || (strcmp($data[\''.$columnFormHiddenValue.'\'],"0") !== 0)){' . "\n" .
        		"\t\t\t\t\t".			'$select	->	where(\''.substr(ucfirst($this->_dbTable->get_modelName()),0,1).'.'.$this->_selectColumn[$key].' = ?\',$data[\''.$columnFormHiddenValue.'\']);' . "\n" .
       			"\t\t\t\t".			'}'. "\n" .
       			"\t\t\t".		'}'. "\n" .
				"\t\t".		'}'. "\n" .
				"\t\t".		'$select	->	where(\''.'N.nameState_name'.' = ?\',$data[\''.$columnForm.'\']);' . "\n" .
				"\t".	'}'. "\n";
				}
			}else {
				$where .= 
       			"\n\t".		'if (array_key_exists(\''.$this->_selectColumn[$key].'\',$data)){' . "\n" .
				"\t\t".			'if (!empty($data[\''.$this->_selectColumn[$key].'\']) && (strcmp($data[\''.$this->_selectColumn[$key].'\'],"none") !== 0) && (strcmp($data[\''.$this->_selectColumn[$key].'\'],"") !== 0)){' . "\n" .
        		"\t\t\t".			'$select	->	where(\''.substr(ucfirst($this->_dbTable->get_modelName()),0,1).'.'.$this->_selectColumn[$key].' = ?\',$data[\''.$this->_selectColumn[$key].'\']); ' . "\n" .
       			"\t\t".			'}'. "\n" .
       			"\t".		'}'. "\n";
			}
		}
		return $where;
	}
	
	
	
	/**
	 * metoda vybere sloupce tabulky netvorici cizy klic a tvorici
	 */
	protected  function set_defaultColumn($table = NULL)
	{
		if (is_null($table)){
			$this->_selectColumn[] = current($this->_dbTable->get__modelPrimary());
			foreach ($this->_dbTable->get_describeTable() as $key => $value){
				//if ((strcmp($this->_describeTable[$key]['Key'], 'PRI') !== 0) && (strcmp($this->_describeTable[$key]['Key'], 'MUL') !== 0)){
				if ((strcmp($this->_describeTable[$key]['Key'], 'PRI') !== 0)){
					//&& (strcmp($this->_describeTable[$key]['Key'], 'MUL') !== 0)
					$this->_selectColumn[] = $this->_describeTable[$key]['Field']; //pole se vsemi sloupci vyjma primarniho
				}
				if ((strcmp($this->_describeTable[$key]['Key'], 'MUL') == 0)){
					$this->_selectForeignColumn[] = $this->_describeTable[$key]['Field'];//pole s pouze cizimi klici
					//echo "<p>".$this->_describeTable[$key]['Field']."</p>";
				}
				$this->_selectColumnAll[] = $this->_describeTable[$key]['Field'];//pole se vsemi slouci
			}
		}else{
			// je to nabytecne protoze tato vetev byla dodana za behu
			$this->_selectColumnForeigenTable[] = current($table->get__modelPrimary());
			$describeForeigenTable = $table->get_describeTable();
			foreach ($describeForeigenTable as $key => $value){
				//if ((strcmp($this->_describeTable[$key]['Key'], 'PRI') !== 0) && (strcmp($this->_describeTable[$key]['Key'], 'MUL') !== 0)){
				if ((strcmp($describeForeigenTable[$key]['Key'], 'PRI') !== 0)){
					//&& (strcmp($this->_describeTable[$key]['Key'], 'MUL') !== 0)
					$this->_selectColumnForeigenTable[] = $describeForeigenTable[$key]['Field']; //pole se vsemi sloupci vyjma primarniho
				}
				if ((strcmp($this->_describeTable[$key]['Key'], 'MUL') == 0)){
					$this->_selectForeignColumnForeigenTable[] = $describeForeigenTable[$key]['Field'];//pole s pouze cizimi klici
					//echo "<p>".$this->_describeTable[$key]['Field']."</p>";
				}
				$table->_selectAllColumnForeigenTable[] = $describeForeigenTable[$key]['Field'];//pole se vsemi slouci
			}
		}
	}
	
	private function create_join()
	{
		$join = '';
		$columnForeignTable = '';
		//'S.NameState_id_NameState = N.id_NameState',
		if (is_array($this->_selectForeignColumn)){	//tabulka neobsahuje cizy klice
			foreach ($this->_selectForeignColumn as $key => $nameColumn){
				//KONTROLA ZDA NEJDE O M:N
				if(stristr($this->_dbTable->get_modelName(), '_has_') === FALSE) {
					$explodeName = explode('_', $nameColumn,2);
					$this->_foreigenTable[] = $explodeName[0];
					//$this->_fromForeigenTable .= substr(ucfirst($explodeName[0]),0,1).'.'.$explodeName[0]
					//echo "<p>".$explodeName[0]."</p>";
					//echo "<p>".$explodeName[1]."</p>";
					$dbTables = MyWeb_DbTable_CreatorDbTable::loadDbTables(array($explodeName[0]), $this->_dbTable->get_db()->getConfig());
					$foreigenTable = $dbTables[0]['table']->get_describeTable();
					//echo "<p>".$explodeName[0]."</p>";
					
					foreach ($foreigenTable as $key => $value){
						$columnForeigenTable[] = $foreigenTable[$key]['Field'];//pole se vsemi slouci
						//echo "<p>".$foreigenTable[$key]['Field']."</p>";
					}
					
					// pokud jmeno sloupce cizy tabulky je stejne jako jmeno sloupce v hlavni tabulce nebude vypsan
					foreach ($columnForeigenTable as $key => $value){
						if (in_array($value, $this->_selectColumn)){
							$key = array_search($value, $columnForeigenTable);
							unset($columnForeigenTable[$key]);
							reset($columnForeigenTable);
						}
					}
					
					$join .= "\n\t\t\t".'		->	join(array(\''.substr(ucfirst($dbTables[0]['table']->get_modelName()),0,1).'\' => \''.$dbTables[0]['table']->get_modelName().'\'),' . "\n" .
					 	 "\t\t\t\t\t\t\t".				'\''.substr(ucfirst($this->_dbTable->get_modelName()),0,1).'.'.$nameColumn
					 									.'='.substr(ucfirst($dbTables[0]['table']->get_modelName()),0,1).'.'.$explodeName[1].'\','. "\n" .
					 	 "\t\t\t\t\t\t\t".				'array(\''.implode("','", $columnForeigenTable).'\'))';
					
					 
        							
        							
					$columnForeigenTable = NULL;
				}
			}
			$query1 = "SHOW TABLES LIKE '".'state'."'";
			$query2 = "SHOW TABLES LIKE '".'namestate'."'";
			$query3 = "SHOW TABLES LIKE '".'TableDatabase'."'";
			$db = $this->get_dbTables()->get_db();
			$result1 = $db->fetchAll($query1,'FETCH_NUM');
			$result2 = $db->fetchAll($query2,'FETCH_NUM');
			$result3 = $db->fetchAll($query3,'FETCH_NUM');
			//echo "<p>"." count ".var_dump(count($result))."</p>";
			if( count($result1)>0 && count($result2)>0 && count($result3)>0) {
				if (in_array('State_id_state', $this->_selectColumn)){
					 	$join .=	"\n\t\t\t\t\t".			'->	join(array(\'N\' => \'NameState\'),'						. "\n" .
        							"\t\t\t\t\t\t\t".		'\'S.NameState_id_NameState=N.id_NameState\','				. "\n" .
        							"\t\t\t\t\t\t\t".		'array(\'id_NameState\',\'nameState_name\'))'				. "\n" .
        							"\t\t\t\t\t".			'->	join(array(\'T\' => \'TableDatabase\'),'					. "\n" .
        							"\t\t\t\t\t\t\t".		'\'S.TableDatabase_id_tableDatabase=T.id_tableDatabase\','	. "\n" .
        							"\t\t\t\t\t\t\t".		'array(\'id_tableDatabase\',\'tableDatabase_table\'))';
				}
			}
		}
		return $join;
	}
	
	
	
	/**
	 * 
	 * Metoda prida retezec do vysledneho souboru
	 * @param $content
	 */
	public function add_contentFile($content)
	{
		$this->_addContent = $content;
	}
	
	
	
	
	
	
	
	
	/**
     *  createModelTable
     *  
     *  create class and files model
     */
	public function createContent()
	{
		$stringFile = "<?php \n";
		//**************************************************************************************
		//**************************************************************************************
			
		
		// ************ fetchEntries ***********************
			$methodFetchEntries = new Zend_CodeGenerator_Php_Method();
        	$methodFetchEntries ->setName('fetchEntries');
			$methodFetchEntries ->setParameter( array('name' => 'dataInput'));
			$methodFetchEntries ->setBody(
        		'// databázový adaptér' . "\n" .
        		'$db = $this->getStorage()->getAdapter();'					. "\n" .
       			'$select = $this->createFetchEntrySelect($dataInput);'		. "\n" .
																		  "\n" .
																		  "\n" .
																		  "\n" .
				'// načítá údaje'						. "\n" .
				'$this->showMe($select, \'Q\');'		. "\n" .
        		'$data = $db->fetchAll($select);'		. "\n" .
				'return $data;' 						. "\n"
        		);
		
		
		
			// ************ fetchEntry ***********************
			$methodFetchEntry = new Zend_CodeGenerator_Php_Method();
			$methodFetchEntry ->setName('fetchEntry');
			$methodFetchEntry ->setParameter( array('name' => 'id'));
			$methodFetchEntry ->setBody(
			
			
        		'// databázový adaptér' . "\n" .
        		'$db = $this->getStorage()->getAdapter();' . "\n" . "\n" .
       			
        		'// vytvoří SELECT' . "\n" .
        		'$select = $db->select();' . "\n" .
				
        		'if (is_null($id)){' . "\n" .
        		"\t".'$select	->	from(array(\''.substr(ucfirst($this->_dbTable->get_modelName()),0,1).'\' => \''.$this->_dbTable->get_modelName().'\'),' . "\n" .
       			"\t\t\t\t\t\t".				'array(\''.implode("','", $this->_selectColumn).'\'))' . "\n" .
				$this->create_join().';' . "\n" .
        		'}else {' . "\n" .
        		"\t".'$select	->	from(array(\''.substr(ucfirst($this->_dbTable->get_modelName()),0,1).'\' => \''.$this->_dbTable->get_modelName().'\'),' . "\n" .
       			"\t\t\t\t".'array(\''.implode("','", $this->_selectColumn).'\'))' . "\n" .
				$this->create_join() . "\n" .
       			"\t\t\t\t".'->	where(\''.substr(ucfirst($this->_dbTable->get_modelName()),0,1).".".current($this->_dbTable->get__modelPrimary()).' = ?\',$id);' . "\n" .
        		'}' . "\n" .
        
        		'// načítá údaje' . "\n" .
				'$this->showMe($select, \'Q\');'			. "\n" .
				'$db->setFetchMode(Zend_Db::FETCH_ASSOC);'	. "\n" .
        		'$data[\'data\'] = $db->fetchRow($select);' . "\n" .
        		'return $data;' . "\n"
        		);
        		
        		
        		
        	// ************ getFetchEntrySelect ***********************
        	$getFetchEntrySelect = new Zend_CodeGenerator_Php_Method();
        	$getFetchEntrySelect ->setName('getFetchEntrySelect');
			$getFetchEntrySelect ->setParameter( array('name' => 'data'));
			$getFetchEntrySelect ->setBody(
				'$select = $this->createFetchEntrySelect($data);'			. "\n" .
				'$select = $this->createWhere($select, $data, " ");'	. "\n" .
				'return $select;'											. "\n"
				);
			// ************ fetchEntries ***********************
			$methodCreateFetchEntrySelect = new Zend_CodeGenerator_Php_Method();
        	$methodCreateFetchEntrySelect ->setName('createFetchEntrySelect');
			$methodCreateFetchEntrySelect ->setParameter( array('name' => 'data'));
			$methodCreateFetchEntrySelect ->setBody(
        		'// databázový adaptér' . "\n" .
        		'$db = $this->getStorage()->getAdapter();' . "\n" . "\n" .
       			
        		'// vytvoří SELECT' . "\n" .
        		'$select = $db	->	select()' . "\n" .
				"\t			->	from(array('".substr(ucfirst($this->_dbTable->get_modelName()),0,1).'\' => \''.$this->_dbTable->get_modelName().'\'),' . "\n" .
        		"\t				array('".implode("','", $this->_selectColumn).'\'))' . "\n" .
        		$this->create_join().';' . "\n" . "\n" .
        		
        		'$select	->	where(\'T.tableDatabase_table = ?\',$this->_storageName);'	. "\n" .
        		'// načítá údaje' 									. "\n" .
        		' if (is_null($data)){' 							. "\n" .
        		"\t".'$this->showMe(\'kompletni vypis\', \'info\');'					. "\n" .
				'}else {' 											. "\n" .
        		
				$this->createWhere()								. "\n" .
				
				'}'											. "\n" .
				'$this->showMe($select, \'Q\');'			. "\n" .
				'return $select;' 					. "\n"
        		);
        		
        		
			$class = new Zend_CodeGenerator_Php_Class();
			$class	->setName('Application_Model_'.ucfirst($this->_dbTable->get_modelName()).' extends MyWeb_Model_Database')
					->setProperties($this->classProperties())
					->setMethod($methodFetchEntries)
					->setMethod($methodFetchEntry)
					->setMethod($getFetchEntrySelect)
					->setMethod($methodCreateFetchEntrySelect);
					
					
					
			$stringFile .= $class;
			$this->set_contentFile($stringFile);
	}
	
	
	protected function classProperties()
	{
		$properties = array(
										array(
												'name'         => '_storageName',
												'visibility'   => 'protected',
												'defaultValue' => ucfirst($this->_dbTable->get_modelName())
												),
										array(
												'name'         => '_formClasses',
												'visibility'   => 'protected',
												'defaultValue' => array(
        															'insert' => $this->_dbTable->get_modelName().ucfirst($this->prefix[1]),
        															'update' => $this->_dbTable->get_modelName().ucfirst($this->prefix[2]),
        															'search' => $this->_dbTable->get_modelName().ucfirst($this->prefix[3])
    																)
												)
											);
											
		// v pripade ze jde o model user obsahuje navic formulare pro login a logout
		if (strcmp($this->_dbTable->get_modelName(),'user') === 0){
			$properties[1]['defaultValue']['login']  = 'userLogin';
			$properties[1]['defaultValue']['logout']  = 'userLogout';
		}
		return $properties;
	}
	
	
}