<?php

include_once(dirname(__FILE__).'/Types/Type.php');

/*
Form item type definition:
Type - identifikace typu z podporovaných
Caption - popisek, titulek položky
Default - výchozí hodnota
Null - hodnota nemusí být zadána
NotInList - sloupec neviditelný v seznamu položek
Hidden - neviditelný, při přidání nové položky se použije výchozí hodnota.
Filter - column is used as filer according default value
Suffix - text za hodnotou
Description - popis významu položky
ReadOnly - je položky pouze pro čtení
Required - položka je vyžadována
SQL - SQL dotaz pro zjištění hodnoty, #Id bude nahrazeno Id aktuální položky
*/


class Form
{
  var $FormManager;
  var $Definition;
  var $Values;
  var $ValuesValidate;
  var $ValuesFilter;
  var $OnSubmit;
  var $Database;

  function __construct($FormManager)
  {
    $this->FormManager = &$FormManager;
    $this->Database = $FormManager->Database;
    $this->Definition = array();
    $this->Values = array();
    $this->ValuesFilter = array();
    $this->ValuesValidate = array();
    $this->OnSubmit = '';
  }

  function LoadDefaults()
  {
    foreach ($this->Definition['Items'] as $Index => $Item)
    {
      if (!array_key_exists($Item['Type'], $this->FormManager->FormTypes) or
      (array_key_exists($Item['Type'], $this->FormManager->FormTypes) and
      ($this->FormManager->FormTypes[$Item['Type']]['Type'] != 'ManyToOne')))
      {
        if (!array_key_exists($Index, $this->Values))
        {
          if (isset($Item['Default'])) $this->Values[$Index] = $Item['Default'];
            else $this->Values[$Index] = null;
        }
      }
    }
  }

  function SetClass($Name)
  {
    $this->Definition = &$this->FormManager->Classes[$Name];
    $this->LoadDefaults();
  }

  function GetValue($Index, $Event = 'OnView')
  {
    $Item = $this->Definition['Items'][$Index];
    if(array_key_exists($Item['Type'], $this->FormManager->FormTypes))
    {
      if(!array_key_exists($Item['Type'], $this->FormManager->Type->TypeDefinitionList))
        $this->FormManager->Type->RegisterType($Item['Type'], '', $this->FormManager->FormTypes[$Item['Type']]);
      if($this->FormManager->FormTypes[$Item['Type']]['Type'] == 'Reference')
        $UseType = 'OneToMany';
      else if($this->FormManager->FormTypes[$Item['Type']]['Type'] == 'Enumeration')
        $UseType = 'Enumeration';
    } else $UseType = $Item['Type'];
    return $this->FormManager->Type->ExecuteTypeEvent($UseType, $Event,
        array('Value' => $this->Values[$Index], 'Name' => $Index,
        'Type' => $Item['Type'], 'Values' => $this->Values,
        'Filter' => $this->Values[$Index]));
  }

  function ShowViewForm()
  {
    $Table = array(
      //'Header' => array('Položka', 'Hodnota'),
      'Rows' => array(),
    );
    foreach($this->Definition['Items'] as $Index => $Item)
    if(!array_key_exists('Hidden', $Item) or ($Item['Hidden'] == false))
    if(!array_key_exists($Item['Type'], $this->FormManager->FormTypes) or
    (array_key_exists($Item['Type'], $this->FormManager->FormTypes) and
    ($this->FormManager->FormTypes[$Item['Type']]['Type'] != 'ManyToOne')))
    {
      if(array_key_exists($Item['Type'], $this->FormManager->FormTypes))
      {
        if(!array_key_exists($Item['Type'], $this->FormManager->Type->TypeDefinitionList))
          $this->FormManager->Type->RegisterType($Item['Type'], '', $this->FormManager->FormTypes[$Item['Type']]);
        if($this->FormManager->FormTypes[$Item['Type']]['Type'] == 'Reference')
          $UseType = 'OneToMany';
        else if($this->FormManager->FormTypes[$Item['Type']]['Type'] == 'Enumeration')
          $UseType = 'Enumeration';
      } else $UseType = $Item['Type'];
      $Edit = $this->FormManager->Type->ExecuteTypeEvent($UseType, 'OnView',
        array('Value' => $this->Values[$Index], 'Name' => $Index,
        'Type' => $Item['Type'], 'Values' => $this->Values,
        'Filter' => $this->ValuesFilter[$Index]));
      if(array_key_exists('Suffix', $Item)) $Edit .= ' '.$Item['Suffix'];
      if(!$this->FormManager->Type->IsHidden($UseType))
        array_push($Table['Rows'], array($Item['Caption'].':', $Edit));
    }
    $Output = '<fieldset><legend>'.$this->Definition['Title'].'</legend>'.Table($Table).
    '</fieldset>';
    return($Output);
  }

