<?php

class PageUser extends Page
{
  function __construct(System $System)
  {
    parent::__construct($System);
    $this->Title = 'Uživatel';
    $this->ParentClass = 'PagePortal';
  }

  function Panel(string $Title, string $Content, array $Menu = array()): string
  {
    if (count($Menu) > 0)
      foreach ($Menu as $Item)
        $Title .= '<div class="Action">'.$Item.'</div>';
    return '<div class="Panel"><div class="Title">'.$Title.'</div><div class="Content">'.$Content.'</div></div>';
  }

  function ShowContacts(): string
  {
    if (!$this->System->ModuleManager->ModuleRunning('Subject')) return '';

    $Query = 'SELECT `Contact`.`Value`, `Contact`.`Description`, (SELECT `Name` FROM `ContactCategory` WHERE `ContactCategory`.`Id` = `Contact`.`Category`) AS `Category` '.
      'FROM `Contact` WHERE `User` = '.
      ModuleUser::Cast($this->System->GetModule('User'))->User->User['Id'];
    $DbResult = $this->Database->query('SELECT COUNT(*) FROM ('.$Query.') AS T');
    $DbRow = $DbResult->fetch_row();
    $PageList = GetPageList('Contacts', $DbRow[0]);

    $Output = '<div>Kontakty</div>';
    $Output .= $PageList['Output'];
    $Output .= '<table class="WideTable" style="font-size: small;">';

    $TableColumns = array(
      array('Name' => 'Category', 'Title' => 'Skupina'),
      array('Name' => 'Value', 'Title' => 'Hodnota'),
      array('Name' => 'Description', 'Title' => 'Popis'),
    );
    $Order = GetOrderTableHeader('Contacts', $TableColumns, 'Value', 0);
    $Output .= $Order['Output'];
    $Query = $Query.' '.$Order['SQL'].$PageList['SQLLimit'];
    $DbResult = $this->Database->query($Query);
    while ($Contact = $DbResult->fetch_assoc())
    {
      $Output .= '<tr>'.
      '<td>'.$Contact['Category'].'</td>'.
      '<td>'.$Contact['Value'].'</td>'.
      '<td>'.$Contact['Description'].'</td>'.
        '</tr>';
    }
    $Output .= '</table>';
    $Output .= $PageList['Output'];

    return $Output;
  }

  function ShowUserPanel(): string
  {
    $User = &ModuleUser::Cast($this->System->GetModule('User'))->User;
    $Output = '';
    if ($User->User['Id'] != null)
    {
      $Actions = '';
      foreach (ModuleUser::Cast($this->System->GetModule('User'))->UserPanel as $Action)
      {
        if (is_string($Action[0]))
        {
          $Class = new $Action[0]($this->System);
          $Method = $Action[1];
          $Actions .= $Class->$Method();
        } else $Actions .= call_user_func($Action).'<br/>';
      }
      $Output .= '<div class="Centered"><table id="MainTable"><tr><td style="vertical-align:top;">';
      $Output .= $this->Panel('Nabídka uživatele', $Actions);
      $Output .= '</td><td style="vertical-align:top;">';
      if ($User->User['Id'] != null)
        {
          $Form = new Form($this->System->FormManager);
          $Form->SetClass('UserOptions');
          $Form->LoadValuesFromDatabase($User->User['Id']);
          $Form->OnSubmit = '?Action=UserOptionsSave';
          $Output .= $Form->ShowViewForm();

          $Output .= '<br/>'.$this->ShowContacts();
        } else $Output .= $this->SystemMessage('Nastavení uživatele', 'Nejste přihlášen');

      //$Output .= $this->Panel('Přehled', $this->UserPanel());
      $Output .= '</td></tr></table></div>';
    } else $Output .= $this->SystemMessage('Oprávnění', 'Nejste přihlášen');
    return $Output;
  }

