<?php

include_once(dirname(__FILE__).'/Types/Type.php');
include_once(dirname(__FILE__).'/FormManager.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 FormItem
{
  public string $Type;
  public string $Caption;
  public string $Default;
  public bool $Null;
  public bool $NotInList;
  public bool $Hidden;
  public bool $Filter;
  public string $Suffix;
  public string $Description;
  public bool $ReadOnly;
  public bool $Required;
  public string $SQL;
}

class Form
{
  public FormManager $FormManager;
  public Database $Database;
  public array $Definition;
  public array $Values;
  public array $ValuesValidate;
  public array $ValuesFilter;
  public string $OnSubmit;

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

  function LoadDefaults(): void
  {
    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(string $Name): void
  {
    $this->Definition = &$this->FormManager->Classes[$Name];
    $this->LoadDefaults();
  }

  function GetValue(string $Index, string $Event = 'OnView'): string
  {
    $Item = $this->Definition['Items'][$Index];
    $UseType = $this->GetItemType($Item);
    
    $Result = $this->FormManager->Type->ExecuteTypeEvent($UseType, $Event,
      array('Value' => $this->Values[$Index], 'Name' => $Index,
      'Type' => $Item['Type'], 'Values' => $this->Values,
      'Filter' => $this->Values[$Index]));
    if ($Result == null) return '';
    return $Result;
  }

  function ShowViewForm(): string
  {
    $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')))
    {
      $UseType = $this->GetItemType($Item);
      $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(): string
  {
    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(string $Context = ''): string
  {
    $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']);

        $UseType = $this->GetItemType($Item);
        $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 GetItemType($Item): string
  {
    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 $UseType;
  }

  function LoadValuesFromDatabase(string $Id): void
  {
    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')))
      {
        $UseType = $this->GetItemType($Item);
        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')))
      {
        $UseType = $this->GetItemType($Item);
        $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(string $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);
        $UseType = $this->GetItemType($Item);
        $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;
      $this->Database->insert($this->Definition['Table'], $Values);
    } else
      $this->Database->update($this->Definition['Table'], 'Id='.$Id, $Values);
  }

  function HasAllPostVariables(): bool
  {
    $Result = array_key_exists('submit', $_POST);

    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')))
      {
        $UseType = $this->GetItemType($Item);
        if (!$this->FormManager->Type->ExecuteTypeEvent($UseType, 'OnCanLoad',
          array('Value' => $this->Values[$Index], 'Name' => $Index,
          'Type' => $Item['Type'], 'Values' => $this->Values,
          'Filter' => $this->Values[$Index])))
        {
          $Result = false;
          break;
        }
      }
    }

    return $Result;
  }

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

  function LoadValuesFromFormBlock(string $Context = ''): array
  {
    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))
          $UseType = $this->GetItemType($Item);
          $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;
  }

  // Check if filled value is in valid form
  function Validate(): bool
  {
    $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))
        $UseType = $this->GetItemType($Item);
        $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(string $Target, string $Title): string
{
  return '<a href="'.$Target.'">'.$Title.'</a>';
}

function Table(array $Table): string
{
  $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;
}