  function ShowEditForm()
  {
    if(!array_key_exists('SubmitText', $this->Definition)) $this->Definition['SubmitText'] = 'Uložit';
    $Output = '<form enctype="multipart/form-data" class="Form" action="'.$this->OnSubmit.'" method="post">'.$this->ShowEditBlock().
      '<div><input name="submit" type="submit" value="'.$this->Definition['SubmitText'].'" /> '.
      '<input type="button" value="Zrušit" onclick="location.href=\'?\'"/></div></form>';
    return($Output);
  }

  function ShowEditBlock($Context = '')
  {
    $Hidden = '';
    $IsHidden = false;
    $Table = array(
      //'Header' => array('Položka', 'Hodnota'),
      'Rows' => array(),
    );
    if ($Context != '') $Context = $Context.'-';
    foreach ($this->Definition['Items'] as $Index => $Item)
    {
      if (!array_key_exists('ReadOnly', $Item)) $Item['ReadOnly'] = false;
      if ($Item['ReadOnly'] == false)
      if (!array_key_exists('Hidden', $Item) or ($Item['Hidden'] == false))
      if (!array_key_exists($Item['Type'], $this->FormManager->FormTypes) or
      (array_key_exists($Item['Type'], $this->FormManager->FormTypes) and
      ($this->FormManager->FormTypes[$Item['Type']]['Type'] != 'ManyToOne')))
      {
        $Parameters = array('Value' => $this->Values[$Index], 'Name' => $Index,
          'Type' => $Item['Type'], 'Values' => $this->Values);
        if (array_key_exists('Null', $Item)) $Parameters['Null'] = $Item['Null'];
          else unset($Parameters['Null']);
        if (array_key_exists('OnPreset', $Item)) $Parameters['OnPreset'] = $Item['OnPreset'];
          else unset($Parameters['OnPreset']);

        if (array_key_exists($Item['Type'], $this->FormManager->FormTypes))
        {
          if (!array_key_exists($Item['Type'], $this->FormManager->Type->TypeDefinitionList))
            $this->FormManager->Type->RegisterType($Item['Type'], '',
              $this->FormManager->FormTypes[$Item['Type']]);
          if ($this->FormManager->FormTypes[$Item['Type']]['Type'] == 'Reference')
          {
            $UseType = 'OneToMany';
          } else if ($this->FormManager->FormTypes[$Item['Type']]['Type'] == 'Enumeration')
            $UseType = 'Enumeration';
        } else $UseType = $Item['Type'];
        $Edit = $this->FormManager->Type->ExecuteTypeEvent($UseType, 'OnEdit', $Parameters);
        if (array_key_exists('Suffix', $Item)) $Edit .= $Item['Suffix'];

        $Caption = $Item['Caption'].':';
        if (array_key_exists($Index, $this->ValuesValidate) and
          $this->ValuesValidate[$Index])
        {
          $Format = $this->FormManager->Type->ExecuteTypeEvent($UseType, 'GetValidationFormat', array());
          if ($Format != '') $Caption .= '<br/><small>'.$Format.'</small>';
          $Caption = '<span style="color:red;">'.$Caption.'</span>';
        }
        if (!$this->FormManager->Type->IsHidden($UseType))
          array_push($Table['Rows'], array($Caption, $Edit));
        else $Hidden .= $Edit;
      }
    }
    $Output = '<fieldset><legend>'.$this->Definition['Title'].'</legend>'.Table($Table).
    $Hidden.'</fieldset>';
    return $Output;
  }

