<?php

include('global.php');

class Index extends Page
{
  var $FullTitle = 'Seznam serverů';
  var $ShortTitle = 'Seznam serverů';
  
  function ShowServerListOnRow($Row)
  {
    $Server = new Server($this->Database, $Row['Id']);
    $ServerState = $Server->GetState();
    $Row['Online'] = $ServerState['Online'] * 1;
    $Row['NetworkPortRealmd'] = $this->System->Config['Web']['Host'].':'.$Row['NetworkPortRealmd'];
    $Row['Name'] = '<a href="?Action=ServerShow&amp;Id='.$Row['Id'].'">'.$Row['Name'].'</a>';
    $Row['AccountCount'] = $ServerState['AccountCount'];
    $Row['CharacterCount'] = $ServerState['CharacterCount'];
    $Row['OnlinePlayerCount'] = $ServerState['OnlinePlayerCount'];
    return($Row);
  }
  
  function ShowServerList()
  {
    global $Config;
    
    $Output = '<h4>Seznam serverů</h4>';
    $Table = new Table('ServerList');
    $Table->OnRow = array($this, 'ShowServerListOnRow');
    $Table->LoadValuesFromDatabase($this->Database);
    $Output .= $Table->Show();
    if($this->System->Modules['User']->User['Role'] >= USER_ROLE_USER) 
    {
      $DbResult = $this->Database->query('SELECT COUNT(*) FROM Server');
      $DbRow = $DbResult->fetch_row();
      $ServerCount = $DbRow[0];
      $DbResult = $this->Database->query('SELECT COUNT(*) FROM Server WHERE User='.$this->System->Modules['User']->User['Id']);
      $DbRow = $DbResult->fetch_row();
      if(($ServerCount < $Config['MaxServerCount']) and ($DbRow[0] == 0))
        $Output .= '<br /><div style="text-align: center;"><a href="?Action=ServerAdd">Vytvořit nový server</a></dev>';      
    }
    return($Output);
  }
  
  function ShowServer($Id)
  {
    $Server = new Server($this->Database, $Id);
    $Output = '<h4>Podrobnosti serveru</h4>';
    $Form = new Form('EditServer');
    $Form->LoadValuesFromDatabase($Id);
    $Output .= $Form->ShowTable();
    $Output .= '<div style="text-align: center">';
    if(($this->System->Modules['User']->User['Role'] >= USER_ROLE_USER) and ($this->System->Modules['User']->User['Id'] == $Server->Server['User']))
    {
      $Output .= '<br /><a href="'.$this->System->Config['Web']['Host'].'/mysql/">Správa databáze</a> ';
      if(array_key_exists('Id', $Server->Server['Database']))
      {
        $ServerStatus = $Server->GetState();
        if($ServerStatus['RealmdPortState'] == true) $Output .= ' <a href="?Action=ServerStop">Zastavit</a>  <a href="?Action=ServerRestart">Restartovat</a>';
          else $Output .= ' <a href="?Action=ServerStart">Spustit</a>';
      }
      $Output .= ' <a href="?Action=ServerEdit">Upravit</a>';
      $Output .= ' <a href="?Action=ServerDatabaseImport">Načtení čisté databáze</a>';
    }
    $Output .= '</div>';
    return($Output);
  }
  
  function ShowEmulatorListOnRow($Row)
  {
    $Row['Name'] = '<a href="?Action=EmulatorShow&amp;Id='.$Row['Id'].'">'.$Row['Name'].'</a>';
    return($Row);
  }
  
  function ShowEmulatorList()
  {
    global $Config;
    
    $Output = '<h4>Seznam verzí emulátoru</h4>';
    $Table = new Table('EmulatorList');
    $Table->OnRow = array($this, 'ShowEmulatorListOnRow');
    $Table->LoadValuesFromDatabase($this->Database);
    $Output .= $Table->Show();
    if($this->System->Modules['User']->User['Role'] >= USER_ROLE_ADMINISTRATOR) 
    {
      $Output .= '<br /><div style="text-align: center;"><a href="?Action=EmulatorAdd">Přidat emulátor</a></dev>';      
    }
    return($Output);
  }
  
