<?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 = array();
  var $MenuItemsLoaded = false;
  var $HideMenu = false;

  function Show()
  {
    if(!$this->System->User->CheckPermission('IS', 'Manage')) 
      return('Nemáte oprávnění');
   
    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 == 'edit') $Content = $this->ShowEdit($Table, $ItemId);
    else if($Action == 'add') $Content = $this->ShowAdd($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->ShowMenuItem(''); 
      $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/>';
    return($Output);
  }
  
  function ShowEdit($Table, $Id)
  {
    $Output = '';
    if(array_key_exists('o', $_GET))
    {
      if($_GET['o'] == 'save')
      {
        $Form = new Form($this->System->FormManager);
        $Form->SetClass($Table);
        $Form->LoadValuesFromForm();
        $Form->SaveValuesToDatabase($Id);
        $Output .= $this->SystemMessage('Úprava položky', 'Položka upravena');
        $Output .= $this->ShowView($Table, $Id);   
      }
    } else 
    {
      $Form = new Form($this->System->FormManager);
      $Form->SetClass($Table);
      $Form->LoadValuesFromDatabase($Id);
      $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 = '';
    $this->Database->delete($Table, 'Id='.$Id);
    $Output .= $this->SystemMessage('Odstranění položky', 'Položka odstraněna');
    $Output .= $this->ShowList($Table);   
    return($Output);
  }
  
  function ShowAdd($Table)
  {
    $Output = '';
    if(array_key_exists('o', $_GET))
    {
      if($_GET['o'] == 'save')
      {
        $Form = new Form($this->System->FormManager);
        $Form->SetClass($Table);
        $Form->LoadValuesFromForm();
        $Form->SaveValuesToDatabase(0);        
        $Output .= $this->SystemMessage('Přidání položky', 'Nová položka vytvořena');
        $Id = $this->Database->insert_id;
        //$this->Database->update($Table, 'Id='.$Id, 
        //  array('UserCreate' => $this->System->User->User['Id'], 
        //  'TimeCreate' => 'NOW()'));
        $Output .= $this->ShowView($Table, $Id);   
      }
    } else 
    {
      $Form = new Form($this->System->FormManager);
      $Form->SetClass($Table);
      $Form->OnSubmit = '?a=add&amp;t='.$Table.'&amp;o=save';
      $Output .= $Form->ShowEditForm();
      $Output .= '<ul class="ActionMenu">';
      $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 .= '</ul>';
    }
    return($Output);
  }
  
  function ShowView($Table, $Id)
  {
    if($Table != '') $FormClass = $this->System->FormManager->Classes[$Table];
      else return($this->SystemMessage('Chyba', 'Tabulka nenalezena'));
    
    $Form = new Form($this->System->FormManager);
    $Form->SetClass($Table);
    $Form->LoadValuesFromDatabase($Id);
    $Form->OnSubmit = '?a=view';
    $Output = $Form->ShowViewForm();
    $Output .= '<ul class="ActionMenu">';
    $Output .= '<li><a href="?a=edit&amp;t='.$Table.'&amp;i='.$Id.'"><img alt="Upravit" title="Upravit" src="'.
      $this->System->Link('/images/edit.png').'"/>Upravit</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 .= '<li><a href="?a=add&amp;t='.$Table.'"><img alt="Přidat" title="Přidat" src="'.
      $this->System->Link('/images/add.png').'"/>Přidat</a></li>';
    if(array_key_exists('ItemActions', $FormClass))
    {
      foreach($FormClass['ItemActions'] as $Action)
        $Output .= '<li><a href="'.$this->System->Link($Action['URL']).'&amp;i='.$Id.'"><img alt="'.$Action['Caption'].'" title="'.$Action['Caption'].'" src="'.
            $this->System->Link('/images/action.png').'"/>'.$Action['Caption'].'</a></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']).'<br/>';
    }    
    return($Output);
  }
  
  function ShowTable($Table, $Filter = '', $Title = '', $RowActions = array())
  {   
    if($Table != '') $FormClass = $this->System->FormManager->Classes[$Table];
      else return($this->SystemMessage('Chyba', 'Tabulka nenalezena'));

    // 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')))
      {
        $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']);
        $Columns[] = $this->System->FormManager->Type->ExecuteTypeEvent($UseType, 'OnFilterNameQuery',
          array('Value' => $Value, 'Name' => $ItemIndex,
              'Type' => $FormItem['Type']));
      }
      
    // Get total item count in database
    $Query = 'SELECT COUNT(*) FROM `'.$FormClass['Table'].'`';
    $DbResult = $this->Database->query($Query);
    $DbRow = $DbResult->fetch_assoc();
    $TotalCount = $DbRow['COUNT(*)'];
    
    // Get total filtered item count in database
    $Columns = implode(',', $Columns);
    if($UserFilter != '')
    {
      $Query = 'SELECT COUNT(*) FROM (SELECT '.$Columns.' FROM `'.$FormClass['Table'].'`) 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';
    $Order = GetOrderTableHeader($TableColumns, $FormClass['DefaultSortColumn'], 0);
    $Output .= $Order['Output'];
    
    // Show search fields
    $Output .= '<tr><form action="?a=list&amp;t='.$Table.'&amp;filter=1" 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')))
    {
      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 `'.$FormClass['Table'].'`) 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')))
      {
        //$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 = '')
  { 
    $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 ShowList($Table, $Filter = '', $Title = '')  
  {
    $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 != '') $FormClass = $this->System->FormManager->Classes[$Table];
      else return($this->SystemMessage('Chyba', 'Tabulka nenalezena'));
    if(array_key_exists('ItemActions', $FormClass))
    {
      foreach($FormClass['ItemActions'] as $Action)
        $RowActions .= '<a href="'.$this->System->Link($Action['URL']).'&amp;i=#RowId"><img alt="'.$Action['Caption'].'" title="'.$Action['Caption'].'" src="'.
          $this->System->Link('/images/action.png').'"/></a>';
    }   
    $Output = $this->ShowTable($Table, $Filter, $Title, $RowActions);
    $Output .= '<ul class="ActionMenu">';
    $Output .= '<li><a href="?a=add&amp;t='.$Table.'"><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 ShowMenuItem($Parent)
  {
    if($this->MenuItemsLoaded == false)
    {
      $DbResult = $this->Database->query('SELECT `MenuItem`.`Id`, `MenuItem`.`Name`, `MenuItem`.`Parent`, `Action`.`URL` AS `URL`, `ActionIcon`.`Name` AS `IconName`  FROM `MenuItem` '.
        'LEFT JOIN `Action` ON `Action`.`Id` = `MenuItem`.`Action` '.
        'LEFT JOIN `ActionIcon` ON `ActionIcon`.`Id` = `Action`.`Icon` '.
        'ORDER BY `MenuItem`.`Parent`,`MenuItem`.`Name`');
      while($DbRow = $DbResult->fetch_assoc())
      {
        $this->MenuItems[$DbRow['Id']] = $DbRow;
      }
      $this->MenuItemsLoaded = true;
    }    
    
    $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'] != '') 
      {
        if(substr($MenuItem['URL'], 0, 4) != 'http') $MenuItem['URL'] = $this->System->Link($MenuItem['URL']);
        $LinkTitle = MakeLink($MenuItem['URL'], $LinkTitle);
      }
      if($MenuItem['IconName'] != '') $Image = '<img src="../images/favicons/'.$MenuItem['IconName'].'"/>&nbsp;';
        else $Image = '';
      $Output .= '<li>'.$Image.$LinkTitle.'</li>';
      $Output .= $this->ShowMenuItem($MenuItem['Id']);
    }
    $Output .= '</ul>';
    return($Output);
  }
}

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 Install()
  {
  }
  
  function Uninstall()
  {     
  }
  
  function Start()
  {
    parent::Start();
    $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 Stop()
  { 
  } 
}

?>
