<?php
require_once 'HTML/Table.php';
/*********************************************************************/
/*	Chyba v PHP 
 * pokud pouziji funkce pro logovani 
 * MyWeb_Log_ApplicationLogger::addLog($this,1,4);
 * MyWeb_plugin::showMe(MyWeb_Log_ApplicationLogger::showLog(),'Zend_View_Helper_Table');
 * pak funkce get_class_methods volana v tride MyWeb_Log_ApplicationLogger nenalezne vsechny metodt ve
 * tride Zend_View_Helper_Table ale pouze public metody
 * 
 * pokud funkci get_class_methods volam v aktualni tride pak vse funguje sparvne
 * 
 * duledek:
 * overit zdali to plati pro dany navrhovy vzor view_helper a nebo jestli to plati i pro jine
 * overit jesli je mozne logovat v jinych tridach privat funkce 
 */

/**
 * 
 * Trida zajistuje vzykresleni tabulky
 * @author aaa
 * 
 */
class Zend_View_Helper_Table extends Zend_View_Helper_Abstract
{
	private $table;
	private $selectColumn;//sloupce vybrane pro zobrayeni v tabulce
	private $head;//jmena sloupcu tabulky
	private $paginatorData;
	private $hidden;
	/*********************************************/
	//		$hidden[index] = name of column;
	//		$hidden[0] = 'id_article';
	//		$hidden[1] = 'article_text';
	/*********************************************/
	private $links;
	private $caption;
	private $columnValue;
	
	
	/**
	 * metoda volana z view
	 * @param $paginatorData
	 * @param $head
	 */
	public function Table($paginatorData,$column,$columnValue,$head,$hidden,$caption = NULL,$links = "nic"){
		
		//MyWeb_Log_ApplicationLogger::addLog($this,1,4);
        //MyWeb_plugin::showMe(MyWeb_Log_ApplicationLogger::showLog(),'Zend_View_Helper_Table');
        
		$this->head=$head;//$head['nameHeader']
		$this->selectColumn=$column;
		$this->columnValue = $columnValue;
		$this->hidden = $hidden;
		$this->links=$links;
		$this->paginatorData=$paginatorData;
		$this->caption=$caption;
		$this->createTable();
		return '<div class = "table">'.$this->table->toHtml().'</div>';
	}
	
	
	
	/**
	 * nastavi tabulce caption
	 * @param string $caption
	 */
	public function setCaption($caption){
		//MyWeb_Log_ApplicationLogger::addLog($this,2,4);
        //MyWeb_plugin::showMe(MyWeb_Log_ApplicationLogger::showLog(),'Zend_View_Helper_Table');
        
		$this->table->setCaption($caption);
	}
	
	
	
	/**
	 * vytvori tabulku
	 * @param paginator $paginatorData
	 */
	private function createTable(){
		//MyWeb_Log_ApplicationLogger::addLog($this,3,4);
        //MyWeb_plugin::showMe(MyWeb_Log_ApplicationLogger::showLog(),'Zend_View_Helper_Table');
        
		//$linksTable[index_sloupce]=modul,kontroler,akce,
		$data1 = $this->paginatorToArray($this->paginatorData);
		$data2 = $this->selectData($data1);
		try {
			$this->validationValueLink();
			$data2 = $this->createLink($data2,$data1);
			$data2 = $this->valueCell($data2,$this->columnValue);
			$data2 = $this->createHidden($data2,$data1, $this->columnValue);
		}
		catch (Exception $e){
    		echo $e->getMessage();
    	}
    	$this->table = new HTML_Table();
		$this->setOptions($data2);
		$this->addInputData($data2);
	}
	
	/**
	 * ze vstupnich dat selectu vybere pozadovane sloupce
	 * @param array $data
	 */
	private function selectData($data)
	{
		if (!is_null($this->selectColumn) && (is_array($this->selectColumn))){
			foreach ($data as $row => $column){
  				foreach ($column as $name_column => $value){
  					if (FALSE === array_search($name_column, $this->selectColumn)){
  						unset($data[$row][$name_column]);
  						reset($data);
  					}
    			}
			}
		}
		return $data;
	}
	
