<?php

include_once(dirname(__FILE__).'/../../Common/Global.php');

class PageIS extends Page
{
  var $FullTitle = 'Správa dat';
  var $ShortTitle = 'Správa dat';
  var $ParentClass = 'PagePortal';
  var $MenuItems;
  var $HideMenu = false;

  function Show()
  {
    if(!$this->System->User->CheckPermission('IS', 'Manage'))
      return('Nemáte oprávnění');
    $this->System->FormManager->ShowRelation = true;

    if(array_key_exists('a', $_GET)) $Action = $_GET['a'];
      else $Action = '';
    if(array_key_exists('t', $_GET)) $Table = $_GET['t'];
      else $Table = '';
    if(array_key_exists('i', $_GET)) $ItemId = $_GET['i'];
      else $ItemId = 0;

    if($Action == 'list') $Content = $this->ShowList($Table);
    else if($Action == 'select') $Content = $this->ShowSelect($Table);
    else if($Action == 'mapselect') $Content = $this->ShowMapSelect($Table);
    else if($Action == 'edit') $Content = $this->ShowEdit($Table, $ItemId);
    else if($Action == 'add') $Content = $this->ShowAdd($Table);
    else if($Action == 'addsub') $Content = $this->ShowAddSub($Table);
    else if($Action == 'view') $Content = $this->ShowView($Table, $ItemId);
    else if($Action == 'delete') $Content = $this->ShowDelete($Table, $ItemId);
    else $Content = $this->Dashboard();
    if($this->HideMenu == false)
    {
      $Output = '<table style="width: 100%"><tr><td style="width: 20%; vertical-align: top;">';
      $Output .= '<strong>Nabídka:</strong>'.$this->ShowMenu();
      $Output .= '</td><td style="width: 80%; vertical-align: top;">';
      $Output .= $Content;
      $Output .= '</td></tr></table>';
    } else $Output = $Content;

    return($Output);
  }

  function Dashboard()
  {
    $Output = '<strong>Nástěnka:</strong><br/>';
    $DbResult = $this->Database->select('Task', 'COUNT(*)', 'Progress < 100');
    $DbRow = $DbResult->fetch_row();
    $Output .= 'Nedokončených úkolů: '.$DbRow['0'].'<br/>';
    $DbResult = $this->Database->select('Member', 'COUNT(*)', '1');
    $DbRow = $DbResult->fetch_row();
    $Output .= 'Zákazníků: '.$DbRow['0'].'<br/>';
    $DbResult = $this->Database->select('Subject', 'COUNT(*)', '1');
    $DbRow = $DbResult->fetch_row();
    $Output .= 'Subjektů: '.$DbRow['0'].'<br/>';
    $DbResult = $this->Database->select('User', 'COUNT(*)', '1');
    $DbRow = $DbResult->fetch_row();
    $Output .= 'Uživatelů: '.$DbRow['0'].'<br/>';
    $DbResult = $this->Database->select('NetworkDevice', 'COUNT(*)', '1');
    $DbRow = $DbResult->fetch_row();
    $Output .= 'Registrovaných zařízení: '.$DbRow['0'].'<br/>';
    $DbResult = $this->Database->select('FinanceOperation', 'SUM(Value)', '1');
    $DbRow = $DbResult->fetch_row();
    $Output .= 'Stav placení: '.$DbRow['0'].'<br/>';
    $DbResult = $this->Database->select('FinanceBankImport', 'COUNT(*)', 'FinanceOperation IS NULL');
    $DbRow = $DbResult->fetch_row();
    $Output .= 'Nezpárovaných plateb: '.$DbRow['0'].'<br/>';
    return($Output);
  }

