<?php
Class baseController {

  /**
   * @var object Registry
   */
  protected $registry;

  /**
   * @var array Subsite
   */
  protected $subsite = array();

  /**
   * @var object Template
   */
  protected $template;

  /**
   * @var string název controlleru
   */
  public $controller_name;

  /**
   * @var string název souboru controlleru (bez Controller)
   */
  public $controller_fname;
  
  /**
   * @var string popis controlleru
   */
  public $controller_info;

  public $entita_classname;

  public $item_to_page = 25;

  protected $html = '';
  protected $tpl  = 'page.tpl';

  function __construct() {
    $this->registry = Registry::getInstance();
    $this->template = $this->registry->template;
    $this->subsite['loaded'] = false;
    $this->registry->aktual_controller = $this->controller_name;
  }

  /**
   * metoda index musí být implmentována všemi Controllery
   */
  protected function index($args) {
  	die('akce Index není definována.');
  }

  /**
   * metoda getSubsite musí být implmentována všemi Controllery
   */
  protected function loadSubsite($id) {

    $result = dibi::query('SELECT  SUB.ID AS SUB_ID, TSUB.SLOZKA AS SUB_SLOZKA, SUB.NAZEV AS SUB_NAZEV, SUB.REWRITE_URL AS SUB_REWRITE_URL, SUB.ROBOTS AS SUB_ROBOTS,
	SUB.SERVER_TITLE AS SUB_SERVER_TITLE, SUB.SERVER_KEYWORDS AS SUB_SERVER_KEYWORDS, SUB.SERVER_DESCRIPTION AS 	
	SUB_SERVER_DESCRIPTION
		FROM SUBSITE SUB
		INNER JOIN SABLONA TSUB ON TSUB.ID = SUB.ID_SABL 
		WHERE SUB.ID = %i', $id);
    $res = $result->fetchAll();
    $tmp = $res[0]->getArrayCopy();
    $this->subsite['id']              = $tmp['SUB_ID'];
    $this->subsite['nazev']           = $tmp['SUB_NAZEV'];
    $this->subsite['tslozka']         = $tmp['SUB_SLOZKA'];
    $this->subsite['robots']          = $tmp['SUB_ROBOTS'];
    $this->subsite['rewrite_url']     = $tmp['SUB_REWRITE_URL'];
    $this->subsite['server_title']    = $tmp['SUB_SERVER_TITLE'];
    $this->subsite['server_keywords'] = $tmp['SUB_SERVER_KEYWORDS'];
    $this->subsite['server_description'] = $tmp['SUB_SERVER_DESCRIPTION'];
    $this->subsite['loaded']            = true;

  }

  /**
   * metoda getSubsite musí být implmentována všemi Controllery
   */
  protected function loadSubsiteByURL($url) {

    $result = dibi::query('SELECT SUB.ID AS SUB_ID, SUB.VYCHOZI, TSUB.SLOZKA AS SUB_SLOZKA,  SUB.NAZEV AS SUB_NAZEV,
    SUB.REWRITE_URL AS SUB_REWRITE_URL, SUB.ROBOTS AS SUB_ROBOTS, SUB.SERVER_TITLE AS SUB_SERVER_TITLE, 
    SUB.SERVER_KEYWORDS AS SUB_SERVER_KEYWORDS, SUB.SERVER_DESCRIPTION AS SUB_SERVER_DESCRIPTION 
    FROM SUBSITE SUB 
    LEFT JOIN SABLONA TSUB ON TSUB.ID = SUB.ID_SABL 
    WHERE SUB.REWRITE_URL = %s OR SUB.VYCHOZI = 1 ORDER BY SUB.VYCHOZI ASC', $url);

    $res = $result->fetchAll();
    $tmp = $res[0]->getArrayCopy();
    $this->subsite['id']              = $tmp['SUB_ID'];
    $this->subsite['nazev']           = $tmp['SUB_NAZEV'];
    $this->subsite['tslozka']         = $tmp['SUB_SLOZKA'];
    $this->subsite['robots']          = $tmp['SUB_ROBOTS'];
    $this->subsite['rewrite_url']     = $tmp['SUB_REWRITE_URL'];
    $this->subsite['server_title']    = $tmp['SUB_SERVER_TITLE'];
    $this->subsite['server_keywords'] = $tmp['SUB_SERVER_KEYWORDS'];
    $this->subsite['server_description'] = $tmp['SUB_SERVER_DESCRIPTION'];
    $this->subsite['vychozi'] 					= $tmp['VYCHOZI'];
    $this->subsite['loaded']            = true;

  }

  /**
   * metoda getSubsite musí být implmentována všemi Controllery
   */
  public function getSubsite($subs = 'classic') {

    if ( $this->subsite['loaded'] == false ) {
      $this->loadSubsiteByURL($subs);
    }
    
    $this->registry->subsite = $this->subsite;
    $this->registry->template->setPath($this->subsite['tslozka']);
    Debug::addPoint('Subsite loaded: '.$this->subsite['nazev'], $this->registry->subsite);

  }

  public function setView($tpl = '') {

    if (empty($tpl)) {
      $tpl = $this->tpl;
    }
    $this->getSubsite();
		$this->getMessage();

		if ($this->registry->subsite['vychozi'] == 1) {
			$this->template->setHTML('subs_link', URL);
		}
		else {
			$this->template->setHTML('subs_link', Tools::subsiteLink($this->registry->subsite['rewrite_url']));
		}
		$this->template->setHTML('subs_nazev', $this->registry->subsite['nazev']);
		if (method_exists($this, 'treeNav')) {
			$this->treeNav();
		}

		if (empty($this->registry->meta_title)) {
    	$this->registry->meta_title = $this->controller_name;
		}

    $this->template->setHTML('page_html', $this->html);

    $this->registry->html_view = $this->template->fetch($tpl, false, false);

    Debug::addPoint('setView');

  }
  /**
   * metoda index musí být implmentována všemi Controllery
   */
  //abstract function getview($args);

  public function getMessage() {
  	$message = $this->registry->message.(!empty($this->registry->to_message) ? '<br />'.$this->registry->to_message : $this->registry->to_message);
    $message_class = $this->registry->message_class;
    if (!empty($message)) {
    	$this->registry->template->setHTML('message', $message);
      if (empty($message_class)) {
      	$message_class = 'mess';
      }
      $this->registry->template->setHTML('message_class', $message_class);
      $this->registry->template->set('message_activ', (!empty($message)), TRUE);
    }
  }

  public function setMessage($message, $class = '', $persistent = 0) {

    Tools::setMessage($message, $class, $persistent);

  }

  public function myOrder(& $query, $entita = null,array $defaultOrder = array()) {
  	$my_ord = $this->registry->content_order;

		if (count($my_ord) == 0) {
  		$my_ord = $defaultOrder;
		}

  	if (count($my_ord) > 0) {
  		$order = array();
  		$test	 = array();
 			foreach($my_ord as $item) {
				$order[] = strtoupper($item['name']).' '.$item['ord'];
  			$test[] = $item['name'];
  		}

  		array_push($query,'ORDER BY %sql',implode(', ',$order));

  	}

  }

  function addLimit(& $query, & $filtr_query, $from, $ret_html = true, $settings = array()) {
  	$default = array(
  		'res_text' => 'Celkem ',
  		'res_1' => 'záznam',
  		'res_3' => 'záznamy',
  		'res_5' => 'záznamů',
  		'next_button' => 'Další stránka',
  		'prev_button' => 'Předchozí stránka',
  		'res_5' => 'záznamů',
  		'res_5' => 'záznamů',
  	);
  	
  	foreach($default as $key=>$value) {
  		if (!isset($settings[$key])) {
  			$settings[$key] = $value;
  		}
  	}
  	$count_query = array();
  	$count_query[] = 'SELECT COUNT(*) '.$from;
  	$count_query = array_merge($count_query, $filtr_query);
	
  	$page = @$_GET['page'];
  	if (is_null($page) OR $page <= 0) {
  		$page = 1;
  	}
  	array_push($filtr_query, 'LIMIT %i, %i', ($page-1) * $this->item_to_page, $this->item_to_page);
  	
  	$count = dibi::query($count_query)->fetchSingle();
  	$celkem = ceil($count/$this->item_to_page);

  	if ($celkem <= 0) {
  		$celkem = 1;
  	}
  	
  	$ret = '';
    switch ($count) {
  		case 1:
  			$ret .= '<br /><div class="celkem">'.$settings['res_text'].$count.' '.$settings['res_1'].'</div>';
  			break;

  		case 2:
  		case 3:
  		case 4:
  			$ret .= '<br /><div class="celkem">'.$settings['res_text'].$count.' '.$settings['res_3'].'</div>';
  			break;

  		default:
  			$ret .= '<br /><div class="celkem">'.$settings['res_text'].$count.' '.$settings['res_5'].'</div>';
  			break;
  			
  	}
		$ret .= '<div class="page_predchozi">&nbsp;';
  	$ret .= ($page > 1 ? '<input type="submit" name="page_predchozi" value="'.$settings['prev_button'].'"> ' : '');
  	$ret .= '</div><span class="str"> Stránka ';
  	$ret .= '<select name="page" onchange="this.form.submit();">';
  	for($i = 1; $i <= $celkem; $i++) {
  		$ret .= '<option value="'.$i.'" '.($i == $page ? 'selected="selected"' : '').'>&nbsp;'.$i.'&nbsp;</option>';
  	}
  	$ret .= '</select>';
  	$ret .= '&nbsp;z&nbsp;<b>'.$celkem.'</b></span>';
  	$ret .= ($page < $celkem ? '&nbsp;<input type="submit" name="page_dalsi" value="'.$settings['next_button'].'"> ' : '');  	
  	$ret .= '<hr class="cleaner" />';
  	if ($ret_html) {
  		return $ret;
  	}
  	else {
  		$this->template->setHTML('strankuj', true, true);
  		$this->template->setHTML('strankovani',$ret);
  	}
  }

	public function setFilter(& $filtr_query, $filtry = array(), $nastaveni = array()) {

		if (count($_POST) > 0 OR count($nastaveni) > 0) {
    	if (isset($_POST['all'])) {
    		$_POST = array();
    		$_POST = $nastaveni;
    	}
    	else {
    		$_POST = array_merge($_POST,$nastaveni);
    	}
    	if (!isset($_GET['all'])) {
    		if (isset($_GET['page_predchozi'])) {
    			$_GET['page']--;
    		}
    	  if (isset($_GET['page_dalsi'])) {
    			$_GET['page']++;
    		}

      	array_push($filtr_query,'WHERE 1');
      	foreach($filtry as $kkey=>$filtr) {
    		
        	if (isset($filtr['key'])) {
        		if (!isset($filtr['tab_name'])) {
      				$filtr['tab_name'] = 'E';
      			}
        		if (!empty($_POST[$filtr['key']]) OR !empty($_POST[$kkey]) OR is_numeric(@$_POST[$filtr['key']])) {
        			if ($filtr['sql'] == 'num') {
        				array_push($filtr_query,'AND '.$filtr['tab_name'].'.'.$filtr['key'].' = %i',$_POST[$filtr['key']]);
        			}
        			elseif ($filtr['sql'] == 'text') {
        				array_push($filtr_query,'AND '.$filtr['tab_name'].'.'.$filtr['key'].' LIKE %s',"%".$_POST[$filtr['key']]."%");
        			}
        		  elseif ($filtr['sql'] == 'in') {
        				array_push($filtr_query,'AND '.$filtr['tab_name'].'.'.$filtr['key'].' IN (%i)',$_POST[$filtr['key']]);
        			}

        		  elseif ($filtr['sql'] == 'gt') {
        				array_push($filtr_query,'AND '.$filtr['tab_name'].'.'.$filtr['key'].' >= %d',$_POST[$kkey]);
        			}
        		  elseif ($filtr['sql'] == 'lt') {
        				array_push($filtr_query,'AND '.$filtr['tab_name'].'.'.$filtr['key'].' <= %d',$_POST[$kkey]);
        			}
        		}
      		}
      	}
    	}
    	else {
    		$_GET = array();
    	}
    }
	}

	public function defaultSubsite() {
		$this->loadSubsite(DEFAULT_SUBSITE);
		$this->getSubsite();
		$this->setView();
	}

	public function thCss(& $css) {
		$my_ord = $this->registry->content_order;
  	if (count($my_ord) > 0) {
  		$order = array();
  		$test	 = array();
 			foreach($my_ord as $item) {
 				if ($item['ord'] != 'ASC') {
 					@$css[strtoupper($item['name'])] .= ' headerSortUp';
 				}
 				else {
 					@$css[strtoupper($item['name'])] .= ' headerSortDown';
 				}
 				
 			}
  	}
	}

  public function getTable($id = '#seznam', array $hlavicka, $zaznamy = array(), array $args = array(), array $td_class = array(), array $tl_tr = array(), array $th_class = array(), $my_info = '', $filtry = array(), $closeform = false) {

    $th_row = '';
    $td_row = '';

    if (count($tl_tr)) {
      if (!empty($th_class[$tl_tr[0]])) {
        $th_class[$tl_tr[0]] .= ' ui-corner-tl';  
      }
      else {
        $th_class[$tl_tr[0]] = ' ui-corner-tl'; 
      }

      if (!empty($th_class[$tl_tr[1]])) {
        $th_class[$tl_tr[1]] .= ' ui-corner-tr';  
      }
      else {
        $th_class[$tl_tr[1]] = 'ui-corner-tr';
      }
    }

    if (!empty($my_info)) {

      switch($my_info) {
        case 'multisort':
          $my_info = 'Pokud chcete řadit podle více sloupců, klikněte na první sloupec a při kliknutí na další položky podržte klávesu Shift';
          break;
        
        default:
          $my_info = $my_info;
          break;
      }

      $my_info = '<acronym class="f_r" title="'.$my_info.'"><img class="info" src="'.URL.'image/ico/32_info.png" alt="info" /></acronym>';
    }
    
///////////////////
    $action = URL.Application::myController('URL');
    if (substr($action,-1) != DIRSEP) {
      $action .= DIRSEP;
    }
		if (!strstr($action,SEND)) {
    	$action .= SEND;
    }

    $fargs['id']     = $id.'_form';
    $fargs['action'] = $action;
    $fargs['method'] = 'post';

    $form = '<form';
    foreach ($fargs as $key => $val) {
    	if (!empty($val)) {
        $form .= ' '.$key.'="'.$val.'"';
      }
    }
    $form .= '>';
    
//////////
    $table_HTML = $form.$my_info.'<table id="'.$id.'" cellspacing="0"';
    foreach ($args as $key => $val) {
      
      if (!empty($args[$key])) {
        $table_HTML .= ' '.$key.'="'.$args[$key].'"';
      }
      elseif (!empty($val)) {
        $table_HTML .= ' '.$key.'="'.$val.'"';
      }

    }
    $table_HTML .= '>';


    $filtr = '';
    foreach($hlavicka as $key=>$value) {

      $class = @$th_class[$key];
      if (!empty($class)) {
        $th_row .= '<th class="'.$th_class[$key].'">'.$value.'</th>';
      }
      else {
        $th_row .= '<th>'.$value.'</th>';
      }

      if (isset($filtry[$key])) {
      	$value = @$_POST[$key];
      	if (isset($filtry[$key]['key'])) {
      		$my_key = $filtry[$key]['key'];
      	}
      	else {
      		$my_key = $key;
      	}
      	switch($filtry[$key]['type']) {
      		case 'text':
      			$filtr .= '<td><input type="text" name="'.$my_key.'" size="'.$filtry[$key]['size'].'" value="'.$value.'" /></td>';
      			break;

      		case 'select':
      			$table_key = $filtry[$key]['opt'];
      			$filtr .= '<td><select name="'.$my_key.'" onchange="this.form.submit();"><option value="">&nbsp;-- vše -- </option>';
      			$result = dibi::query('SELECT ID, '.$table_key.' FROM ['.$filtry[$key]['table'].']');
      			foreach($result as $row) {
      				$filtr .= '<option value="'.$row['ID'].'" '.(@$_POST[$my_key] == $row['ID'] ? 'selected="selected"' : '').'>'.$row[$table_key].'</option>';
      			}
      			$filtr .= '</select></td>';
      			break;

      		case 'select_an':
      			$filtr .= '<td><select name="'.$filtry[$key]['key'].'" onchange="this.form.submit();">';
						$filtr .= '<option value="" '.((empty($_POST[$my_key]) AND !@is_numeric($_POST[$my_key])) ? 'selected="selected"' : '').'>&nbsp;-- vše -- </option>';
      			$filtr .= '<option value="0" '.((empty($_POST[$my_key]) AND @is_numeric($_POST[$my_key])) ? 'selected="selected"' : '').'>Ne</option>';
						$filtr .= '<option value="1" '.(@$_POST[$my_key] == 1 ? 'selected="selected"' : '').'>Ano</option>';
      			$filtr .= '</select></td>';
      			break;

      		case 'stav':
      			$filtr .= '<td><select name="STAV" onchange="this.form.submit();"><option value="">&nbsp;-- vše -- </option>';
      			if (isset($filtry[$key]['table'])){
      				$table = $filtry[$key]['table'];
      			}
      			else {
      				$table = $this->entita_classname;
      			}
      			$result = dibi::query('SELECT STAV_ID,NAZEV FROM [STAV] WHERE ENTITA = %s ORDER BY STAV_ID ASC',strtoupper($table));
      			foreach($result as $row) {
      				$filtr .= '<option value="'.$row['STAV_ID'].'" '.(@$_POST['STAV'] == $row['STAV_ID'] ? 'selected="selected"' : '').'>'.$row['NAZEV'].'</option>';
      			}
      			$filtr .= '</select></td>';
      			break;
      			
      		case 'submit':
      			$filtr .= '<td><input type="submit" name="'.$key.'" title="Filtrovat položky" value="Filtruj" /></td>';
      			break;

      		case 'all':
      			$filtr .= '<td><input type="submit" name="all" title="Zobrazit vše" value="Vše" /></td>';
      			break; 

      		case 'buttons':
      			$filtr .= '<td><input type="submit" name="'.$key.'" title="Filtrovat položky" value="Filtruj" />&nbsp;<input type="submit" name="all" title="Zobrazit vše" value="Vše" /></td>';
      			break;   
      			
      	}
      }
      else {
      	$filtr .= '<td>&nbsp;</td>';
      }

      $class = @$td_class[$key];
      if (!empty($class)) {
        $td_row .= '<td  class="'.$td_class[$key].'">\'.$row[\''.$key.'\'].\'</td>';
      }
      else {
        $td_row .= '<td>\'.$row[\''.$key.'\'].\'</td>';
      }

    }
    
    $table_HTML .= '<thead><tr>'.$th_row.'</tr>'.(count($filtry) > 0 ? '<tr>'.$filtr.'</tr>' : '').'</thead><tbody>';

    if ( count($zaznamy) ) {
      foreach($zaznamy as $row) {

        eval('$prom = print_r(\''.$td_row.'\',true);');
        $table_HTML .= '<tr class="zaznamy">'.$prom.'</tr>';

      }
    }
    else {
      $table_HTML .= '<tr><td colspan="'.count($hlavicka).'"><acronym class="f_r" title="Pro vámi zadaná kritéria nebyly nalezeny žádné záznamy"><img src="'.URL.'image/ico/24_pomoc.png" widht="20" height="20" alt="???" /></acronym> Není co zobrazit</td></tr>';
    }

    $table_HTML .= '</tbody></table>';
    
    if ($closeform) {
    	$table_HTML .= '</form>';
    }

    return $table_HTML;
  } 
	
}
?>