  function LoadValuesFromDatabase($Id)
  {
    foreach($this->Definition['Items'] as $Index => $Item)
    if(!array_key_exists($Item['Type'], $this->FormManager->FormTypes) or
    (array_key_exists($Item['Type'], $this->FormManager->FormTypes) and
    ($this->FormManager->FormTypes[$Item['Type']]['Type'] != 'ManyToOne')))
    {
        if(array_key_exists($Item['Type'], $this->FormManager->FormTypes))
        {
          if(!array_key_exists($Item['Type'], $this->FormManager->Type->TypeDefinitionList))
            $this->FormManager->Type->RegisterType($Item['Type'], '',
              $this->FormManager->FormTypes[$Item['Type']]);
          if($this->FormManager->FormTypes[$Item['Type']]['Type'] == 'Reference')
            $UseType = 'OneToMany';
          else if($this->FormManager->FormTypes[$Item['Type']]['Type'] == 'Enumeration')
            $UseType = 'Enumeration';
        } else $UseType = $Item['Type'];
      if(!array_key_exists('SQL', $Item)) $Item['SQL'] = '';
        else $Item['SQL'] = str_replace('#Id', $Id, $Item['SQL']);
      $Columns[] = $this->FormManager->Type->ExecuteTypeEvent($UseType, 'OnFilterNameQuery',
        array('Name' => $Index, 'Type' => $Item['Type'], 'SQL' => $Item['SQL']));
    }
    $Columns = implode(',', $Columns);
    if(array_key_exists('SQL', $this->Definition))
      $SourceTable = '('.$this->Definition['SQL'].') AS `TX`';
      else $SourceTable = '`'.$this->Definition['Table'].'` AS `TX`';
    $DbResult = $this->Database->query('SELECT '.$Columns.' FROM '.$SourceTable.' WHERE `TX`.`Id`='.$Id);
    $DbRow = $DbResult->fetch_array();
    foreach($this->Definition['Items'] as $Index => $Item)
    if(!array_key_exists($Item['Type'], $this->FormManager->FormTypes) or
    (array_key_exists($Item['Type'], $this->FormManager->FormTypes) and
    ($this->FormManager->FormTypes[$Item['Type']]['Type'] != 'ManyToOne')))
    {
        if(array_key_exists($Item['Type'], $this->FormManager->FormTypes))
        {
          if(!array_key_exists($Item['Type'], $this->FormManager->Type->TypeDefinitionList))
            $this->FormManager->Type->RegisterType($Item['Type'], '',
              $this->FormManager->FormTypes[$Item['Type']]);
          if($this->FormManager->FormTypes[$Item['Type']]['Type'] == 'Reference')
            $UseType = 'OneToMany';
          else if($this->FormManager->FormTypes[$Item['Type']]['Type'] == 'Enumeration')
            $UseType = 'Enumeration';
        } else $UseType = $Item['Type'];
        $this->Values[$Index] = $this->FormManager->Type->ExecuteTypeEvent($UseType, 'OnLoadDb',
            array('Value' => $DbRow[$Index], 'Name' => $Index,
            'Type' => $Item['Type'], 'Values' => $this->Values));
        $this->ValuesFilter[$Index] = $DbRow[$Index.'_Filter'];
    }
  }

  function SaveValuesToDatabase($Id)
  {
    $Values = array();
    foreach($this->Definition['Items'] as $Index => $Item)
    {
      if(array_key_exists($Index, $this->Values))
      if(!array_key_exists($Item['Type'], $this->FormManager->FormTypes) or
      (array_key_exists($Item['Type'], $this->FormManager->FormTypes) and
      ($this->FormManager->FormTypes[$Item['Type']]['Type'] != 'ManyToOne')))
      {
        $Parameters = array('Value' => $this->Values[$Index], 'Name' => $Index,
          'Type' => $Item['Type'], 'Values' => $this->Values);

        if(array_key_exists($Item['Type'], $this->FormManager->FormTypes))
        {
          if(!array_key_exists($Item['Type'], $this->FormManager->Type->TypeDefinitionList))
            $this->FormManager->Type->RegisterType($Item['Type'], '',
              $this->FormManager->FormTypes[$Item['Type']]);
          if($this->FormManager->FormTypes[$Item['Type']]['Type'] == 'Reference')
          {
            $UseType = 'OneToMany';
          }
          else if($this->FormManager->FormTypes[$Item['Type']]['Type'] == 'Enumeration')
            $UseType = 'Enumeration';
        } else $UseType = $Item['Type'];
        $Values[$Index] = $this->FormManager->Type->ExecuteTypeEvent($UseType, 'OnSaveDb', $Parameters);
        if(($Item['Type'] == 'Password') and ($Values[$Index] == '')) unset($Values[$Index]);
      }
    }
    if($Id == 0)
    {
      $Values['Id'] = $Id;
      $DbResult = $this->Database->insert($this->Definition['Table'], $Values);
    } else
      $DbResult = $this->Database->update($this->Definition['Table'], 'Id='.$Id, $Values);
  }