  function ShowEdit($Table, $Id)
  {
  	$this->ShortTitle .= ' - Úprava '.$Table;
    $Output = '';
    if(defined('NEW_PERMISSION') and !$this->System->User->CheckPermission($this->TableToModule($Table), 'Write'))
      return('Nemáte oprávnění');
    if(array_key_exists('o', $_GET))
    {
      if($_GET['o'] == 'save')
      {
        $Form = new Form($this->System->FormManager);
        $Form->SetClass($Table);
        $Form->LoadValuesFromForm();
        $this->ShortTitle .= ' - úprava '.$Form->Definition['Title'];
        try {
          $Form->Validate();
          $Form->SaveValuesToDatabase($Id);
          $Values = $Table.': '.str_replace('=>', '=', str_replace('array', '', var_export($Form->Values, true)));
          $this->System->ModuleManager->Modules['Log']->NewRecord('IS', 'Edit', $Values);
          $Output .= $this->SystemMessage('Úprava položky', 'Položka upravena');
          $Output .= $this->ShowView($Table, $Id);
        } catch (Exception $E)
        {
        	$Output .= $this->SystemMessage('Úprava položky', 'Položku se nepodařilo uložit. Opravte problém a opakujte akci.<br/>'.$E->getMessage());
          $Form->OnSubmit = '?a=edit&amp;t='.$Table.'&amp;i='.$_GET['i'].'&amp;o=save';
          $Output .= $Form->ShowEditForm();
          $Output .= '<ul class="ActionMenu">';
          $Output .= '<li><a href="?a=view&amp;t='.$Table.'&amp;i='.$Id.'"><img alt="Prohlížet" title="Prohlížet" src="'.
            $this->System->Link('/images/view.png').'"/>Prohlížet</a></li>';
          $Output .= '<li><a href="?a=list&amp;t='.$Table.'"><img alt="Seznam" title="Seznam" src="'.
            $this->System->Link('/images/list.png').'"/>Seznam</a></li>';
          $Output .= '<li><a href="?a=delete&amp;t='.$Table.'&amp;i='.$Id.'" onclick="return confirmAction(\'Opravdu smazat položku?\');"><img alt="Odstranit" title="Odstranit" src="'.
            $this->System->Link('/images/delete.png').'"/>Odstranit</a></li>';
          $Output .= '</ul>';
         }
      }
    } else
    {
      $Form = new Form($this->System->FormManager);
      $Form->SetClass($Table);
      $Form->LoadValuesFromDatabase($Id);
      $this->ShortTitle .= ' - úprava '.$Form->Definition['Title'];
      $Form->OnSubmit = '?a=edit&amp;t='.$Table.'&amp;i='.$_GET['i'].'&amp;o=save';
      $Output .= $Form->ShowEditForm();
      $Output .= '<ul class="ActionMenu">';
      $Output .= '<li><a href="?a=view&amp;t='.$Table.'&amp;i='.$Id.'"><img alt="Prohlížet" title="Prohlížet" src="'.
      $this->System->Link('/images/view.png').'"/>Prohlížet</a></li>';
      $Output .= '<li><a href="?a=list&amp;t='.$Table.'"><img alt="Seznam" title="Seznam" src="'.
        $this->System->Link('/images/list.png').'"/>Seznam</a></li>';
      $Output .= '<li><a href="?a=delete&amp;t='.$Table.'&amp;i='.$Id.'" onclick="return confirmAction(\'Opravdu smazat položku?\');"><img alt="Odstranit" title="Odstranit" src="'.
        $this->System->Link('/images/delete.png').'"/>Odstranit</a></li>';
      $Output .= '</ul>';
    }
    return($Output);
  }

  function ShowDelete($Table, $Id)
  {
    $Output = '';
    if(defined('NEW_PERMISSION') and !$this->System->User->CheckPermission($this->TableToModule($Table), 'Write'))
      return('Nemáte oprávnění');
    $this->ShortTitle .= ' - odstranění '.$Table;
    $DbResult = $this->Database->select($Table, '*', '`Id`='.$Id);
    if($DbResult->num_rows > 0)
    {
    	$DbRow = $DbResult->fetch_assoc();
    	try {
        $this->Database->delete($Table, '`Id`='.$Id);
        $Values = $Table.': '.str_replace('=>', '=', str_replace('array', '', var_export($DbRow, true)));
        $this->System->ModuleManager->Modules['Log']->NewRecord('IS', 'Delete', $Values);
        $Output .= $this->SystemMessage('Smazání položky', 'Položka odstraněna');
      } catch (Exception $E)
      {
      	$Output .= $this->SystemMessage('Smazání položky', 'Položku se nepodařilo smazat. Pravděpodobně na ni závisejí další položky.');
      }
    } else $Output .= $this->SystemMessage('Smazání položky', 'Položka nenalezena');
    $Output .= $this->ShowList($Table);
    return($Output);
  }

