<?php 
class Application_Model_Table1 extends MyWeb_Model_Database
{

    protected $_storageName = 'Table1';

    protected $_formClasses = array(
        'insert' => 'table1New',
        'update' => 'table1Edit',
        'search' => 'table1Search'
        );

    public function fetchEntries($dataInput)
    {
        // databázový adaptér
        $db = $this->getStorage()->getAdapter();
        $select = $this->createFetchEntrySelect($dataInput);
        
        
        
        // načítá údaje
        $this->showMe($select, 'Q');
        $data = $db->fetchAll($select);
        return $data;
    }

    public function fetchEntry($id)
    {
        // databázový adaptér
        $db = $this->getStorage()->getAdapter();
        
        // vytvoří SELECT
        $select = $db->select();
        if (is_null($id)){
        	$select	->	from(array('T1' => 'table1'),
        						array('id_table1','table1_column1','table1_column2','table1_column3','table3_id_table3'))
        
        					->	join(array('T3' => 'table3'),
        							'T1.table3_id_table3=T3.id_table3',
        							array('id_table3','table3_column1','table3_column2','table3_column3'));
        }else {
        	$select	->	from(array('T1' => 'table1'),
        				array('id_table1','table1_column1','table1_column2','table1_column3','table3_id_table3'))
        
        					->	join(array('T3' => 'table3'),
        							'T1.table3_id_table3=T3.id_table3',
        							array('id_table3','table3_column1','table3_column2','table3_column3'))
        				->	where('T1.id_table1 = ?',$id);
        }
        // načítá údaje
        $this->showMe($select, 'Q');
        $db->setFetchMode(Zend_Db::FETCH_ASSOC);
        $data['data'] = $db->fetchRow($select);
        return $data;
    }

    public function getFetchEntrySelect($data)
    {
        $select = $this->createFetchEntrySelect($data);
        $select = $this->createWhere($select, $data, " ");
        return $select;
    }

    public function createFetchEntrySelect($data)
    {
        // databázový adaptér
        $db = $this->getStorage()->getAdapter();
        
        // vytvoří SELECT
        $select = $db	->	select()
        				->	from(array('T1' => 'table1'),
        					array('id_table1','table1_column1','table1_column2','table1_column3','table3_id_table3'))
        
        					->	join(array('T3' => 'table3'),
        							'T1.table3_id_table3=T3.id_table3',
        							array('id_table3','table3_column1','table3_column2','table3_column3'));
        
        // načítá údaje
         if (is_null($data)){
        	$this->showMe('kompletni vypis', 'info');
        }else {
        
        	if (array_key_exists('id_table1',$data)){
        		if (!empty($data['id_table1']) && (strcmp($data['id_table1'],"none") !== 0) && (strcmp($data['id_table1'],"") !== 0)){
        			$select	->	where('T1.id_table1 = ?',$data['id_table1']); 
        		}
        	}
        
        	if (array_key_exists('table1_column1',$data)){
        		if (!empty($data['table1_column1']) && (strcmp($data['table1_column1'],"none") !== 0) && (strcmp($data['table1_column1'],"") !== 0)){
        			$select	->	where('T1.table1_column1 = ?',$data['table1_column1']); 
        		}
        	}
        
        	if (array_key_exists('table1_column2',$data)){
        		if (!empty($data['table1_column2']) && (strcmp($data['table1_column2'],"none") !== 0) && (strcmp($data['table1_column2'],"") !== 0)){
        			$select	->	where('T1.table1_column2 = ?',$data['table1_column2']); 
        		}
        	}
        
        	if (array_key_exists('table1_column3',$data)){
        		if (!empty($data['table1_column3']) && (strcmp($data['table1_column3'],"none") !== 0) && (strcmp($data['table1_column3'],"") !== 0)){
        			$select	->	where('T1.table1_column3 = ?',$data['table1_column3']); 
        		}
        	}
        
        	if (array_key_exists('table3_id_table3',$data)){
        		if (!empty($data['table3_id_table3']) && (strcmp($data['table3_id_table3'],"none") !== 0) && (strcmp($data['table3_id_table3'],"") !== 0)){
        			$select	->	where('T1.table3_id_table3 = ?',$data['table3_id_table3']); 
        		}
        	}
        
        }
        $this->showMe($select, 'Q');
        return $select;
    }

    /**
     * Method model
     *
     * Ulozani zaznamu do tabulky vazebni pro M:N
     */
    public function _postInsert($data)
    {
        try {
        	$useMnTble = array('table1hastable2');
        	foreach ($useMnTble as $value) {
        		$modelMN = $this->loadModel($value);
        		$primaryKeyMN = $modelMN->getStorage()->info('primary');
        		$primaryKey = $this->getStorage()->info('primary');
        
        		// pole pro kontrolu existence dat pro hodnoty vsech primarnich klicu MN table (vyjma pri)
        		$primaryKeyCheck = array_keys($primaryKey);
        		foreach ($primaryKeyCheck as $nameKey => $value) {
        			$primaryKeyCheck[$nameKey] = false;
        		}
        
        		foreach ($primaryKeyMN as $key => $namePriMN){
        			if (substr_count($namePriMN, strtolower($primaryKey[1])) == 1){
        				$data[$primaryKeyMN[$key]] = $data[current($primaryKey)];
        				$primaryKeyCheck[$namePriMN] = true;
        			}else {
        				$primaryKeyCheck[$namePriMN] = true;
        			}
        		}
        
        		if (array_product($primaryKeyCheck)){
        			foreach ($primaryKeyCheck as $nameKey => $value) {
        				if (!$value) {
        					throw new Exception('Formularova data neobsahuji neobsahuji klic '.$nameKey.'pro vazebni tabulku.');
        				}
        			}
        		}
        $row = $modelMN->getStorage()->createRow($data);
        	$id = $row->save();
        	}
        	} catch (Exception $e) {
        	// vyvolá vlastní výjimku
        	throw new Exception('Vložení nebylo úspěšné');
        }
    }

    /**
     * Method model
     *
     * Smazani zaznamu z tabulky vazebni M:N
     */
    public function _preUpdate($data)
    {
        $whereData = array();
        try {
        	$useMnTble = array('table1hastable2');
        	$primaryKey = $this->getStorage()->info('primary');
        	$index = 0;
        
        	foreach ($useMnTble as $value) {
        		$modelMN = $this->loadModel($value);
        		$primaryKeyMN = $modelMN->getStorage()->info('primary');
        		foreach ($primaryKeyMN as $key => $namePri){
        			// pridani do wheru klice MN, ktery prislusi jako primarni klic nevazebni tabulce
        			if (substr_count($namePri, strtolower($primaryKey[1])) == 1){
        				$whereData[$index][$data[$primaryKey[1]]] = $namePri;
        				$index++;
        				continue;
        				}
        			// pridani klicu v datech z formu pokud jsou stejne
        			if (key_exists($namePri, $data)){
        				//echo "<p>exists ".$namePri."</p>";
        				//$whereData[$index][$data[$namePri]] = $namePri;
        				//$index++;
        			}else {
        				//$whereData[$index][$data[$primaryKey[1]]] = $namePri;
        				//echo "<p>noexists ".$namePri." ".$primaryKey[1]."</p>";
        				//$index++;
        			}
        		}
        	}
        	$this->deleteMNroe($useMnTble,$whereData);
        	} catch (Exception $e) {
        	// vyvolá vlastní výjimku
        	throw new Exception('Vložení nebylo úspěšné');
        }
        return $data;
    }


}
