<?php

include_once('form_classes.php');
include_once('database.php');

class Form
{
  var $Definition = array();
  var $Values = array();
  var $OnSubmit = '';

  function Form($ClassName)
  {  
    global $FormClasses;

    $this->Definition = &$FormClasses[$ClassName];
  }

  function ShowEditForm()
  {
    $Output = '<form action="'.$this->OnSubmit.'" method="post"><center>'.$this->ShowEditBlock().'<input type="submit" value="Uložit"></center></form>';
    return($Output);
  }

  function ShowEditBlock($Context = '')
  {
    global $Database, $FormTypes;

    $Table = array(
      //'Header' => array('Položka', 'Hodnota'),
      'Rows' => array(),
    );
    if($Context != '') $Context = $Context.'-';
    foreach($this->Definition['Items'] as $Index => $Item)
    {
      if(!array_key_exists($Index, $this->Values) and isset($Item['Default'])) $this->Values[$Index] = $Item['Default']; 
      switch($Item['Type'])
      {
        case 'Boolean':
          if($this->Values[$Index] == 0) $Checked = ''; else $Checked = ' CHECKED';
          $Edit = '<input type="checkbox" name="'.$Context.$Index.'"'.$Checked.'>';
          break;
        case 'String':
          $Edit = '<input type="text" name="'.$Context.$Index.'" value="'.$this->Values[$Index].'">';
          break;
        case 'Password':
          $Edit = '<input type="password" name="'.$Context.$Index.'" value="'.$this->Values[$Index].'">';
          break;
        case 'Integer':
          $Edit = '<input type="text" name="'.$Context.$Index.'" value="'.$this->Values[$Index].'">';
          break;
        case 'Float':
          $Edit = '<input type="text" name="'.$Context.$Index.'" value="'.$this->Values[$Index].'">';
          break;
        case 'Time':
          if($this->Values[$Index] == 'Now') $this->Values[$Index] = date('j.n.Y');
          $Edit = '<input type="text" name="'.$Context.$Index.'" value="'.$this->Values[$Index].'">';
          break;
        case 'Array':
          $Form  = new Form($Item['ItemClass']);
          $Edit = '<script type="text/javascript" id="syndication">'.
            "var Count = 0;".
            "function AddItem() {".
            "Count = Count + 1;".
            "var newcontent = document.createElement('div');".
            "newcontent.id = '".$Context.$Item['ItemClass']."-' + Count;".
            "newcontent.innerHTML = '<input type=\"hidden\" name=\"".$Context.$Item['ItemClass']."-' + Count + '\">".$Form->ShowEditBlock($Context.$Item['ItemClass']."-' + Count + '")."';".
            "var scr = document.getElementById('syndication');".
            "scr.parentNode.insertBefore(newcontent, scr); }".
            '</script>';
            $Edit .= '<form><input type="button" onclick="AddItem();" value="Přidat položku"></form>';
          break;
        default:
          if(array_key_exists($Item['Type'], $FormTypes))
          {
            // Custom types
            switch($FormTypes[$Item['Type']]['Type'])
            {
              case 'Enumeration':
                $Edit = '<select name="'.$Context.$Index.'">';
                foreach($FormTypes[$Item['Type']]['States'] as $StateIndex => $StateName)
                  $Edit .= '<option value="'.$StateIndex.'">'.$StateName.'</option>';
                $Edit .= '</select>';
                break;
              case 'Reference':
                $Edit = '<select name="'.$Context.$Index.'">';
                $DbResult = $Database->select($FormTypes[$Item['Type']]['Table'], $FormTypes[$Item['Type']]['Id'].' as Id, '.$FormTypes[$Item['Type']]['Name'].' as Name', $FormTypes[$Item['Type']]['Filter'].' ORDER BY Name');
                while($Row = $DbResult->fetch_array())
                  $Edit .= '<option value="'.$Row['Id'].'">'.$Row['Name'].'</option>';
                $Edit .= '</select>';
                break;
              default:
                $Edit = 'Neznámý typ';
            }
          } else $Edit = 'Neznámý typ';
      }
      array_push($Table['Rows'], array($Item['Caption'].':', $Edit));
    }
    $Output = '<fieldset style="width: 500px;"><legend>'.$this->Definition['Title'].'</legend>'.Table($Table).
    '</fieldset>';
    return($Output); 
  }