  function ShowAdd($Table, $Actions = array())
  {
    $Output = '';
    if(defined('NEW_PERMISSION') and !$this->System->User->CheckPermission($this->TableToModule($Table), 'Write'))
      return('Nemáte oprávnění');
    if(array_key_exists('o', $_GET))
    {
      if($_GET['o'] == 'save')
      {
        $Form = new Form($this->System->FormManager);
        $Form->SetClass($Table);
        $Form->LoadValuesFromForm();
        $this->ShortTitle .= ' - přidání '.$Form->Definition['Title'];
        try {
          $Form->Validate();
          if(array_key_exists('BeforeInsert', $Form->Definition))
          {
            $Class = $Form->Definition['BeforeInsert'][0];
            $Method = $Form->Definition['BeforeInsert'][1];
            $this->Values = $Class->$Method($Form);
          }
          $Form->Validate();
          $Form->SaveValuesToDatabase(0);
          $Id = $this->Database->insert_id;
          $Values = $Table.': '.str_replace('=>', '=', str_replace('array', '', var_export($Form->Values, true)));
          $this->System->ModuleManager->Modules['Log']->NewRecord('IS', 'Add', $Values);
          $Output .= $this->SystemMessage('Přidání položky', 'Nová položka vytvořena');
          $Output .= $this->ShowView($Table, $Id, $_GET['a'] == 'addsub');
          if(array_key_exists('AfterInsert', $Form->Definition))
          {
            $Class = $Form->Definition['AfterInsert'][0];
            $Method = $Form->Definition['AfterInsert'][1];
            $this->Values = $Class->$Method($Form);
          }
          // Add action to update caller form
          if($_GET['a'] == 'addsub')
          {
            $Type = $this->System->FormManager->FormTypes[$_GET['rt']];
            $DbResult = $this->Database->select($Table, '('.$Type['Name'].') AS Name', 'Id='.$Id);
            $DbRow = $DbResult->fetch_assoc();
            $Actions[] = '<a href="javascript:window.close();" onclick="add_select_item('.$Id.',&quot;'.$DbRow['Name'].'&quot;,&quot;'.
              $_GET['r'].'&quot;); set_return('.$Id.',&quot;'.
              $_GET['r'].'&quot;);"><img alt="Vybrat" title="Vybrat" src="'.
              $this->System->Link('/images/select.png').'"/> Vybrat</a>';
          }

        //$this->Database->update($Table, 'Id='.$Id,
        //  array('UserCreate' => $this->System->User->User['Id'],
        //  'TimeCreate' => 'NOW()'));
        } catch (Exception $E)
        {
        	$Output .= $this->SystemMessage('Přidání položky', 'Položku se nepodařilo přidat. Opravte problém a opakujte akci.<br/>'.$E->getMessage());
        	$Form->OnSubmit = '?a=add&amp;t='.$Table.'&amp;o=save';
          $Output .= $Form->ShowEditForm();
          $Actions[] = '<a href="?a=list&amp;t='.$Table.'"><img alt="Seznam" title="Seznam" src="'.
            $this->System->Link('/images/list.png').'"/>Seznam</a>';
        }
      }
    } else
    {
      $Form = new Form($this->System->FormManager);
      $Form->SetClass($Table);
      $this->ShortTitle .= ' - přidání '.$Form->Definition['Title'];
      // Load presets from URL
      foreach($_GET as $Key => $Value)
      if(substr($Key, 0, 6) == 'preset')
      {
        $Key = substr($Key, 6);
        if(($Key != '') and array_key_exists($Key, $Form->Values))
          $Form->Values[$Key] = $Value;
      }
      if(array_key_exists('r', $_GET)) $URL = '&amp;r='.$_GET['r'].'&amp;rt='.$_GET['rt'];
        else $URL = '';
      $Form->OnSubmit = '?a='.$_GET['a'].'&amp;t='.$Table.'&amp;o=save'.$URL;
      $Output .= $Form->ShowEditForm();
      $Actions[] = '<a href="?a=list&amp;t='.$Table.'"><img alt="Seznam" title="Seznam" src="'.
        $this->System->Link('/images/list.png').'"/>Seznam</a>';
    }
    $Output .= '<ul class="ActionMenu">';
    foreach($Actions as $Action)
    {
      $Output .= '<li>'.$Action.'</li>';
    }
    $Output .= '</ul>';
    return($Output);
  }

  function ShowAddSub($Table, $Filter = '', $Title = '')
  {
    if(defined('NEW_PERMISSION') and !$this->System->User->CheckPermission($this->TableToModule($Table), 'Write'))
      return('Nemáte oprávnění');
    $this->BasicHTML = true;
    $this->HideMenu = true;
    $Output = $this->ShowAdd($Table);
    return($Output);
  }