  function EmulatorShow($Id)
  {
    //$Server = new Server($this->Database, $Id);
    $Output = '<h4>Podrobnosti emulátoru</h4>';
    $Form = new Form('EmulatorItem');
    $Form->LoadValuesFromDatabase($Id);
    $Output .= $Form->ShowTable();
    $Output .= '<div style="text-align: center">';
    if($this->System->Modules['User']->User['Role'] >= USER_ROLE_ADMINISTRATOR)
    {
      $Output .= ' <a href="?Action=EmulatorCompile&amp;Id='.$Id.'">Přeložit</a>';
      $Output .= ' <a href="?Action=EmulatorDownloadAndCompile&amp;Id='.$Id.'">Stáhnout a přeložit</a>';
    }
    $Output .= '</div>';
    return($Output);
  }
  
  function Show()
  {
    global $Config;
    
    $Output = '';
    if(array_key_exists('Action', $_GET))
    {
      if($_GET['Action'] == 'LoginForm')
      {
        $Form = new Form('UserLogin');
        $Form->OnSubmit = '?Action=Login';
        $Output .= $Form->ShowEditForm();
        $Output .= '<div class="Centred"><a href="?Action=UserRegister">Registrovat se</a> '.
		    '<a href="?Action=PasswordRecovery">Obnova zapomenutého hesla</a></div>';
      } else
      if($_GET['Action'] == 'Login')
      {
        $Form = new Form('UserLogin');
        $Form->OnSubmit = '?Action=Login';
        $Result = $this->System->Modules['User']->Login($_POST['Username'], $_POST['Password']);
        $Output .= $this->SystemMessage('Přihlášení', $Result);
        if($Result <> USER_LOGGED_IN)
        {
          $Form->LoadValuesFromForm();
          $Form->Values['Password'] = '';
          $Output .= $Form->ShowEditForm();
          $Output .= '<div class="Centred"><a href="?Action=UserRegister">Registrovat se</a> '.
	    	    '<a href="?Action=PasswordRecovery">Obnova zapomenutého hesla</a></div>';
        }
      } else 
      if($_GET['Action'] == 'Logout')
      {
        $Output .= $this->SystemMessage('Odhlášení', $this->System->Modules['User']->Logout());
      } else
      if($_GET['Action'] == 'UserOptions')
      { 
        $UserOptions = new Form('UserOptions');
        $UserOptions->LoadValuesFromDatabase($this->System->Modules['User']->User['Id']);
        $UserOptions->OnSubmit = '?Action=UserOptionsSave';
        $Output .= $UserOptions->ShowEditForm();
      } else
      if($_GET['Action'] == 'UserOptionsSave')
      {
        $UserOptions = new Form('UserOptions', array());
        $UserOptions->LoadValuesFromForm();
        $UserOptions->SaveValuesToDatabase($this->System->Modules['User']->User['Id']);
        $Output .= $this->SystemMessage('Nastavení', 'Nastavení uloženo.');
        $this->System->Modules['Log']->NewRecord('User', 'Nastavení uživatele změněno', $UserOptions->Values['Name']);
        $UserOptions->LoadValuesFromDatabase($this->System->Modules['User']->User['Id']);
        $UserOptions->OnSubmit = '?Action=UserOptionsSave';
        $Output .= $UserOptions->ShowEditForm();
      } else
      if($_GET['Action'] == 'UserRegister')
      {
        $Form = new Form('UserRegister');
        $Form->LoadValuesFromForm();
        $Form->OnSubmit = '?Action=UserRegisterSave';
        $Output .= $Form->ShowEditForm();
      } else
      if($_GET['Action'] == 'UserRegisterConfirm')
      {
        $Output .= $this->SystemMessage('Potvrzení registrace', $this->System->Modules['User']->RegisterConfirm($_GET['User'], $_GET['H']));
      } else
      if($_GET['Action'] == 'PasswordRecovery')
      {
        $Form = new Form('PasswordRecovery');
        $Form->OnSubmit = '?Action=PasswordRecovery2';
        $Output .= $Form->ShowEditForm();
      } else
      if($_GET['Action'] == 'PasswordRecovery2')
      {
        $Form = new Form('PasswordRecovery');
        $Form->LoadValuesFromForm();
        $Result = $this->System->Modules['User']->PasswordRecoveryRequest($Form->Values['Name'], $Form->Values['Email']);
        $Output .= $this->SystemMessage('Obnova hesla', $Result);
        if($Result <> USER_PASSWORD_RECOVERY_SUCCESS)
        {
          $Output .= $Form->ShowEditForm();
        }        
      } else
      if($_GET['Action'] == 'PasswordRecoveryConfirm')
      {
        $Output .= $this->SystemMessage('Obnova hesla', $this->System->Modules['User']->PasswordRecoveryConfirm($_GET['User'], $_GET['H'], $_GET['P']));
      } else
      if($_GET['Action'] == 'UserRegisterSave')
      {
        $Form = new Form('UserRegister', array());
        $Form->LoadValuesFromForm();
        $Result = $this->System->Modules['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);
        if($Result <> USER_REGISTRATED) 
        {
          $Form->OnSubmit = '?Action=UserRegisterSave';
          $Output .= $Form->ShowEditForm();
        }
      } else
      if($_GET['Action'] == 'ServerAdd')
      {
        if($this->System->Modules['User']->User['Role'] >= USER_ROLE_USER)
        {
          $DbResult = $this->Database->query('SELECT COUNT(*) FROM Server');
          $DbRow = $DbResult->fetch_row();
          $ServerCount = $DbRow[0];
          if($ServerCount < $Config['MaxServerCount'])
          {
            $DbResult = $this->Database->query('SELECT COUNT(*) FROM Server WHERE User='.$this->System->Modules['User']->User['Id']);
            $DbRow = $DbResult->fetch_row();
            if($DbRow[0] > 0) $Output .= $this->SystemMessage('Nový server', 'Lze vytvořit pouze jeden server pro každý uživatelský účet.');
            else 
            {
              $Form = new Form('NewServer');
              $Form->LoadValuesFromForm();
              $Form->OnSubmit = '?Action=ServerCreate';
              $Output .= 'Tento formulář vám umožní si vytvořit nový server. Pečlivě vyplňte požadované údaje.';
              $Output .= $Form->ShowEditForm();
            }
          } else $Output .= $this->SystemMessage('Nový serve', 'Nelze vytvářet další servery');
        } else $Output .= USER_BAD_ROLE;
      } else
      if($_GET['Action'] == 'ServerCreate')
      {
        if($this->System->Modules['User']->User['Role'] >= USER_ROLE_USER)
        {
          $DbResult = $this->Database->query('SELECT COUNT(*) FROM Server WHERE User='.$this->System->Modules['User']->User['Id']);
          $DbRow = $DbResult->fetch_row();
          if($DbRow[0] > 0) $Output .= $this->SystemMessage('Nový server', 'Lze vytvořit pouze jeden server pro každý uživatelský účet.');
          else 
          {
            $Form = new Form('NewServer', array());
            $Form->LoadValuesFromForm();
            $this->Database->insert('Server', array('Name' => $Form->Values['Name'], 'Description' => $Form->Values['Description'], 'User' => $this->System->Modules['User']->User['Id'], 'Motd' => $Form->Values['Motd'], 'Homepage' => $Form->Values['Homepage'], 'Type' => $Form->Values['Type'], 'Database' => 1));
            $LastInsertId = $this->Database->insert_id;
            $Server = new Server($this->Database, $LastInsertId);
            $Server->CreateDatabase();
            $Output .= $this->SystemMessage('Nový server', 'Server vytvořen.');
            //$UserOptions->LoadValuesFromDatabase($this->System->Modules['User']->User['Id']);
            //$Form->OnSubmit = '?Action=ServerCreate';
            //$Output .= $Form->ShowEditForm();
          }
        } else $Output .= USER_BAD_ROLE;
      } else
      if($_GET['Action'] == 'ServerShow')
      {
        if(array_key_exists('Id', $_GET)) $Output .= $this->ShowServer($_GET['Id']);
          else 
          {
            $DbResult = $this->Database->query('SELECT Id FROM Server WHERE User='.$this->System->Modules['User']->User['Id']);
            $Server = $DbResult->fetch_assoc();
            $Output .= $this->ShowServer($Server['Id']);
          }
      } else
      if($_GET['Action'] == 'ServerEdit')
      {
        if($this->System->Modules['User']->User['Role'] >= USER_ROLE_USER)
        {
          $DbResult = $this->Database->query('SELECT Id FROM Server WHERE User='.$this->System->Modules['User']->User['Id']);
          $Server = $DbResult->fetch_assoc();
          $Form = new Form('EditServer');
          $Form->LoadValuesFromDatabase($Server['Id']);
          $Form->OnSubmit = '?Action=ServerSave';
          $Output .= $Form->ShowEditForm();
        } else $Output .= USER_BAD_ROLE;
      } else
      if($_GET['Action'] == 'ServerSave')
      {
        if($this->System->Modules['User']->User['Role'] >= USER_ROLE_USER)
        {
          $DbResult = $this->Database->query('SELECT Id FROM Server WHERE User='.$this->System->Modules['User']->User['Id']);
          $Server = $DbResult->fetch_assoc();
          $UserOptions = new Form('EditServer', array());
          $UserOptions->LoadValuesFromForm();
          $Output .= $this->SystemMessage('Upravit server', 'Nastavení serveru uloženo.');
          $UserOptions->SaveValuesToDatabase($Server['Id']);
          $UserOptions->OnSubmit = '?Action=ServerSave';
        
          $Server = new Server($this->Database, $Server['Id']);
          $Server->SaveConfiguration();

          $Output .= $UserOptions->ShowEditForm();
        } else $Output .= USER_BAD_ROLE;
      } else
      if($_GET['Action'] == 'ServerStart')
      {
        if($this->System->Modules['User']->User['Role'] >= USER_ROLE_USER)
        {
          $DbResult = $this->Database->query('SELECT Id FROM Server WHERE User='.$this->System->Modules['User']->User['Id']);
          $Server = $DbResult->fetch_assoc();
          $Server = new Server($this->Database, $Server['Id']);
          $Output .= $this->SystemMessage('Spuštění serveru', $Server->Start());
        } else $Output .= USER_BAD_ROLE;
      } else
      if($_GET['Action'] == 'ServerStop')
      {
        if($this->System->Modules['User']->User['Role'] >= USER_ROLE_USER)
        {
          $DbResult = $this->Database->query('SELECT Id FROM Server WHERE User='.$this->System->Modules['User']->User['Id']);
          $Server = $DbResult->fetch_assoc();
          $Server = new Server($this->Database, $Server['Id']);
          $Output .= $this->SystemMessage('Zastavení serveru', $Server->Stop());
        } else $Output .= USER_BAD_ROLE;
      } else
      if($_GET['Action'] == 'ServerDatabaseImport')
      {
        if($this->System->Modules['User']->User['Role'] >= USER_ROLE_USER)
        {
          $DbResult = $this->Database->query('SELECT Id FROM Server WHERE User='.$this->System->Modules['User']->User['Id']);
          $Server = $DbResult->fetch_assoc();
          $Server = new Server($this->Database, $Server['Id']);
          $Server->ImportDatabase(true);
          $Output .= $this->SystemMessage('Import čisté databáze', 'Úloha zařazena do fronty');
        } else $Output .= USER_BAD_ROLE;
      } else
      if($_GET['Action'] == 'EmulatorShow')
      {
        if(array_key_exists('Id', $_GET)) 
        {
          $Output .= $this->EmulatorShow($_GET['Id']);
        } else $Output .= $this->SystemMessage('Překlad emulátoru', 'Nebylo zadáno Id');
      } else
      if($_GET['Action'] == 'EmulatorList')
      {
        $Output .= $this->ShowEmulatorList();
      } else
      if($_GET['Action'] == 'EmulatorCompile')
      {
        if(array_key_exists('Id', $_GET)) 
        {
          $Emulator = new Emulator($this->Database, $_GET['Id']);
          $Emulator->Compile();       
          $Output .= $this->SystemMessage('Překlad emulátoru', 'Úloha zařazena do fronty');
        } else $Output .= $this->SystemMessage('Překlad emulátoru', 'Nebylo zadáno Id');
      } else
      if($_GET['Action'] == 'Test')
      {
        //$Emulator = new Emulator($this->Database, 2);
        //  $Emulator->Compile();
        //$Server = new Server($this->Database, 1);
        //$Output .= $Server->ImportDatabase();
        //$Config = new MangosConfigurationFile($this->Database);
        //$Config->Load('../emu/mangos/7681/etc/mangosd.conf');
        //$Config->Save('../server/1/etc/mangosd.conf');
      } else
      {
        $Output = $this->ShowServerList();
      }
    } else 
    {
      $Output = $this->ShowServerList();
    }
    return($Output);
  }
}

$System->AddModule(new Index());
$System->Modules['Index']->GetOutput();

?>
