<?php

class ModuleError extends Module
{
  public string $Encoding;
  public ErrorHandler $ErrorHandler;

  function __construct(System $System)
  {
    parent::__construct($System);
    $this->Name = 'Error';
    $this->Version = '1.0';
    $this->Creator = 'Chronos';
    $this->License = 'GNU/GPLv3';
    $this->Description = 'Error logging and reporting';
    $this->Dependencies = array(ModuleLog::GetName());

    $this->ErrorHandler = new ErrorHandler();
    $this->Encoding = 'utf-8';
  }

  function DoStart(): void
  {
    $this->ErrorHandler->ShowError = Core::Cast($this->System)->Config['Web']['ShowPHPError'];
    $this->ErrorHandler->OnError = array(array($this, 'DoOnError'));
    $this->ErrorHandler->Start();
  }

  function DoStop(): void
  {
    $this->ErrorHandler->Stop();
  }

  function DoOnError(string $Error): void
  {
    ModuleLog::Cast($this->System->GetModule('Log'))->NewRecord('Error', 'Log', $Error);

    //if ($Config['Web']['ErrorLogFile'] != '')
    // error_log($Error, 3, $Config['Web']['ErrorLogFile']);
    // Pošli mi zprávu (pokud je to kritická chyba)
    //mail($Config['Web']['AdminEmail'], $Config['Web']['Title'].' - Chybové hlášení', $Error);
    // Show error message
    if ($this->ErrorHandler->ShowError == true)
    {
      if (array_key_exists('REMOTE_ADDR', $_SERVER))
      {
        echo('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head>'."\n".
            '<meta http-equiv="Content-Language" content="cs">'."\n".
            '<meta http-equiv="Content-Type" content="text/html; charset='.$this->Encoding.'"></head><body>'."\n".
            'Došlo k vnitřní chybě!<br/> O chybě byl uvědoměn správce webu a chybu brzy odstraní.<br/><br/>');
        echo('<pre>'.$Error.'</pre><br/>');     // V případě ladění chybu i zobraz
        echo('</body></html>');
      } else
      {
        echo($Error);
      }
    }
  }
}