  function ShowView($Table, $Id, $WithoutActions = false)
  {
    if($Table != '') $FormClass = $this->System->FormManager->Classes[$Table];
      else return($this->SystemMessage('Chyba', 'Tabulka nenalezena'));
    if(defined('NEW_PERMISSION') and !$this->System->User->CheckPermission($this->TableToModule($Table), 'Read'))
      return('Nemáte oprávnění');

    $Form = new Form($this->System->FormManager);
    $Form->SetClass($Table);
    $this->ShortTitle .= ' - položka '.$Form->Definition['Title'];
    $Form->LoadValuesFromDatabase($Id);
    $Form->OnSubmit = '?a=view';
    $Output = $Form->ShowViewForm();
    if($WithoutActions == false)
    {
    $Actions = array(
      '<a href="?a=edit&amp;t='.$Table.'&amp;i='.$Id.'"><img alt="Upravit" title="Upravit" src="'.
        $this->System->Link('/images/edit.png').'"/>Upravit</a>',
      '<a href="?a=list&amp;t='.$Table.'"><img alt="Seznam" title="Seznam" src="'.
      $this->System->Link('/images/list.png').'"/>Seznam</a>',
      '<a href="?a=delete&amp;t='.$Table.'&amp;i='.$Id.'" onclick="return confirmAction(\'Opravdu smazat položku?\');"><img alt="Odstranit" title="Odstranit" src="'.
      $this->System->Link('/images/delete.png').'" />Odstranit</a>',
      '<a href="?a=add&amp;t='.$Table.'"><img alt="Přidat" title="Přidat" src="'.
      $this->System->Link('/images/add.png').'"/>Přidat</a>');
    if(array_key_exists('ItemActions', $FormClass))
    {
      foreach($FormClass['ItemActions'] as $Action)
      {
        $URL = $this->System->Link($Action['URL']);
        if(strpos($URL, '?') === false) $URL .= '?';
        else if((substr($URL, -5, 5) !== '&amp;') and (substr($URL, -1, 1) !== '?')) $URL .= '&amp;';
        $URL .= 'i='.$Id;
        $Actions[] = '<a href="'.$URL.'"><img alt="'.$Action['Caption'].'" title="'.$Action['Caption'].'" src="'.
            $this->System->Link('/images/action.png').'"/>'.$Action['Caption'].'</a>';
      }
    }
    $Output .= '<ul class="ActionMenu">';
    foreach($Actions as $Action)
    {
      $Output .= '<li>'.$Action.'</li>';
    }
    $Output .= '</ul><br/>';

    // Show ManyToOne relations
    foreach($Form->Definition['Items'] as $Index => $Item)
    if((array_key_exists($Item['Type'], $this->System->FormManager->FormTypes) and
    ($this->System->FormManager->FormTypes[$Item['Type']]['Type'] == 'ManyToOne')))
    {
      $Output .= $this->ShowList($this->System->FormManager->FormTypes[$Item['Type']]['Table'], '`'.
        $this->System->FormManager->FormTypes[$Item['Type']]['Ref'].'`='.$Id, $Item['Caption'],
        $this->System->FormManager->FormTypes[$Item['Type']]['Ref'], $Id).'<br/>';
    }
    }
    return($Output);
  }