  function LoadValuesFromDatabase($Id)
  {
    global $Database;

    $DbResult = $Database->query('SELECT * FROM '.$this->Definition['Table'].' WHERE Id='.$Id);
    $DbRow = $DbResult->fetch_array();
    foreach($this->Definition['Items'] as $Index => $Item)
    {
      $this->Values[$Index] = $DbRow[$Index];
      switch($Item['Type'])
      {
        case 'Password':
          if($Item['Type'] == 'Password') $this->Values[$Index] = '';  // Dont show password
          break;
        case 'Time':
          $this->Values[$Index] == MysqlDateTimeToTime($this->Values[$Index]);
          break;
      }
    }
  }

  function SaveValuesToDatabase($Id)
  {
    global $Database;

    foreach($this->Definition['Items'] as $Index => $Item)
    {
      switch($Item['Type'])
      {
        case 'Password':
          if($this->Values[$Index] == '') unset($this->Values[$Index]); // Do not modify empty passwords
          else $this->Values[$Index] = sha1($this->Values[$Index]);
          break;
        case 'Time':
          $this->Values[$Index] = TimeToMysqlDateTime($this->Values[$Index]);
          break;
      }
    }
    $this->Values['Id'] = $Id;
    $DbResult = $Database->replace($this->Definition['Table'], $this->Values);
    //echo($Database->LastQuery);
  }

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

  function LoadValuesFromFormBlock($Context = '')
  {
    global $FormTypes;

    if($Context != '') $Context = $Context.'-';
    $Values = array();
    foreach($this->Definition['Items'] as $Index => $Item)
    {
      switch($Item['Type'])
      {
        case 'Boolean':
          if(array_key_exists($Context.$Index, $_POST)) $Values[$Index] = 1; 
          else $Values[$Index] = 0;
          break;
        case 'String':
          $Values[$Index] = $_POST[$Context.$Index];
          break;
        case 'Password':
          $Values[$Index] = $_POST[$Context.$Index];
          break;
        case 'Integer':
          $Values[$Index] = $_POST[$Context.$Index];
          break;
        case 'Float':
          $Values[$Index] = $_POST[$Context.$Index];
          break;
        case 'Time':
          $Values[$Index] = explode('.', $_POST[$Context.$Index]);
          $Values[$Index] = mktime(0, 0, 0, $Values[$Index][1], $Values[$Index][0], $Values[$Index][2]);
          break;
        case 'Array':
          $I = 1;
          //echo('Expect: '.$Context.$Item['ItemClass'].'-'.$I.'<br>');
          while(isset($_POST[$Context.$Item['ItemClass'].'-'.$I]))
          {
            $Form  = new Form($Item['ItemClass']);
            $Values[$Index][] = $Form->LoadValuesFromFormBlock($Context.$Item['ItemClass'].'-'.$I);
            $I++;
          }
          break;
        default:
          if(array_key_exists($Item['Type'], $FormTypes))
          {
            // Custom types
            switch($FormTypes[$Item['Type']]['Type'])
            {
              case 'Enumeration':
                $Values[$Index] = $_POST[$Context.$Index];
                break;
              case 'Reference':
                $Values[$Index] = $_POST[$Context.$Index];
                break;
              default:
            }
          }
      }
    }
    return($Values);
  }
}

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

function Table($Table)
{
  $Result = '<table class="BasicTable">';
  $Result .= '<tr>';
  if(array_key_exists('Header', $Table))
  {
    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.'>'.$Item.'</td>';
    }
    $Result .= '</tr>';
  }
  $Result .= '</table>';
  return($Result);
}

function ShowEditTable($ClassName, $Values)
{
}

?>