<?php
Abstract Class baseadminController extends baseController {

  public function index($args) {

    $this->seznam($args);

  }
  
  public function getSubsite($subs = 'admin') {
	
  	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);
  	}
		else {
 			Debug::addPoint('Subsite loaded');
		}

/*
    if (!empty($cesta)) {
      $this->registry->aktual_sablona_cesta = $cesta;
    }
    else {
      $this->registry->aktual_sablona_cesta = $this->subsite['tslozka'];
    }
*/
  }

  public function getLovQuery($table, $cols = array()) {
  	if (count($cols) == 0) {
  		$cols[] = 'ID';
  		$cols[] = 'NAZEV'; 
  	}
  	
  	$query[] = 'SELECT '.implode(',',$cols).' FROM ['.$table.'] E';
  	return $query;
  }

  public function getLOV($table,array $cols = array(),array $filtr = array(), array $order = array(), array $limit = array()) {

  	if (count($cols) == 0) {
  		$cols[] = 'ID';
  		$cols[] = 'NAZEV'; 
  	}
  	
  	$query[] = 'SELECT '.implode(',',$cols).' FROM ['.$table.']';

    if (count($filtr) > 0) {
  		array_push($query, 'WHERE %and', $filtr);
  	}
  	
    if (count($order) > 0) {
  		array_push($query, 'ORDER BY %by', $order);
  	}
  	
    if (count($limit) == 2) {
  		array_push($query, 'LIMIT %m', $limit);
  	}
  	
  	$result = dibi::query($query);	
  	return $result->fetchAssoc('ID');
  }

  public function setView($tpl = '') {

  	Debug::addPoint('setView '.$tpl);
    if (empty($tpl)) {
      $tpl = $this->tpl;
    }
    $this->getMainMenu();
    $this->getSubsite();

    $message = $this->registry->message.(!empty($this->registry->to_message) ? '<br />'.$this->registry->to_message : $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);
    }

    $this->registry->meta_title = $this->controller_name;
    $this->template->setHTML('controller_info', $this->controller_info);
    $this->template->setHTML('controller_name', $this->controller_name);
    $this->template->setHTML('page_html', $this->html);

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

    Debug::addPoint('setView');

  }

  public function getMainMenu() {

    $result = dibi::query('SELECT CA.ID, CA.CONTROLLER, CA.AKCE, CA.MENU_SUB
    FROM
    	UZIVATEL U 
	INNER JOIN UZIVATEL_ROLE UR ON UR.ID_UZIV = U.ID AND UR.STAV = 1
	INNER JOIN ROLE R ON R.ID = UR.ID_ROLE AND R.STAV = 1
	INNER JOIN ROLE_CAKCE RC ON RC.ID_ROLE = R.ID AND RC.STAV = 1
	INNER JOIN CONTROLLER_AKCE CA ON CA.ID = RC.ID_CAKCE AND CA.STAV = 1 AND CA.MENU_SUB IS NOT NULL 
	WHERE
		U.ID = %i 
		AND CA.CONTROLLER = %s
	ORDER BY CA.PRIORITA DESC'
	, $this->registry->user->id
	,Application::myController('controller'));

	$cnt = $result->count();
	if ($cnt > 0) {
	  $res = $result->fetchAssoc('ID');
	  $submenu = array();
	  foreach($res AS $r) {
	    $row = $r->getArrayCopy();
	    $li = array();
	    if ($this->registry->ca_id == $row['ID']) {
	      $li['li_class'] = 'active';
	      $li['a_class'] = 'active';
	    }
	    else {
	      $li['li_class'] = '';
	      $li['a_class'] = '';
	    }
	    $li['link'] = Tools::umenuLink($r);
	    $li['text'] = $row['MENU_SUB'];
	    $submenu[] = $li;
	  }
	  $this->registry->template->set('submenu', $submenu);
	  $this->registry->template->set('sub_menu_activ', true, true);

	}
	else {
	  $this->registry->template->set('sub_menu_activ', false, true);
	}
  }
  
  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, $before_table = '') {

    $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.$before_table.'<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;
  } 

  public function urlBackup($rewrite = false) {
    $back_url = $this->registry->__get(MY_URL_BACK);
    if ($rewrite OR empty($back_url)) {
      $this->registry->addPersistent(MY_URL_BACK, Application::myController('URL'));
    }
  }
  
  public function geturlBackup($ico = ICO_ZPET, $text = 'Zpět') {
    $ret = '';
    $back_url = $this->registry->__get(MY_URL_BACK);
    $this->registry->unsetPersistent(MY_URL_BACK);
    if (!empty($back_url)) {
      $ret = '<a class="backlink" href="'.URL.$back_url.'">'.$ico.' '.$text.' </a> ';
    }
    return $ret;
  }  
  
  public function clrurlBackup() {
    $this->registry->remove(URL_BACK);
  }

  public function naruseni() {
    throw new AppliException(5, ' Nemáte oprávnění pro operaci, kterou se pokoušíte provést.<br />
          	Zaznaménán pokus o narušení integrity systému.');
  }

  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'];
  		}
  		if ($entita) {
  			if ($entita->dbCols($test)) {
  				array_push($query,'ORDER BY %sql',implode(', ',$order));
  			}
  			else {
  				throw new Appliexception(1, 'Některé pole podle kterého chcete řadit neexistuje');
  			}
  		}
  		else{
  			array_push($query,'ORDER BY %sql',implode(' ',$order));
  		}	
  	}
  }

	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';
 				}
 				
 			}
  	}
	}

  function addLimit(& $query, & $filtr_query,& $entita, $ret_html = true) {
  	$count_query = array();
  	$count_query[] = 'SELECT COUNT(*) FROM ['.$entita->table.'] E';
  	$count_query = array_merge($count_query, $filtr_query);
	
  	$page = @$_POST['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">Celkem '.$count.' záznam</div>';
  			break;

  		case 2:
  		case 3:
  		case 4:
  			$ret .= '<br /><div class="celkem">Celkem '.$count.' záznamy</div>';
  			break;

  		default:
  			$ret .= '<br /><div class="celkem">Celkem '.$count.' záznamů</div>';
  			break;
  			
  	}
		$ret .= '<div class="page_predchozi">&nbsp;';
  	$ret .= ($page > 1 ? '<input type="submit" name="page_predchozi" value="Předchozi stránka"> ' : '');
  	$ret .= '</div> 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 .= 'z  <b>'.$celkem.'</b>';
  	$ret .= ($page < $celkem ? '&nbsp;<input type="submit" name="page_dalsi" value="Další stránka"> ' : '');  	
  	$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,$entita, $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($_POST['page_predchozi'])) {
  			$_POST['page']--;
  		}
  	  if (isset($_POST['page_dalsi'])) {
  			$_POST['page']++;
  		}

    	array_push($filtr_query,'WHERE 1');
    	foreach($entita->filtry as $kkey=>$filtr) {
    		if (isset($filtr['key'])) {
      		if (!empty($_POST[$filtr['key']]) OR !empty($_POST[$kkey]) OR is_numeric(@$_POST[$filtr['key']])) {
      		if (!isset($filtr['tab_name'])) {
      				$filtr['tab_name'] = 'E';
      			}

      			if ($filtr['sql'] == 'num') {
      				array_push($filtr_query,'AND E.'.$filtr['key'].' = %i',$_POST[$filtr['key']]);
      			}
      			elseif ($filtr['sql'] == 'text') {
      				array_push($filtr_query,'AND E.'.$filtr['key'].' LIKE %s',"%".$_POST[$filtr['key']]."%");
      			}
      		  elseif ($filtr['sql'] == 'in') {
      				array_push($filtr_query,'AND E.'.$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'].' <= %t',$_POST[$kkey].' 23:59:59');
        			}
      		}
    		}
    	}
    }
	}
  
/* 
	public function setFilter(& $filtr_query,$entita, $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($_POST['page_predchozi'])) {
  			$_POST['page']--;
  		}
  	  if (isset($_POST['page_dalsi'])) {
  			$_POST['page']++;
  		}

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