  function ShowTable($Table, $Filter = '', $Title = '', $RowActions = array(), $ExcludeColumn = '')
  {
  	if($Table != '') $FormClass = $this->System->FormManager->Classes[$Table];
      else return($this->SystemMessage('Chyba', 'Tabulka nenalezena'));

    if(array_key_exists('SQL', $FormClass))
      $SourceTable = '('.$FormClass['SQL'].') AS `TX`';
      else $SourceTable = '`'.$FormClass['Table'].'` AS `TX`';

    // Build user filter
    $UserFilter = '';
    $Columns = array('Id' => '`Id`');
    if(array_key_exists('filter', $_GET) and ($_GET['filter'] == 1))
    {
      foreach($FormClass['Items'] as $ItemIndex => $FormItem)
      if(!array_key_exists($FormItem['Type'], $this->System->FormManager->FormTypes) or
      (array_key_exists($FormItem['Type'], $this->System->FormManager->FormTypes) and
      ($this->System->FormManager->FormTypes[$FormItem['Type']]['Type'] != 'ManyToOne')))
      {
        $UseType = $UseType = $FormItem['Type'];
        if(array_key_exists($FormItem['Type'], $this->System->FormManager->FormTypes))
        {
          if(!array_key_exists($FormItem['Type'], $this->System->FormManager->Type->TypeDefinitionList))
            $this->System->FormManager->Type->RegisterType($FormItem['Type'], '',
              $this->System->FormManager->FormTypes[$FormItem['Type']]);
          if($this->System->FormManager->FormTypes[$FormItem['Type']]['Type'] == 'Reference')
          $UseType = 'OneToMany';
          else
          if($this->System->FormManager->FormTypes[$FormItem['Type']]['Type'] == 'Enumeration')
          $UseType = 'Enumeration';
        }
        $FilterName = $this->System->FormManager->Type->ExecuteTypeEvent($UseType, 'OnFilterName',
          array('Name' => $ItemIndex, 'Type' => $FormItem['Type']));
        if(array_key_exists('Filter'.$ItemIndex, $_POST) and ($_POST['Filter'.$ItemIndex] != ''))
          $UserFilter .= ' AND ('.$FilterName.' LIKE "%'.$_POST['Filter'.$ItemIndex].'%")';
      }
    }
    if(($Filter == '') and ($UserFilter != '')) $Filter = '1 '.$UserFilter;
    if($Filter != '') $Filter = ' WHERE '.$Filter;

    foreach($FormClass['Items'] as $ItemIndex => $FormItem)
      if(!array_key_exists($FormItem['Type'], $this->System->FormManager->FormTypes) or
      (array_key_exists($FormItem['Type'], $this->System->FormManager->FormTypes) and
      ($this->System->FormManager->FormTypes[$FormItem['Type']]['Type'] != 'ManyToOne')))
      {
      	if($ExcludeColumn != $ItemIndex)
          $TableColumns[] = array('Name' => $ItemIndex, 'Title' => $FormItem['Caption']);
        $UseType = $UseType = $FormItem['Type'];
        if(array_key_exists($FormItem['Type'], $this->System->FormManager->FormTypes))
        {
          if(!array_key_exists($FormItem['Type'], $this->System->FormManager->Type->TypeDefinitionList))
            $this->System->FormManager->Type->RegisterType($FormItem['Type'], '',
                $this->System->FormManager->FormTypes[$FormItem['Type']]);
          if($this->System->FormManager->FormTypes[$FormItem['Type']]['Type'] == 'Reference')
            $UseType = 'OneToMany';
          else
            if($this->System->FormManager->FormTypes[$FormItem['Type']]['Type'] == 'Enumeration')
            $UseType = 'Enumeration';
        }
        if(array_key_exists('Filter'.$ItemIndex, $_POST) and ($_POST['Filter'.$ItemIndex] != ''))
          $Value = $_POST['Filter'.$ItemIndex];
          else $Value = '';
        if($ItemIndex == 'Id') unset($Columns['Id']);

        if(!array_key_exists('SQL', $FormItem)) $FormItem['SQL'] = '';
          else $FormItem['SQL'] = str_replace('#Id', '`TX`.`Id`', $FormItem['SQL']);
        $Columns[] = $this->System->FormManager->Type->ExecuteTypeEvent($UseType, 'OnFilterNameQuery',
          array('Value' => $Value, 'Name' => $ItemIndex,
            'Type' => $FormItem['Type'], 'SQL' => $FormItem['SQL']));
      }

    // Get total item count in database
    $Query = 'SELECT COUNT(*) FROM '.$SourceTable;
    $DbResult = $this->Database->query($Query);
    $DbRow = $DbResult->fetch_assoc();
    $TotalCount = $DbRow['COUNT(*)'];

    // Get total filtered item count in database
    $Columns = implode(',', $Columns);
    if($Filter != '')
    {
      $Query = 'SELECT COUNT(*) FROM (SELECT '.$Columns.' FROM '.$SourceTable.') AS `TS` '.$Filter;
      $DbResult = $this->Database->query($Query);
      $DbRow = $DbResult->fetch_row();
      $TotalFilteredCount = $DbRow[0];
    } else $TotalFilteredCount = $TotalCount;
    $PageList = GetPageList($TotalFilteredCount);

    $Output = '<div style="text-align: center;">'.$FormClass['Title'].'</div>';
    $Output .= $PageList['Output'];
    $Output .= '<table class="WideTable" style="font-size: small;">';

    $TableColumns[] = array('Name' => '', 'Title' => 'Akce');
    if(!array_key_exists('DefaultSortColumn', $FormClass))
      $FormClass['DefaultSortColumn'] = 'Id';
    if(!array_key_exists('DefaultSortOrder', $FormClass))
      $FormClass['DefaultSortOrder'] = 0;
    $Order = GetOrderTableHeader($TableColumns, $FormClass['DefaultSortColumn'], $FormClass['DefaultSortOrder']);
    $Output .= $Order['Output'];

    // Show search fields
    if(array_key_exists('r', $_GET)) $Addition = '&amp;r='.$_GET['r'];
      else $Addition = '';
    $Output .= '<tr><form action="?a='.$_GET['a'].'&amp;t='.$Table.'&amp;filter=1'.$Addition.'" method="post">';
    foreach($FormClass['Items'] as $ItemIndex => $FormItem)
    if((!array_key_exists($FormItem['Type'], $this->System->FormManager->FormTypes) or
    (array_key_exists($FormItem['Type'], $this->System->FormManager->FormTypes) and
    ($this->System->FormManager->FormTypes[$FormItem['Type']]['Type'] != 'ManyToOne'))) and
    ($ExcludeColumn != $ItemIndex))
    {
      if(array_key_exists('Filter'.$ItemIndex, $_POST) and ($_POST['Filter'.$ItemIndex] != ''))
        $Value = $_POST['Filter'.$ItemIndex];
        else $Value = '';
      $Output .= '<td><input type="text" name="Filter'.$ItemIndex.'" value="'.$Value.'" style="width: 100%"/></td>';
    }
    $Output .= '<td><input type="Submit" value="Hledat"/></td></form></tr>';

    // Load and show items
    $Query = 'SELECT * FROM (SELECT '.$Columns.' FROM '.$SourceTable.') AS `TS` '.
      $Filter.' '.$Order['SQL'].$PageList['SQLLimit'];
    $VisibleItemCount = 0;
    $DbResult = $this->Database->query($Query);
    while($Row = $DbResult->fetch_assoc())
    {
      $Output .= '<tr>';
      foreach($FormClass['Items'] as $ItemIndex => $FormItem)
      if((!array_key_exists($FormItem['Type'], $this->System->FormManager->FormTypes) or
      (array_key_exists($FormItem['Type'], $this->System->FormManager->FormTypes) and
      ($this->System->FormManager->FormTypes[$FormItem['Type']]['Type'] != 'ManyToOne'))) and
      ($ExcludeColumn != $ItemIndex))
      {
      	//$Output .= '<td>'.$Row[$ItemIndex].'</td>';
        $UseType = $UseType = $FormItem['Type'];
        if(array_key_exists($FormItem['Type'], $this->System->FormManager->FormTypes))
        {
          if(!array_key_exists($FormItem['Type'], $this->System->FormManager->Type->TypeDefinitionList))
            $this->System->FormManager->Type->RegisterType($FormItem['Type'], '',
              $this->System->FormManager->FormTypes[$FormItem['Type']]);
          if($this->System->FormManager->FormTypes[$FormItem['Type']]['Type'] == 'Reference')
          $UseType = 'OneToMany';
          else
          if($this->System->FormManager->FormTypes[$FormItem['Type']]['Type'] == 'Enumeration')
          $UseType = 'Enumeration';
        }
        $Row[$ItemIndex] = $this->System->FormManager->Type->ExecuteTypeEvent($UseType, 'OnLoadDb',
          array('Value' => $Row[$ItemIndex], 'Name' => $ItemIndex,
          'Type' => $FormItem['Type']));
        $Value = $this->System->FormManager->Type->ExecuteTypeEvent($UseType, 'OnView',
          array('Value' => $Row[$ItemIndex], 'Name' => $ItemIndex,
          'Type' => $FormItem['Type'], 'Filter' => $Row[$ItemIndex.'_Filter']));
        if($Value == '') $Value = '&nbsp;';
        $Output .= '<td>'.$Value.'</td>';
      }
      $Output .= '<td>'.str_replace('#RowId', $Row['Id'], $RowActions).'</td></tr>';
      $VisibleItemCount = $VisibleItemCount + 1;
    }
    $Output .= '<tr><td colspan="'.count($TableColumns).'" style="text-align: right;">Zobrazeno <strong>'.$VisibleItemCount.'</strong>';
    if($UserFilter != '') $Output .= ' z filtrovaných <strong>'.$TotalFilteredCount.'</strong>';
    $Output .= ' z celkem <strong>'.$TotalCount.'</strong></td></tr>';
    $Output .= '</table>';
    $Output .= $PageList['Output'];
    return($Output);
  }