  function LoadValuesFromForm()
  {
    $this->Values = $this->LoadValuesFromFormBlock();
  }

  function LoadValuesFromFormBlock($Context = '')
  {
    if ($Context != '') $Context = $Context.'-';
    $Values = array();
    foreach ($this->Definition['Items'] as $Index => $Item)
    {
      if (!array_key_exists('Hidden', $Item) or ($Item['Hidden'] == false))
      {
        if ((!array_key_exists($Item['Type'], $this->FormManager->FormTypes) or
        (array_key_exists($Item['Type'], $this->FormManager->FormTypes) and
        ($this->FormManager->FormTypes[$Item['Type']]['Type'] != 'ManyToOne'))) and
        (!array_key_exists('ReadOnly', $Item) or
        (array_key_exists('ReadOnly', $Item) and
        ($Item['ReadOnly'] != true))))
        {
          //if (array_key_exists($Context.$Index, $_POST))
          if (array_key_exists($Item['Type'], $this->FormManager->FormTypes))
          {
            if (!array_key_exists($Item['Type'], $this->FormManager->Type->TypeDefinitionList))
              $this->FormManager->Type->RegisterType($Item['Type'], '',
                $this->FormManager->FormTypes[$Item['Type']]);
            $CustomType = $this->FormManager->FormTypes[$Item['Type']]['Type'];
            if ($CustomType == 'Reference')
              $UseType = 'OneToMany';
            else if ($CustomType == 'Enumeration')
              $UseType = 'Enumeration';
          } else $UseType = $Item['Type'];
          $Parameters = array('Name' => $Index, 'Type' => $Item['Type'], 'Values' => $this->Values);
          if (array_key_exists('Null', $Item)) $Parameters['Null'] = $Item['Null'];
            else unset($Parameters['Null']);
          $Values[$Index] = $this->FormManager->Type->ExecuteTypeEvent($UseType, 'OnLoad',
            $Parameters);
        }
      } else
      {
        if (isset($Item['Default'])) {
          if (isset($Item['Null']) and ($Item['Null'] == true))
            $Values[$Index] = null;
          else $Values[$Index] = $Item['Default'];
        }
      }
    }
    return($Values);
  }

  function Validate()
  {
    $Valid = true;
    foreach($this->Definition['Items'] as $Index => $Item)
    if((!array_key_exists($Item['Type'], $this->FormManager->FormTypes) or
    (array_key_exists($Item['Type'], $this->FormManager->FormTypes) and
    ($this->FormManager->FormTypes[$Item['Type']]['Type'] != 'ManyToOne'))) and
    (!array_key_exists('ReadOnly', $Item) or
    (array_key_exists('ReadOnly', $Item) and
    ($Item['ReadOnly'] != true))))
    {
        //if(array_key_exists($Context.$Index, $_POST))
        if(array_key_exists($Item['Type'], $this->FormManager->FormTypes))
        {
          if(!array_key_exists($Item['Type'], $this->FormManager->Type->TypeDefinitionList))
            $this->FormManager->Type->RegisterType($Item['Type'], '',
              $this->FormManager->FormTypes[$Item['Type']]);
          $CustomType = $this->FormManager->FormTypes[$Item['Type']]['Type'];
          if($CustomType == 'Reference')
            $UseType = 'OneToMany';
          else if($CustomType == 'Enumeration')
            $UseType = 'Enumeration';
        } else $UseType = $Item['Type'];

        $Parameters = array('Value' => $this->Values[$Index]);
        if(array_key_exists('Null', $Item)) $Parameters['Null'] = $Item['Null'];
          else $Parameters['Null'] = false;
        if(!$this->FormManager->Type->ExecuteTypeEvent($UseType, 'Validate',
          $Parameters)) {
            $this->ValuesValidate[$Index] = true;
            $Valid = false;
          }
    }
    if($Valid == false) throw new Exception('not validated');
    return($Valid);
  }
}


function MakeLink($Target, $Title)
{
  return('<a href="'.$Target.'">'.$Title.'</a>');
}

function Table($Table)
{
  $Result = '<table class="BasicTable">';
  if(array_key_exists('Header', $Table))
  {
    $Result .= '<tr>';
    foreach($Table['Header'] as $Item)
      $Result .= '<th>'.$Item.'</th>';
    $Result .= '</tr>';
  }
  foreach($Table['Rows'] as $Row)
  {
    $Result .= '<tr>';
    foreach($Row as $Index => $Item)
    {
      if($Index == 0) $Class = ' class="Header"'; else $Class = '';
      $Result .= '<td'.$Class.' style="width: '.(floor(100 / count($Row))).'%">'.$Item.'</td>';
    }
    $Result .= '</tr>';
  }
  $Result .= '</table>';
  return($Result);
}