	/**
	 * nastavuje vlastnosti tabulky
	 * @param array $data
	 */
	private function setOptions($data){
		
		//MyWeb_Log_ApplicationLogger::addLog($this,4,4);
        //MyWeb_plugin::showMe(MyWeb_Log_ApplicationLogger::showLog(),'Zend_View_Helper_Table');
        
		$colgroup = $this->createArrayColGroup($data);
		$attributes = 'span="3" class="group1"';
		$this->table->setColGroup($colgroup, $attributes);
		$this->table->addBody();
		$this->createThead($data[0]);
		$this->table->setRowAttributes(0, "span=col");
		if (!is_null($this->caption)){
			$this->table->setCaption($this->caption);
		}
	}
	
	
	
	/**
	 * priada vstupni data do tabulky
	 * @param array $data
	 */
	private function addInputData($data){
		
		//MyWeb_Log_ApplicationLogger::addLog($this,5,4);
        //MyWeb_plugin::showMe(MyWeb_Log_ApplicationLogger::showLog(),'Zend_View_Helper_Table');
        
		// addCol a addRow zvlada pouze vstupni pole indexovane nikoli asociativni
		
		$i=0;
		foreach ($data as $row => $column){
			
  			foreach ($column as $name_column => $value){
  				//echo "<p>addInputData".$value."</p>";
     				 $rowArrayIndex[$i]=$value;
     				 $i++;
    		}
			if (($row % 2) == 0){
    			$this->table->addRow($rowArrayIndex,"class=odd");
    		}else {
    			$this->table->addRow($rowArrayIndex);
    		}
    		$i=0;
		}
	}
	
	
	
	/**
	 * vytvory coGroup
	 * @param array $data
	 */
	private function createArrayColGroup($data){
		
		//MyWeb_Log_ApplicationLogger::addLog($this,6,4);
        //MyWeb_plugin::showMe(MyWeb_Log_ApplicationLogger::showLog(),'Zend_View_Helper_Table');
        
		$index = 0;
		$colGroup=array();
		foreach ($data as $row => $column){
			$colGroup[]="id = id_col_".$index++;
		}
		return $colGroup;
	}
	
	
	
	/**
	 * vytvory th jmena sloupcu
	 * @param $row
	 * @param $head
	 */
	private function createThead($row){
		
		//MyWeb_Log_ApplicationLogger::addLog($this,7,4);
        //MyWeb_plugin::showMe(MyWeb_Log_ApplicationLogger::showLog(),'Zend_View_Helper_Table');
        
		$col=0;
		$newHeaderTable = array();
		foreach ($row as $name_column => $value){
			if (count($this->head['nameHeader'] ) >= $col){//pocet ciklu bude urcen velikosti pole thead a ne polem tvorici tabulku
				if(is_null($this->head['nameHeader'])){
					$this->table->setHeaderContents(0, $col, $this->createLinkHead($name_column));
					//echo "<p>".$name_column."</p>";
				}else {
					$this->table->setHeaderContents(0, $col, $this->createLinkHead($this->head['nameHeader'][$col]));
					//echo "<p>".$select."</p>";
				}
			}else {
				break;
			}
			$col++;
		}
	}
	
	/**
	 * matoda vytvori odkazi ze jmen sloupcu tabulky pro serazeni
	 * Enter description here ...
	 */
	private function createLinkHead($valueLink){
		
		$request = Zend_Controller_Front::getInstance()->getRequest();
		$actionName = $request->getActionName();
		$controllerName = $request->getControllerName();
		$ModulName = $request->getModuleName();
		
		//na zaklade hodnoty pole chci ziskat klic
		$key = NULL;
		if (is_null($this->head) || !is_array($this->head) || !array_key_exists('nameHeader', $this->head)){
			$this->head['nameHeader'] = $this->selectColumn;
		}
		foreach ($this->head['nameHeader'] as $columnName) {
			if ($columnName == $valueLink) {
				$key = key($this->head['nameHeader']);
				break;
			}
		}
		$optionsUrl = array(
								'controller' => $controllerName,
		 						'action' => $actionName,
		 						's'=>$this->selectColumn[$key]);
		
		if ($request->getParam('page',false)){
			$page = $request->getParam('page',false);
			$optionsUrl['page'] = $page;
		}
		if ((false !== $request->getParam('d',false)) && ( $request->getParam('d',false) < 2)){
			$sortIndex = (int) $request->getParam('d',false) + 1;
		}else {
			$sortIndex = 0;
		}
		$url = new Zend_View_Helper_Url();
		$request = Zend_Controller_Front::getInstance()->getRequest();
		$headerLink = '';
		$optionsUrl['d'] = $sortIndex;
		$headerLink = "<a href = ".$url->url(array_merge($this->getLinkParams(),$optionsUrl), 'default', true).">".$valueLink."</a>";
		return $headerLink;
	}
	