  function Show(): string
  {
    $User = &ModuleUser::Cast($this->System->GetModule('User'))->User;
    $Output = '';
    if (array_key_exists('Action', $_GET))
    {
      $Action = $_GET['Action'];
      if ($Action == 'LoginForm')
      {
        $Form = new Form($this->System->FormManager);
        $Form->SetClass('UserLogin');
        $Form->OnSubmit = '?Action=Login';
        $Output .= $Form->ShowEditForm();
        $Output .= '<div class="Centered"><a href="?Action=UserRegister">Registrovat se</a> '.
        '<a href="?Action=PasswordRecovery">Obnova zapomenutého hesla</a></div>';
      } else
      if ($Action == 'Login')
      {
        if (array_key_exists('Username', $_POST) and array_key_exists('Password', $_POST))
        {
          $Form = new Form($this->System->FormManager);
          $Form->SetClass('UserLogin');
          $Form->OnSubmit = '?Action=Login';
          if (array_key_exists('StayLogged', $_POST) and ($_POST['StayLogged'] == 'on')) $StayLogged = true;
            else $StayLogged = false;
          $Result = $User->Login($_POST['Username'], $_POST['Password'], $StayLogged);
          $Output .= $this->SystemMessage('Přihlášení', $Result);
          if ($Result <> USER_LOGGED_IN)
          {
            $Form->LoadValuesFromForm();
            $Form->Values['Password'] = '';
            $Output .= $Form->ShowEditForm();
            $Output .= '<div class="Centered"><a href="?Action=UserRegister">Registrovat se</a> '.
              '<a href="?Action=PasswordRecovery">Obnova zapomenutého hesla</a></div>';
          } else {
            //$Output .= '<div class="Centered">Za 5 sekund budete přesměrováni na <a href="?Action=UserMenu">nabídku uživatele</a></div>';
            //Header('refresh:5;url=?Action=UserMenu');
            Header('Location: ?Action=UserMenu');
          }
        } else $Output .= $this->SystemMessage('Přihlášení', 'Nezadány přihlašovací údaje');
      } else
      if ($Action == 'Logout')
      {
        if ($User->User['Id'] != null)
        {
          $Output .= $this->SystemMessage('Odhlášení', $User->Logout());
        } else $Output .= $this->SystemMessage('Nastavení uživatele', 'Nejste přihlášen');
      } else
      if ($Action == 'UserOptions')
      {
        if ($User->User['Id'] != null)
        {
          $Form = new Form($this->System->FormManager);
          $Form->SetClass('UserOptions');
          $Form->LoadValuesFromDatabase($User->User['Id']);
          $Form->OnSubmit = '?Action=UserOptionsSave';
          $Output .= $Form->ShowEditForm();
        } else $Output .= $this->SystemMessage('Nastavení uživatele', 'Nejste přihlášen');
      } else
      if ($Action == 'UserOptionsSave')
      {
        $Form = new Form($this->System->FormManager);
        $Form->SetClass('UserOptions');
        $Form->LoadValuesFromForm();
        $Form->SaveValuesToDatabase($User->User['Id']);
        $Output .= $this->SystemMessage('Nastavení', 'Nastavení uloženo.');
        ModuleLog::Cast($this->System->GetModule('Log'))->NewRecord('User', 'Nastavení uživatele změněno', $Form->Values['Name']);
        $Form->LoadValuesFromDatabase($User->User['Id']);
        $Form->OnSubmit = '?Action=UserOptionsSave';
        $Output .= $Form->ShowEditForm();
      } else
      if ($Action == 'UserRegister')
      {
        $Form = new Form($this->System->FormManager);
        $Form->SetClass('UserRegister');
        //$Form->LoadValuesFromForm();
        $Form->OnSubmit = '?Action=UserRegisterSave';
        $Output .= $Form->ShowEditForm();
      } else
      if ($Action == 'UserRegisterConfirm')
      {
        $Output .= $this->SystemMessage('Potvrzení registrace',
          $User->RegisterConfirm($_GET['User'], $_GET['H']));
      } else
      if ($Action == 'PasswordRecovery')
      {
        $Form = new Form($this->System->FormManager);
        $Form->SetClass('PasswordRecovery');
        if ($Form->HasAllPostVariables())
        {
          $Form->LoadValuesFromForm();
          if ($Form->Values['IsHuman'] == 1)
          {
            $Result = $User->PasswordRecoveryRequest($Form->Values['Name'], $Form->Values['Email']);
            $Output .= $this->SystemMessage('Obnova hesla', $Result);
          } else 
          {
            $Result = USER_NOT_HUMAN;
            $Output .= $this->SystemMessage('Nejsi člověk. Strojům není dovoleno obnovovat heslo.', $Result);
          }
          if ($Result <> USER_PASSWORD_RECOVERY_SUCCESS)
          {
            $Output .= $Form->ShowEditForm();
          }
        } else
        {
          $Form->OnSubmit = '?Action=PasswordRecovery';
          $Output .= $Form->ShowEditForm();
        }
      } else
      if ($Action == 'PasswordRecoveryConfirm')
      {
        $Output .= $this->SystemMessage('Obnova hesla', $User->PasswordRecoveryConfirm($_GET['User'], $_GET['H'], $_GET['P']));
      } else
      if ($Action == 'UserRegisterSave')
      {
        if (array_key_exists('Login', $_POST) and array_key_exists('Password', $_POST) and array_key_exists('Name', $_POST)
          and array_key_exists('Email', $_POST))
        {
          $Form = new Form($this->System->FormManager);
          $Form->SetClass('UserRegister');
          $Form->LoadValuesFromForm();
          if ($Form->Values['IsHuman'] == 1)
          {
            $Result = $User->Register($Form->Values['Login'], $Form->Values['Password'],
              $Form->Values['Password2'], $Form->Values['Email'], $Form->Values['Name']);
            $Output .= $this->SystemMessage('Registrace nového účtu', $Result);
          } else
          {
            $Result = USER_NOT_HUMAN;
            $Output .= $this->SystemMessage('Nejsi člověk. Strojům není dovoleno se registrovat.', $Result);
          }
          if ($Result <> USER_REGISTRATED)
          {
            $Form->OnSubmit = '?Action=UserRegisterSave';
            $Output .= $Form->ShowEditForm();
          }
        } else $Output .= $this->SystemMessage('Registrace', 'Nezadány registrační údaje');
      } else
      if ($Action == 'UserMenu')
      {
        $Output = $this->ShowUserPanel();
      } else $Output = $this->ShowMain();
    } else $Output = $this->ShowMain();
    return $Output;
  }

  function ShowMain(): string
  {
    $Output = 'Nebyla vybrána akce';
    return $Output;
  }
}
