<?php

class PageEdit extends Page
{
  public string $Table;
  public string $TableSQL;
  public array $Definition;
  public array $ItemActions;
  public bool $AllowEdit;

  function __construct($System)
  {
    parent::__construct($System);
    $this->Table = '';
    $this->Definition = array();
    $this->ItemActions = array(
      array('Name' => T('View'), 'URL' => '?action=view&amp;id=#Id'),
    );
    $this->AllowEdit = false;
    if ($this->AllowEdit) $this->ItemActions[] = array('Name' => T('Delete'), 'URL' => '?action=remove&amp;id=#Id');
  }

  function Show(): string
  {
    $Output = '';
    if (array_key_exists('action', $_GET))
    {
      if ($_GET['action'] == 'add') $Output .= $this->AddItem();
      else if ($_GET['action'] == 'view') $Output .= $this->ViewItem();
      //else if ($_GET['action'] == 'edit') $Output .= $this->ModifyItem();
      //else if ($_GET['action'] == 'remove') $Output .= $this->RemoveItem();
      else if ($_GET['action'] == 'delete') $Output .= $this->DeleteItem();
      else $Output .= ShowMessage(T('Unknown action'), MESSAGE_CRITICAL);
    } else $Output .= $this->ViewList();
    return $Output;
  }

  function ViewItem()
  {
    $DbResult = $this->Database->query('SELECT * FROM ('.$this->TableSQL.') AS `T` WHERE `Id`='.$_GET['id']);
    if ($DbResult->num_rows > 0)
    {
      $DbRow = $DbResult->fetch_assoc();

      $Output = T('Item').
        '<table>';
      foreach ($this->Definition as $DefIndex => $Def)
      {
        $Output .= '<tr><td>'.$Def['Title'].':</td><td>'.$this->ViewControl($Def['Type'], $DefIndex, $DbRow[$DefIndex]).'</tr>';
      }
      $Output .= '<tr>'.
        '</table>';
    } else $Output = ShowMessage(T('Item not found'), MESSAGE_CRITICAL);
    if ($this->AllowEdit)
    {
      $Output .= '<a href="?action=add">'.T('Add').'</a> ';
      $Output .= '<a href="?action=edit&amp;id='.$_GET['id'].'">'.T('Edit').'</a> ';
      $Output .= '<a href="?action=delete&amp;id='.$_GET['id'].'">'.T('Add').'</a> ';
    }
    $Output .= '<a href="?">'.T('List').'</a><br/>';
    return $Output;
  }

  function ViewList()
  {
    $DbResult = $this->Database->query('SELECT COUNT(*) FROM ('.$this->TableSQL.') AS `T`');
    $DbRow = $DbResult->fetch_row();
    $PageList = GetPageList($DbRow[0]);
    $Output = $PageList['Output'];

    $Output .= '<table class="BaseTable">';
    $TableColumns = array();
    foreach ($this->Definition as $Index => $Def)
      if ($Def['InList'])
        $TableColumns[] = array('Name' => $Index, 'Title' => $Def['Title']);
    if (count($this->ItemActions) > 0)
      $TableColumns[] = array('Name' => '', 'Title' => 'Akce');

    $Order = GetOrderTableHeader($TableColumns, 'Name', 0);
    $Output .= $Order['Output'];

    $DbResult = $this->Database->query('SELECT * FROM ('.$this->Table.') '.$Order['SQL'].$PageList['SQLLimit']);
    while ($Item = $DbResult->fetch_assoc())
    {
      $Output .= '<tr>';
      foreach ($this->Definition as $Index => $Def)
      if ($Def['InList'])
      {
        if ($Def['Type'] == 'URL') $Output .= '<td><a href="'.$Item[$Index].'">'.$Item[$Index].'</a></td>';
          else $Output .= '<td>'.$Item[$Index].'</td>';
      }
      if (count($this->ItemActions) > 0)
      {
        $Output .= '<td>';
        foreach ($this->ItemActions as $Index => $Action)
        {
          $URL = $Action['URL'];
          if (strpos($URL, '#Id')) $URL = str_replace('#Id', $Item['Id'], $URL);
          $Output .= '<a href="'.$URL.'">'.$Action['Name'].'</a> ';
        }
        $Output .= '</td>';
      }
      $Output .= '</tr>';
    }
    $Output .= '</table>';
    if ($this->AllowEdit) $Output .= '<a href="?action=add">'.T('Add').'</a><br/>';
    return $Output;
  }

  function AddItem()
  {
    $Output = '';
    $User = ModuleUser::Cast($this->System->GetModule('User'))->User;
    if ($User->Licence(LICENCE_USER))
    {
      if (array_key_exists('finish', $_GET))
      {
        $Items = array();
        foreach ($this->Definition as $Index => $Def)
        {
          $Items[$Index] = $_POST[$Index];
        }
        $this->Database->insert($this->Table, $Items);
        $Output = ShowMessage(T('Item added'), MESSAGE_INFORMATION);
      } else
      {
        $Output .= '<form action="?action=add&amp;finish=1" method="post">'.
          '<fieldset><legend>'.T('New item').'</legend>'.
          '<table>';
        foreach ($this->Definition as $DefIndex => $Def)
        {
          $Output .= '<tr><td>'.$Def['Title'].':</td><td>'.$this->GetControl($Def['Type'], $DefIndex, '').'</tr>';
        }
        $Output .= '<tr><td colspan="2"><input type="submit" value="'.T('Add').'" /></td></tr>'.
          '</table>'.
          '</fieldset>'.
          '</form>';
      }
    } else $Output .= ShowMessage(T('Access denied'), MESSAGE_CRITICAL);
    return $Output;
  }

  function DeleteItem()
  {
    $User = ModuleUser::Cast($this->System->GetModule('User'))->User;
    if ($User->Licence(LICENCE_USER))
    {
      $this->Database->query('DELETE FROM `'.$this->Table.'` WHERE (`User`='.$User->Id.') AND (`Id`='.($_GET['id'] * 1).')');
      $Output = ShowMessage(T('Record removed'));
    } else $Output = ShowMessage(T('Access denied'), MESSAGE_CRITICAL);
    return $Output;
  }

  function GetControl($Type, $Name, $Value)
  {
    if ($Type == 'Text') $Output = '<input type="text" name="'.$Name.'" value="'.$Value.'"/>';
    else if ($Type == 'Boolean') $Output = '<input type="checkbox" name="'.$Name.'"/>';
    else $Output = '<input type="text" name="'.$Name.'" value="'.$Value.'"/>';
    return $Output;
  }

  function ViewControl($Type, $Name, $Value)
  {
    if ($Type == 'Text') $Output = $Value;
    else if ($Type == 'URL') $Output = '<a href="'.$Value.'">'.$Value.'</a>';
    else if ($Type == 'Boolean') $Output = $Value;
    else $Output = $Value;
    return $Output;
  }
}