	/**
	 * prevede vstupni data z paginatoru na pole
	 * @param paginator $paginator
	 */
	public function paginatorToArray($paginator){
		
		//MyWeb_Log_ApplicationLogger::addLog($this,8,4);
        //MyWeb_plugin::showMe(MyWeb_Log_ApplicationLogger::showLog(),'Zend_View_Helper_Table');
        
		$index=0;
		$array_table=array();
		foreach ($paginator as $item){
			//$item['id_user']."\t".
			foreach ($item as $name_column => $value){
				$array_table[$index][$name_column]=$value;
			}
			$index++;
		}
		return $array_table;
	}
	
	
	
	/**
	 * metoda vraci hodnoty predane odkazem k opetovnemu predani
	 * a vypusti hodnoty uvedene v poli pro odstraneni
	 */
	private function returnGetString()
	{
		$request = Zend_Controller_Front::getInstance()->getRequest();
        $inGetParams = $request->getParams();
        $arrayRemoveValue = array('controller','action','module','sourceController','sourceAction');
        foreach ($arrayRemoveValue as $value) {
        	if (array_key_exists($value, $inGetParams)){
        		unset($inGetParams[$value]);
        		reset($inGetParams);
        	}
        }
        $stringParams = '';
        foreach ($inGetParams as $key => $value){
        	$stringParams .= '/'.$key.'/'.$value;
        }
        return $stringParams;
	}
	
	/**
	 * 
	 * vytvori retezec pro promene v odkazu
	 * @param $data
	 * @param $data1
	 */
	private function createGetString($data,$data1){
		$getString = '';
		if (TRUE === is_array($this->links)){
			foreach ($data1 as $index_row => $value_row){
				foreach ($this->links as $nameColumn => $link){
					if (is_array($link) && (array_key_exists('get', $link))){
						if(is_array($link['get'])){
							foreach ($link['get'] as $index => $columnGet){
								if (!is_null($columnGet)){
									if (array_key_exists($columnGet, $data1[$index_row])){
										$data[$index_row][$nameColumn] .= '/'.$columnGet.'/'.$data1[$index_row][$columnGet];
									}
								}
							}
							$data[$index_row][$nameColumn] .= '/';
						}
					}
					$data[$index_row][$nameColumn] .= '">'.$value_row[$nameColumn].'</a>';
				}
			}
		}
		return $data;
	}
	
	
	
	/**
	 * vytvori odkaz ze sloupce tabulky
	 * @param $data
	 * @param $column
	 */
	//$links['id_state'][0] = 'state_state';
	private function createLink($data,$data1){
		$url = new Zend_View_Helper_Url();
        $id_column='';
		if (TRUE === is_array($this->links)){
			foreach ($data as $index_row => $value_row){
				//$columnIndex = 0;
				foreach ($this->links as $name_column => $link){
					if (array_key_exists('link', $link)){
						//*** pokud se jedna o odkaz zavirajici cele okno
						if (strcmp($link['link'], 'close.window') === 0){
							//$columnIndex++;
							$data[$index_row][$name_column]='<a id="button'.$index_row.'" href="'.'javascript: self.close()';
						}else {
							//*** odkazi s pouze id v poli get
							$id_column = $name_column;
							if (array_key_exists($name_column, $value_row)){
								$data[$index_row][$name_column] = '<a id="button'.$index_row.'" href="'.$this->links[$name_column]['link'];
							}
						}
					}
				}
			}
		}
		$data = $this->createGetString($data,$data1);
		return $data;
	}
	
	
	/**
	 * funkce vytvori pole dane delky a naplni jej
	 * danou hodnotou
	 * 
	 * @param int $count
	 * @param mixed $value
	 */
	private function createArray($count,$value,$defaultValue,$keys){
		if (!is_array($value)){
			for ($indexArray = 0; $indexArray < $count; $indexArray++){
				$array[$indexArray] = $value;
			}
		}else {
			foreach ($keys as $key => $valueKey) {
				foreach ($value as $key => $valueCell) {
					if ($valueKey == $key){
						$array[$valueKey] = $valueCell;
					}else {
						$array[$valueKey] = $defaultValue;
					}
				}
			}
		}
		return $array;
	}
	
