<?php

class SystemController extends Controller
{

  public $layout = '//layouts/column2';

  public function actionStatusBox()
  {
    $sysStausList = SystemStatus::model ()->findAll ();
    return $this->renderPartial ( '_systemStatusSummaryBox', array (
        'sysStausList' => $sysStausList 
    ) );
  }

  protected function getSystemInfo()
  {
    $env = new Environment ();
    return $env->getConfig ();
  }

  public function actionRepair()
  {
    $repairAll = true;
    
    $tableNames = query ( "SELECT DISTINCT TABLE_NAME AS 'table' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=:db ORDER BY TABLE_NAME", array (
        ':db' => getDbName () 
    ), false, true );
    
    $tables = array ();
    foreach ( $tableNames as $t )
    {
      $tableName = $t->table;
      $tinfo = array ();
      $tinfo [0] = array ();
      $tinfo [0] ['Table'] = null;
      $tinfo [0] ['Op'] = null;
      $tinfo [0] ['Msg_type'] = null;
      $tinfo [0] ['Msg_text'] = null;
      $tables [$tableName] = $tinfo;
    }
    
    foreach ( $tables as $tableName => $tableMessages )
    {
      $results = query ( "REPAIR TABLE {$tableName}", array (), false, false );
      $tables [$tableName] = $results;
    }
    
    $this->redirectTo ( '/' );
  }

  public function actionSetup()
  {
    if (User::model ()->count () <= 0)
    {
      $model = new User ();
      
      $model->username = 'admin';
      $model->password = $model->hashPassword ( 'admin' );
      $model->password_repeat = $model->password;
      $model->password_last_update = date ( "Y-m-d H:i:s" );
      $model->apikey = rand_str ( '0123456789QAZWSXEDCRFVTGBYHNUJMIKOLP', 32 );
      $model->create_time = DateHelper::ensureObjectEx ( null );
      $model->update_time = DateHelper::ensureObjectEx ( null );
      $model->email = "support@kria.biz";
      $model->superuser = true;
      $model->status = User::STATUS_ACTIVE;
      $model->first_name = null;
      $model->last_name = null;
      $model->matriculation_number = null;
      $model->password_timeout = null;
      $model->can_change_password = true;
      $model->refresh_password_at_first_login = false;
      
      $model->insert ();
    }
    
    $this->redirectTo ( '/' );
  }

  public function actionConfig()
  {
    access_denied_check ( 'system_management' );
    
    if (isset ( $_REQUEST ['authorization'] ) || DebugController::isInDebugMode ())
    {
      $target = $_REQUEST ['target'];
      if (! $this->checkPassword ( $_REQUEST ['authorization'] ) && ! DebugController::isInDebugMode ())
      {
        user ()->setFlash ( 'error', t ( "Wrong password!" ) );
      }
      else
      {
        $this->render ( 'info', array (
            'ok' => true,
            'key' => 'configuration',
            'value' => $this->getSystemInfo () 
        ) );
        return;
      }
    }
    
    $this->render ( 'info', array (
        'ok' => false 
    ) );
  }

  public function actionConfigExport()
  {
    access_denied_check ( 'system_management' );
    
    $configurations = array ();
    $configurations ['global'] = t ( 'Global configuration' );
    $configPath = app ()->basePath . "\\config";
    $configDir = dir ( $configPath );
    while ( $filename = $configDir->read () )
    {
      if (is_file ( $configPath . "\\" . $filename ) && endsWith ( $filename, '.php' ))
      {
        $configurations [$filename] = $filename;
      }
    }
    
    if (isset ( $_REQUEST ['target'] ) && (isset ( $_REQUEST ['authorization'] ) || DebugController::isInDebugMode ()))
    {
      $target = $_REQUEST ['target'];
      if (! $this->checkPassword ( $_REQUEST ['authorization'] ) && ! DebugController::isInDebugMode ())
      {
        user ()->setFlash ( 'error', t ( "Wrong password!" ) );
      }
      else
      {
        if (! array_key_exists ( $target, $configurations ))
        {
          user ()->setFlash ( 'error', t ( "Configuration not found!" ) . $backupPath );
        }
        else
        {
          $now = DateHelper::ensureObjectEx ()->toFilesafeDateTimeString ();
          if ($target == "global")
          {
            $config = $this->getSystemInfo ();
            $eol = PHP_EOL;
            $code = "<?php $eol $eol return " . var_export ( $config, true ) . "; $eol";
            $configName = $now . "_global_configuration.php";
          }
          else
          {
            $code = file_get_contents ( $configPath . "\\" . $target );
            $configName = $now . '_' . $target;
          }
          prepare_download ( $configName );
          echo ($code);
          exit ();
        }
      }
    }
    
    $this->render ( 'export', array (
        'configurations' => $configurations 
    ) );
  }