class FormManager
{
  var $Classes;
  var $FormTypes;
  var $Database;
  var $Type;
  var $RootURL;
  var $ShowRelation;

  function __construct($Database)
  {
    $this->Database = &$Database;
    $this->Classes = array();
    $this->FormTypes = array();
    $this->Type = new Type($this);
    $this->ShowRelation = false;
  }

  function RegisterClass($Name, $Class)
  {
    $this->Classes[$Name] = $Class;
  }

  function UnregisterClass($Name)
  {
    unset($this->Classes[$Name]);
  }

  function RegisterFormType($Name, $Class)
  {
    $this->FormTypes[$Name] = $Class;
  }

  function UnregisterFormType($Name)
  {
    unset($this->FormTypes[$Name]);
  }

  function UpdateSQLMeta()
  {
    $this->Database->query('DELETE FROM ModelField');
    $this->Database->query('DELETE FROM Model');
    $this->Database->query('DELETE FROM DataType WHERE Parent IS NOT NULL');
    $this->Database->query('DELETE FROM DataType');

    foreach($this->Type->TypeDefinitionList as $Name => $Type)
    {
      $DbResult = $this->Database->select('DataType', 'Id', 'Name="'.$Name.'"');
      if($DbResult->num_rows == 0)
      {
        $this->Database->insert('DataType', array('Name' => $Name,
          'Title' => $Type['Class']));
      } else
      {
        $DbRow = $DbResult->fetch_assoc();
        $this->Database->update('DataType', 'Id='.$DbRow['Id'], array('Name' => $Name,
          'Title' => $Type['Class']));
      }
    }

    foreach($this->Classes as $Class)
    if(!array_key_exists('SQL', $Class) and ($Class['Table'] != ''))
    {
      $DbResult = $this->Database->query('SELECT * FROM information_schema.tables  WHERE table_schema = "centrala_big"
          AND table_name = "'.$Class['Table'].'" LIMIT 1');
      if($DbResult->num_rows == 0) continue;

      echo($Class['Table'].'<br>');
      $Module = 1;
      $DbResult = $this->Database->select('Model', 'Id', 'Name="'.$Class['Table'].'"');
      if($DbResult->num_rows == 0)
      {
        $this->Database->insert('Model', array('Name' => $Class['Table'], 'Title' => $Class['Title'], 'Module' => $Module));
        $Model = $this->Database->insert_id;
      } else
      {
        $DbRow = $DbResult->fetch_assoc();
        $Model = $DbRow['Id'];
        $this->Database->update('Model', 'Id='.$DbRow['Id'], array('Name' => $Class['Table'],
          'Title' => $Class['Title'], 'Module' => $Module));
      }

      foreach($Class['Items'] as $Name => $Field)
      {
        echo($Name.', ');
        $DbResult = $this->Database->select('DataType', 'Id', 'Name="'.$Field['Type'].'"');
        if($DbResult->num_rows > 0)
        {
          $DbRow = $DbResult->fetch_assoc();
          $Type = $DbRow['Id'];
        } else {
          $Type = $this->FormTypes[$Field['Type']];

          // Search parent type
          $DbResult = $this->Database->select('DataType', 'Id', 'Name="'.$Type['Type'].'"');
          if($DbResult->num_rows > 0)
          {
            $DbRow = $DbResult->fetch_assoc();
            $ParentType = $DbRow['Id'];
          } else $ParentType = null;

          $this->Database->insert('DataType', array('Name' => $Field['Type'],
            'Title' => '', 'Parent' => $ParentType));
          $Type = $this->Database->insert_id;
        }

        $DbResult = $this->Database->select('ModelField', 'Id', '(Name="'.$Name.'") AND (Model='.$Model.')');
        if($DbResult->num_rows == 0)
        {
          $this->Database->insert('ModelField', array('Name' => $Name,
            'Title' => $Field['Caption'], 'Model' => $Model, 'Type' => $Type));
        } else
        {
          $DbRow = $DbResult->fetch_assoc();
          $this->Database->update('ModelField', 'Id='.$DbRow['Id'], array('Name' => $Name,
            'Title' => $Field['Caption'], 'Model' => $Model, 'Type' => $Type));
        }
      }
      echo('<br>');
    }
  }
}