	/**
	 * 
	 * funkce doplni input do sloupcu s hodnotou
	 * @param $data
	 * @param $column
	 */
	private function valueCell($data,$column){
		if (!is_null($column)){
			if (count($column) != count($this->selectColumn)){
				$array = $this->createArray(count($this->selectColumn),$column,'false',$this->selectColumn);
			}
			//$indexColumn = 0;
			foreach ($array as $index_column => $value){
				if ('true' === $value){
					foreach ($data as $index_row => $value_row){
						$data[$index_row][$index_column] = '<input id="in'.$index_row.'" type="hidden" value="'.$data[$index_row][$index_column].'"/>'.$data[$index_row][$index_column];
						//$data[$index_row][$index_column] = $data[$index_row][$index_column] . '<input id="inid'.$index_row.$index_row.'" type="hidden" value="'.'hidden'.'">';
					}
				}
				//$indexColumn++;
			}
		}
		return $data;
	}
	
	
	
	
	/**
	 * 
	 * k danym polozkam prida pohle hidden s danymi hodnotami
	 * @param array $data
	 * @param array $column
	 */
	private function createHidden($data,$data1,$column)
	{
		if (!is_null($column)){
			if (count($column) != count($this->selectColumn)){
				$array = $this->createArray(count($this->selectColumn),$column,'false',$this->selectColumn);
			}
		
			//$indexColumn = 0;
			foreach ($array as $index_column => $value){
				if ('true' === $value){
					foreach ($data as $index_row => $value_row){
						foreach ($this->hidden as $keyHidden => $valueHidden){
							// prida pole hidden pro nazev 3 4
							$indexHidden = count($this->hidden)+$keyHidden;
							$data[$index_row][$index_column] .= '<input id="inid'.$index_row.$indexHidden.'" type="hidden" value="'.$valueHidden.'">'
																  .'<input id="inid'.$index_row.$keyHidden.'" type="hidden" value="'.$data1[$index_row][$valueHidden].'">';
																								// prida pole hidden pro hodnotu 1 2
						}
					}
				}
				//$indexColumn++;
			}
		}
		return $data;
	}
	
	
	
	/**
	 * metoda kontroluje, aby sloupec
	 * nemohl byt hodnotou a odkazem zaroveň a zdali sloupec existuje
	 * !!! predelat na funkce hledani jehly v kupce sena
	 */
	private function validationValueLink(){
		$columnExistsLink = FALSE;
		$columnExistsValue = FALSE;
		if (is_array($this->links)){
		foreach ($this->links as $nameColumnLink => $value){
			$columnExistsValue = FALSE;
			if (is_array($this->columnValue)){
			foreach ($this->columnValue as $nameColumnValue => $value){
				$columnExistsLink = FALSE;
				if (is_array($this->selectColumn)){
				foreach ($this->selectColumn as $key => $nameColumn){
					//echo "<p>"."$nameColumn"."dddddd".$nameColumnLink."</p>";
					if (strcmp($nameColumnValue, $nameColumn) === 0){
						$columnExistsValue = TRUE;
					}
					if (strcmp($nameColumnLink, $nameColumn) === 0){
						$columnExistsLink = TRUE;
					}
				}
				if (!$columnExistsLink){
    					$zprava = "Zend_View_Helper_Table: Not exists column name for link: "."\n";
        				throw new Exception($zprava);
				}
				if (!$columnExistsValue){
    					$zprava = "Zend_View_Helper_Table: Not exists column name for value: "."\n";
        				throw new Exception($zprava);
				}
				if (strcmp($nameColumnLink, $nameColumnValue) === 0){
    					$zprava = "Zend_View_Helper_Table: Same name column for link and value: "."\n";
        				throw new Exception($zprava);
				}
			}
		}
	}
		}}}
		
		
	/**
	 * metoda vraci parametry v adrese umistene za jmenem kontrolleru a akce
	 * Enter description here ...
	 */
	private function getLinkParams()
	{
		$request = Zend_Controller_Front::getInstance()->getRequest();
        $getVariables = array();
        $path = explode('index.php/'.$request->getControllerName().'/'.$request->getActionName().'/', $request->getRequestUri());
        if (!empty($path[1])){
        	$path = explode('/', $path[1]);
        	foreach ($path as $key => $value){
        		if ((1 == ($key % 2)) && ($key != 0)){
        			$getVariables[$path[$key-1]] = $value;
        			//echo "<p>klic ".$path[$key-1]." ".$value."</p>";
        		}
        	}
        	 return $getVariables;
        }
        return array();
	}
}