  public function actionConfigImport()
  {
    access_denied_check ( 'system_management' );
    
    if (isset ( $_FILES ['userfile'] ) && (isset ( $_REQUEST ['authorization'] ) || DebugController::isInDebugMode ()) && file_exists ( $_FILES ['userfile'] ['tmp_name'] ))
    {
      if (! $this->checkPassword ( $_REQUEST ['authorization'] ) && ! DebugController::isInDebugMode ())
      {
        user ()->setFlash ( 'error', t ( "Wrong password!" ) );
      }
      else
      {
        $now = DateHelper::ensureObjectEx ();
        
        $newConfigValue = file_get_contents ( $_FILES ['userfile'] ['tmp_name'] );
        
        $localPhpFilename = app ()->basePath . "\\config\\local.php";
        $localPhpBakFilename = app ()->basePath . "\\config\\backup_" . $now->toFilesafeDateTimeString () . "_local.php";
        
        $canProceed = false;
        
        if (file_exists ( $localPhpFilename ))
        {
          if (copy ( $localPhpFilename, $localPhpBakFilename ))
          {
            $canProceed = true;
          }
          else
          {
            user ()->setFlash ( 'error', t ( "Backup of previous configuration has failed!" ) );
          }
        }
        else
        {
          $canProceed = true;
        }
        
        if ($canProceed)
        {
          if (file_put_contents ( $localPhpFilename, $newConfigValue ) === false)
          {
            if (! copy ( $localPhpBakFilename, $localPhpFilename ))
            {
              user ()->setFlash ( 'error', t ( "New and old configurations were not applied!" ) );
            }
            else
            {
              user ()->setFlash ( 'notice', t ( "Cannot apply the new configuration!" ) );
            }
          }
          else
          {
            user ()->setFlash ( 'success', t ( "New configuration applied to the system!" ) );
          }
        }
      }
    }
    
    $this->render ( 'import' );
  }

  /**
   *
   * @param string $password          
   * @return boolean
   */
  protected function checkPassword($password)
  {
    return kria_password ( $password ) == paramdeep ( 'configurationEditor', 'password' );
  }

  public function actionConfigRestore()
  {
    access_denied_check ( 'system_management' );
    
    $configPath = app ()->basePath . "\\config";
    $configDir = dir ( $configPath );
    $backups = array ();
    while ( $filename = $configDir->read () )
    {
      if (is_file ( $configPath . "\\" . $filename ) && startsWith ( $filename, 'backup_' ))
      {
        $backups [$filename] = $filename;
      }
    }
    
    if (isset ( $_REQUEST ['backup'] ) && (isset ( $_REQUEST ['authorization'] ) || DebugController::isInDebugMode ()) && isset ( $_REQUEST ['action'] ))
    {
      $actionDelete = $_REQUEST ['action'] == 'delete';
      if (! $this->checkPassword ( $_REQUEST ['authorization'] ) && ! DebugController::isInDebugMode ())
      {
        user ()->setFlash ( 'error', t ( "Wrong password!" ) );
      }
      else
      {
        $backupName = $_REQUEST ["backup"];
        $backupPath = $configPath . "\\" . $backupName;
        if (array_value_exists ( $backups, $_REQUEST ["backup"] ) && file_exists ( $backupPath ))
        {
          if ($actionDelete)
          {
            if (unlink ( $backupPath ))
              user ()->setFlash ( 'success', t ( "Configuration deleted!" ) );
            else
              user ()->setFlash ( 'error', t ( "Configuration cannot be deleted!" ) );
          }
          else
          {
            $now = DateHelper::ensureObjectEx ();
            
            $localPhpFilename = app ()->basePath . "\\config\\local.php";
            $localPhpBakFilename = app ()->basePath . "\\config\\backup_" . $now->toFilesafeDateTimeString () . "_local.php";
            
            $canProceed = false;
            
            if (file_exists ( $localPhpFilename ))
            {
              if (copy ( $localPhpFilename, $localPhpBakFilename ))
              {
                $canProceed = true;
              }
              else
              {
                user ()->setFlash ( 'error', t ( "Backup of previous configuration has failed!" ) );
              }
            }
            else
            {
              $canProceed = true;
            }
            
            if ($canProceed)
            {
              if (copy ( $backupPath, $localPhpFilename ))
              {
                user ()->setFlash ( 'success', t ( "Old configuration applied to the system!" ) );
              }
              else
              {
                user ()->setFlash ( 'notice', t ( "Cannot apply the old configuration!" ) );
              }
            }
          }
        }
        else
        {
          user ()->setFlash ( 'error', t ( "Configuration not found!" ) . $backupPath );
        }
      }
    }
    
    $configDir = dir ( $configPath );
    $backups = array ();
    while ( $filename = $configDir->read () )
    {
      if (startsWith ( $filename, 'backup_' ))
      {
        $backups [$filename] = $filename;
      }
    }
    
    $this->render ( 'restore', array (
        'backups' => $backups 
    ) );
  }
}