  function ShowSelect($Table, $Filter = '', $Title = '')
  {
    if(defined('NEW_PERMISSION') and !$this->System->User->CheckPermission($this->TableToModule($Table), 'Read'))
      return('Nemáte oprávnění');
    $this->BasicHTML = true;
    $this->HideMenu = true;
    $RowActions = '<a href="javascript:window.close();" onclick="set_return(#RowId,&quot;'.
      $_GET['r'].'&quot;);"><img alt="Vybrat" title="Vybrat" src="'.
      $this->System->Link('/images/select.png').'"/></a>';
    $Output = $this->ShowTable($Table, $Filter, $Title, $RowActions);
    return($Output);
  }

  function ShowMapSelect($Table, $Filter = '', $Title = '')
  {
    if(defined('NEW_PERMISSION') and !$this->System->User->CheckPermission($this->TableToModule($Table), 'Write'))
      return('Nemáte oprávnění');
    $MapApi = new MapApiGoogle($this->System);
    $MapApi->Position = array('Lat' => $this->System->Config['Map']['DefaultLatitude'],
      'Lng' => $this->System->Config['Map']['DefaultLongitude']);
    $MapApi->Zoom = $this->System->Config['Map']['DefaultZoom'];
    $MapApi->Key = $this->System->Config['Map']['GoogleMapsApiKey'];
    $MapApi->OnClickObject = $_GET['r'];
    //$MapApi->ShowMarker = true;
    $Output = $MapApi->ShowPage($this);
    return($Output);
  }

  function ShowList($Table, $Filter = '', $Title = '', $ExcludeColumn = '', $ExcludeValue = '')
  {
    if(defined('NEW_PERMISSION') and !$this->System->User->CheckPermission($this->TableToModule($Table), 'Read'))
      return('Nemáte oprávnění');
    $RowActions = '<a href="?a=view&amp;t='.$Table.'&amp;i=#RowId"><img alt="Ukázat" title="Ukázat" src="'.
      $this->System->Link('/images/view.png').'"/></a>'.
      '<a href="?a=edit&amp;t='.$Table.'&amp;i=#RowId"><img alt="Upravit" title="Upravit" src="'.
      $this->System->Link('/images/edit.png').'"/></a>'.
      '<a href="?a=delete&amp;t='.$Table.'&amp;i=#RowId"><img alt="Smazat" title="Smazat" src="'.
      $this->System->Link('/images/delete.png').'" onclick="return confirmAction(\'Opravdu smazat položku?\');"/></a>';
    if(($Table != '') and (array_key_exists($Table, $this->System->FormManager->Classes)))
      $FormClass = $this->System->FormManager->Classes[$Table];
      else return($this->SystemMessage('Chyba', 'Tabulka '.$Table.' nenalezena'));
    if(array_key_exists('ItemActions', $FormClass))
    {
      foreach($FormClass['ItemActions'] as $Action)
      {
        $URL = $this->System->Link($Action['URL']);
        if(strpos($URL, '?') === false) $URL .= '?';
        else if((substr($URL, -5, 5) !== '&amp;') and (substr($URL, -1, 1) !== '?')) $URL .= '&amp;';
        $URL .= 'i=#RowId';
        $RowActions .= '<a href="'.$URL.'"><img alt="'.$Action['Caption'].'" title="'.$Action['Caption'].'" src="'.
          $this->System->Link('/images/action.png').'"/></a>';
      }
    }
    $Output = $this->ShowTable($Table, $Filter, $Title, $RowActions, $ExcludeColumn);
    $Output .= '<ul class="ActionMenu">';
    $Output .= '<li><a href="?a=add&amp;t='.$Table.'&amp;preset'.$ExcludeColumn.'='.$ExcludeValue.'"><img alt="Přidat" title="Přidat" src="'.
      $this->System->Link('/images/add.png').'"/>Přidat</a></li>';
    $Output .= '<li><a href="?a=list&amp;t='.$Table.'"><img alt="Seznam" title="Seznam" src="'.
      $this->System->Link('/images/list.png').'"/>Seznam</a></li>';
    if(array_key_exists('Actions', $FormClass))
    {
      foreach($FormClass['Actions'] as $Action)
        $Output .= '<li><a href="'.$this->System->Link($Action['URL']).'"><img alt="'.$Action['Caption'].'" title="'.$Action['Caption'].'" src="'.
            $this->System->Link('/images/action.png').'"/>'.$Action['Caption'].'</a></li>';
    }
    $Output .= '</ul>';
    return($Output);
  }

  function ShowMenu()
  {
    $this->MenuItems = array();
    $DbResult = $this->Database->query('SELECT `MenuItem`.`Id`, `MenuItem`.`Name`, `MenuItem`.`Parent`, `Action`.`URL` AS `URL`, `ActionIcon`.`Name` AS `IconName`, `Action`.`PermissionOperation` AS `Permission` FROM `MenuItem` '.
      'LEFT JOIN `Action` ON `Action`.`Id` = `MenuItem`.`Action` '.
      'LEFT JOIN `ActionIcon` ON `ActionIcon`.`Id` = `Action`.`Icon` '.
      'WHERE `MenuItem`.`Menu`=1 '.
      'ORDER BY `MenuItem`.`Parent`,`MenuItem`.`Name`');
    while($DbRow = $DbResult->fetch_assoc())
    {
      //if($DbRow['Permission'] != '')
      $this->MenuItems[$DbRow['Id']] = $DbRow;
    }
    return($this->ShowMenuItem(''));
  }

  function ShowMenuItem($Parent)
  {
    $Output = '<ul style="list-style: none; margin-left:1em; padding-left:0em;">';
    foreach($this->MenuItems as $MenuItem)
    if($MenuItem['Parent'] == $Parent)
    {
      $LinkTitle = $MenuItem['Name'];
      if($MenuItem['URL'] != '')
      {
        $Icon = 'Device.png';
        if(substr($MenuItem['URL'], 0, 4) != 'http') $MenuItem['URL'] = $this->System->Link($MenuItem['URL']);
        $LinkTitle = MakeLink($MenuItem['URL'], $LinkTitle);
      } else $Icon = 'Folder.png';
      if($MenuItem['IconName'] != '') $Image = '<img src="'.$this->System->Link('/images/favicons/'.$MenuItem['IconName']).'"/>&nbsp;';
        else $Image = '<img src="'.$this->System->Link('/images/favicons/'.$Icon).'"/>&nbsp;';
      //if($this->System->User->CheckPermission($this->TableToModule($Table), 'Write') or !defined('NEW_PERMISSION'))
        $Output .= '<li>'.$Image.$LinkTitle.'</li>';
      $Output .= $this->ShowMenuItem($MenuItem['Id']);
    }
    $Output .= '</ul>';
    return($Output);
  }

  function TableToModule($Table)
  {
    $DbResult = $this->Database->query('SELECT (SELECT `Name` FROM `Module` '.
      'WHERE `Module`.`Id`=`Model`.`Module`) AS `Name` FROM `Model` WHERE `Name`="'.$Table.'"');
    if($DbResult->num_rows == 1)
    {
      $DbRow = $DbResult->fetch_assoc();
      return($DbRow['Name']);
    } else return('');
  }
}

class ModuleIS extends AppModule
{
  function __construct($System)
  {
    parent::__construct($System);
    $this->Name = 'Information system';
    $this->Version = '1.0';
    $this->Creator = 'Chronos';
    $this->License = 'GNU/GPLv3';
    $this->Description = 'User interface for generic information system';
    $this->Dependencies = array();
  }

  function DoInstall()
  {
  }

  function DoUninstall()
  {
  }

  function DoStart()
  {
    $this->System->RegisterPage('is', 'PageIS');
    $this->System->FormManager->RegisterClass('MenuItem', array(
      'Title' => 'Položky nabídky',
      'Table' => 'MenuItem',
      'Items' => array(
        'Name' => array('Type' => 'String', 'Caption' => 'Název', 'Default' => ''),
        'Parent' => array('Type' => 'TMenuItem', 'Caption' => 'Rodič', 'Default' => '', 'Null' => true),
        'Action' => array('Type' => 'TAction', 'Caption' => 'Akce', 'Default' => ''),
        'Menu' => array('Type' => 'TMenu', 'Caption' => 'Nabídka', 'Default' => ''),
        'Items' => array('Type' => 'TMenuItemListParent', 'Caption' => 'Položky'),
      ),
    ));
    $this->System->FormManager->RegisterClass('Menu', array(
      'Title' => 'Nabídky',
      'Table' => 'Menu',
      'Items' => array(
        'Name' => array('Type' => 'String', 'Caption' => 'Název', 'Default' => ''),
        'Items' => array('Type' => 'TMenuItemListMenu', 'Caption' => 'Položky'),
      ),
    ));
  }

  function DoStop()
  {
  }
}
