<?php

class ModuleAdmin extends Module
{
  function __construct(System $System)
  {
    parent::__construct($System);
    $this->Name = 'Admin';
    $this->Version = '1.0';
    $this->Creator = 'Chronos';
    $this->License = 'GNU/GPL';
    $this->Description = 'Administrator section of the web';
    $this->Dependencies = array('Translation');
  }

  function DoStart(): void
  {
    Core::Cast($this->System)->RegisterMenuItem(array(
      'Title' => T('Administration'),
      'Hint' => T('Administration tools'),
      'Link' => $this->System->Link('/admin/'),
      'Permission' => LICENCE_ADMIN,
      'Icon' => '',
    ));
    $this->System->RegisterPage(['admin'], 'PageAdmin');
  }
}

class PageAdmin extends Page
{
  function ShowMenu()
  {
    $Output = '<h3>'.T('Administration tools').'</h3>';

    $Output .= '<br />'.
      '<a href="https://'.Core::Cast($this->System)->Config['Web']['Host'].'/phpmyadmin/">'.T('Database management').'</a><br/>'.
      '<small>Rozhraní phpMyAdmin pro přímou správu databáze</small><br/><br/>'.
      '<a href="'.$this->System->Link('/import/').'">'.T('Text import').'</a><br/>'.
      '<small>Načtení zdrojových textů do databáze</small><br/><br/>'.
      '<a href="'.$this->System->Link('/log/').'">'.T('Event log').'</a><br/>'.
      '<small>Procházení všech systémových záznamů akcí a událostí</small><br/><br/>'.
      '<a href="'.$this->System->Link('/admin/?action=testing').'">'.T('Testing').'</a><br/>'.
      '<small>Testovací funkce</small><br/><br/>'.
      '<a href="'.$this->System->Link('/admin/?action=locale').'">'.T('Export of the web interface translation').'</a><br/>'.
      '<small>Exportovat texty z PHP souborů pro překlad rozhraní</small><br/><br/>'.
      '<a href="'.$this->System->Link('/admin/?action=uncomplete').'">Nastavit nekompletní texty</a><br/>'.
      '<small>Nastaví questy, které jsou v popisu nebo objektu stejné jako nedokončené</small><br/><br/>'.
      '<a href="'.$this->System->Link('/admin/?action=repairversion').'">Opravit špatně nastavené VersionEnd</a><br/>'.
      '<small>Nastaví špatné version end a Take na originální text, které vzniklo v důsledku importu a špatně indexovaného indexu Take</small><br/><br/>'.
      '<a href="'.$this->System->Link('/admin/?action=dbcstructure').'">Připravit dbc strukturu</a><br/>'.
      '<small>Otevře dbc soubory převedené do textové formy pro přípravu struktury pro import</small><br/><br/>'.
      '<a href="'.$this->System->Link('/admin/?action=merge').'">Sjednocení textů</a><br/>'.
      '<small>Sjednotí stejné originální texty v databázi</small><br/><br/>';
    return $Output;
  }

  function TestError($P1, $P2)
  {
    $s = $TT[0];
  }

  function TestException($P1, $P2)
  {
    throw new Exception('Test exception');
  }

  function TestSQLError($Query)
  {
    $DbResult = $this->System->Database->query($Query);
  }

  function ShowPHPInfo()
  {
    return phpinfo();
  }

  function Testing()
  {
    $this->Title = T('Testing');
    $Output = '<a href="'.$this->System->Link('/admin/?action=phpinfo').'">PHP info</a><br/>'.
      '<small>PHP informace</small><br/><br/>'.
      '<a href="'.$this->System->Link('/admin/?action=error').'">Testovací chyba</a><br/>'.
      '<small>Vyvolá testovací chybu</small><br/><br/>'.
      '<a href="'.$this->System->Link('/admin/?action=exception').'">Testovací výjimka</a><br/>'.
      '<small>Vyvolá testovací chybu</small><br/><br/>'.
      '<a href="'.$this->System->Link('/admin/?action=sqlerror').'">Chybný SQL dotaz</a><br/>'.
      '<small>Vyvolá testovací chybu</small><br/><br/>';
    return $Output;
  }

  function Uncomplete()
  {
    $DbResult = $this->System->Database->query('SELECT  `gs_tran`.`ID`,`gs_tran`.`Details`,`gs_tran`.`Objectives` FROM '
      .'`TextQuest` AS  `gs_tran` '
      .'JOIN  `TextQuest` AS  `gs_orig` ON  `gs_orig`.`Entry` =  `gs_tran`.`Entry` '
      .'AND  `gs_orig`.`Language` =0 '
      .'WHERE  `gs_tran`.`Language` !=0 '
      .'AND  `gs_tran`.`Complete` =1 '
      .'AND ( (`gs_tran`.`Details` =  `gs_orig`.`Details` AND  "" !=  `gs_orig`.`Details` )'
      .' OR ( `gs_tran`.`Objectives` !=  `gs_orig`.`Objectives` AND  "" =  `gs_tran`.`Objectives` )'
      .' OR ( `gs_tran`.`Details` !=  `gs_orig`.`Details` AND  "" =  `gs_tran`.`Details` )'
      .' OR (`gs_tran`.`Objectives` =  `gs_orig`.`Objectives` AND  "" !=  `gs_orig`.`Objectives` ))'
    );
    $Output = 'Questy: <br />';
    while ($quest = $DbResult->fetch_assoc())
    {
      $Output .= $quest['ID'].', ';
      $this->System->Database->query('UPDATE `TextQuest` SET `complete` = 0 WHERE ID='.$quest['ID']);
    }
    $Output .= '<br / ><br / >Questy nastaveny jako nedokončené!';
    return $Output;
  }

  function RepairVersionEnd()
  {
    $TranslationTree = ModuleTranslation::Cast($this->System->ModuleManager->GetModule('Translation'))->GetTranslationTree();

    $Output = '';
    foreach ($TranslationTree as $Group)
    // $Group = $TranslationTree[1];
    {

      $sql = 'SELECT `T`.`ID`,`T`.`Take`,`sub1`.`ID` as `origID`,T.`VersionStart`,T.`VersionEnd`,`sub1`.`VersionStart` as OrigStart,sub1.`VersionEnd` as `OrigEnd` FROM `'.$Group['TablePrefix'] .'` as `T` '.
        ' JOIN `'.$Group['TablePrefix'].'` as `sub1` ON `sub1`.`Language` = 0 AND `T`.`Entry` = `sub1`.`Entry` AND `T`.`VersionStart` = `sub1`.`VersionStart` '.
        ' WHERE `T`.`Take` != `sub1`.`ID` AND `T`.`Language` != 0'.
          //  ' WHERE `T`.`Language` != 0 AND `T`.`VersionEnd` != `sub1`.`VersionEnd` AND `T`.`Take` NOT IN'.
      //  '(Select `ID` FROM `'.$Group['TablePrefix'].'` as `sub2` WHERE `sub2`.`Language` = 0 AND `T`.`Entry` = `sub2`.`Entry` AND `T`.`VersionStart` = `sub2`.`VersionStart`)'.
      ' ';  //LIMIT 1000
      $DbResult = $this->System->Database->query($sql);
      echo ': <br />'.$Group['TablePrefix'].': <br />';
      while ($line = $DbResult->fetch_assoc())
      {
        echo ($line['ID'].', ');
        $this->System->Database->query('UPDATE `'.$Group['TablePrefix'].'` SET `VersionEnd` = '.
          $line['OrigEnd'].', `Take` = '.$line['origID'].'  WHERE ID='.$line['ID']);
      }
      echo '<br / >Verze '.$Group['TablePrefix'].' opraveny!';
    }
    return 'Hotovo!';
  }

  function StripText($Text)
  {
    $Text = strtolower($Text);
    $Text = str_replace(' ', '', $Text);
    return $Text;
  }

  function MergeSameText()
  {
    $TranslationTree = ModuleTranslation::Cast($this->System->ModuleManager->GetModule('Translation'))->GetTranslationTree();

    $Output = '';
    foreach ($TranslationTree as $Group)
    //  $Group = $TranslationTree[1];
    {

      $sql = 'SELECT * FROM `'.$Group['TablePrefix'] .'` as `T` '.
          //  ' JOIN `'.$Group['TablePrefix'].'` as `sub1` ON `sub1`.`Language` = 0 AND `T`.`Entry` = `sub1`.`Entry` AND `T`.`VersionStart` < `sub1`.`VersionStart` '.
      ' WHERE `T`.`Language` = 0 '.
      ' ORDER BY `T`.`VersionStart`';  //LIMIT 1000
      $DbResult = $this->System->Database->query($sql);
      echo ': <br />'.$Group['TablePrefix'].': ';
      while ($line = $DbResult->fetch_assoc())
      {
        $sql = 'SELECT * FROM `'.$Group['TablePrefix'] .'` as `T` '.
            ' WHERE  `T`.`Language` = 0 AND `T`.`VersionStart` > '.$line['VersionEnd'].' AND `T`.`Entry` = '.$line['Entry'].
            ' ORDER BY `T`.`VersionStart` LIMIT 1';  //LIMIT 1000
        $DbResult2 = $this->System->Database->query($sql);
        if ($DbResult2->num_rows > 0)
        {
          $line2 = $DbResult2->fetch_assoc();

          $Same = true;
          foreach ($TranslationTree[$Group['Id']]['Items'] as $Column)
          {
            if ($this->StripText($line[$Column['Column']]) <> $this->StripText($line2[$Column['Column']]))
              $Same = false;
          }
          if ($Same)
          {
            echo $line['ID'].'='.$line2['ID'].' (';
            //       $this->System->Database->query('UPDATE `'.$Group['TablePrefix'].'` SET `Take` = NULL WHERE ID='.$line2['ID']);

            $sql = 'SELECT * FROM `'.$Group['TablePrefix'] .'` as `T` '.
                ' WHERE `T`.`Entry` = '.$line['Entry'].' AND (`T`.`Take` = '.$line['ID'].' OR `T`.`Take` = '.$line2['ID'].') ';
            $DbResult3 = $this->System->Database->query($sql);
            while ($line3 = $DbResult3->fetch_assoc())
            {
              echo $line3['ID'].' ';
              $this->System->Database->query('UPDATE `'.$Group['TablePrefix'].'` SET `VersionEnd` = '.$line2['VersionEnd'].', `VersionStart` = '.$line['VersionStart'].', `Take` = '.$line['ID'].' WHERE ID='.$line3['ID']);
            }

            $this->System->Database->query('DELETE FROM`'.$Group['TablePrefix'].'` WHERE ID='.$line2['ID']);
            $this->System->Database->query('UPDATE `'.$Group['TablePrefix'].'` SET `VersionEnd` = '.$line2['VersionEnd'].' WHERE ID='.$line['ID']);
            echo '), ';
          }
        }
      }
      echo('Texty '.$Group['TablePrefix'].' sjednoceny!');
    }
    return 'Hotovo!';
  }

  function DbcStructure()
  {
    $TranslationTree = ModuleTranslation::Cast($this->System->ModuleManager->GetModule('Translation'))->GetTranslationTree();

    $Output = '';
    if (array_key_exists('GameVersion', $_GET))
    {
      $_SESSION['GameVersion'] = $_GET['GameVersion'];
    }
    if (!array_key_exists('GameVersion', $_SESSION))
      $_SESSION['GameVersion'] = Core::Cast($this->System)->Config['Web']['GameVersion'];

      $Output .= '<br />Nastavená verze: '.$_SESSION['GameVersion'].'<br />';

      if (array_key_exists('GroupItem', $_GET)) {
        $DbResult = $this->System->Database->query('SELECT * FROM `ClientVersion` WHERE `Version` = "'.$_SESSION['GameVersion'].'"');
        $Version = $DbResult->fetch_assoc();
        $this->System->Database->query('INSERT INTO  `GroupItemDBC` (`Id` ,`ClientVersion` ,`GroupItem` ,`ColumnIndex`)VALUES (NULL ,  \''.$Version['Id'].'\',  \''.$_GET['GroupItem'].'\',  \''.$_GET['ColumnIndex'].'\')');
        $Output .= 'vloženo <br />';
      }
      if (array_key_exists('id', $_GET))
      {
        $Group = $TranslationTree[$_GET['id']];
        //  $Output .= '<form action="?action=dbcstructure&amp;id='.$Group['Id'].'">';
        //  foreach ($Group['Items'] as $GroupItem)
        //   {
          //     $Output .= $GroupItem['Column'].': <input name="'.$GroupItem['Id'].'"><br />';
          //   }
        //      $Output .= '<input type="submit" value="uložit"></form>';

        $FileName = NormalizePath(dirname(__FILE__).'/../source/'.$_SESSION['GameVersion'].'/dbc/'.$Group['DBCFileName'].'.dbc.csv');
        $File = new FileStream();
        $File->OpenFile($FileName);

        //while (!$File->EOF())

        $Output .= '<table class="BaseTable">';
        $Output .= '<tr><td>';
        $Line = $File->ReadLine();

        for ($i = 0; $i < substr_count($Line, ','); $i++)
        {
          $Output .= $i;
          $Output .= '</td><td>';
        }
        $Output .= '</td></tr><tr><td>';
        for ($i = 0; $i < substr_count($Line, ','); $i++)
        {
          foreach ($Group['Items'] as $GroupItem)
          {
            $Output .=   ' <a href="'.$this->System->Link('/admin/?action=dbcstructure&amp;id='.
              $Group['Id'].'&amp;GroupItem='.$GroupItem['Id'].'&amp;ColumnIndex='.$i).'">'.
              $GroupItem['Column'].'</a><br/>';
          }
          $Output .= '</td><td>';
        }

        $Output .= '</td></tr><tr><td>';

        $Output .= str_replace(',', '</td><td>', $Line);
        $Output .= '</td></tr><tr><td>';
        for ($i = 0; $i < 50; $i++)
        {
          $Line = $File->ReadLine();
          $Output .= str_replace(',', '</td><td>', $Line);
          $Output .= '</td></tr><tr><td>';
        }

        $Output .= '</td></tr>';
        $Output .= '</table>';
      } else
      {
        $DbResult = $this->System->Database->query('SELECT * FROM `ClientVersion`');
        while ($Version = $DbResult->fetch_assoc())
        {
          $Output .= '<a href="'.$this->System->Link('/admin/?action=dbcstructure&amp;GameVersion='.
            $Version['Version']).'">'.$Version['Version'].'</a> ';
        }
        $Output .= '<br /><br />';

        foreach ($TranslationTree as $Group)
        {
          if ($Group['DBCFileName'] <> '')
            $Output .=   '<a href="'.$this->System->Link('/admin/?action=dbcstructure&amp;id='.
              $Group['Id']).'">'.$Group['DBCFileName'].'</a><br/>';
        }
      }
      return $Output;
  }

  function ShowLocale()
  {
    Core::Cast($this->System)->LocaleManager->UpdateAll(dirname(dirname(__FILE__)));
    $Output = 'Překlad rozhraní přegenerován';
    $Output .= '<table class="BaseTable"><tr><th>Originál</th><th>Překlad</th></tr>';
    foreach (Core::Cast($this->System)->LocaleManager->CurrentLocale->Texts->Data as $Index => $Item)
      $Output .= '<tr><td>'.$Index.'</td><td>'.$Item.'</td></tr>';
    $Output .= '</table>';
    $Output .= 'Překladové soubory zaktualizovány';
    return $Output;
  }

  function Show(): string
  {
    $User = ModuleUser::Cast($this->System->GetModule('User'))->User;
    $this->Title = T('Administration');
    $Output = '';
    if ($User->Licence(LICENCE_ADMIN))
    {
      if (array_key_exists('action', $_GET))
      {
        if ($_GET['action'] == 'error') $Output .= $this->TestError(12, 'test');
        else if ($_GET['action'] == 'exception') $Output .= $this->TestException(12, 'test');
        else if ($_GET['action'] == 'sqlerror') $Output .= $this->TestSQLError('SELECT dads FROM sdas');
        else if ($_GET['action'] == 'testing') $Output .= $this->Testing();
        else if ($_GET['action'] == 'phpinfo') $Output .= $this->ShowPHPInfo();
        else if ($_GET['action'] == 'locale') $Output .= $this->ShowLocale();
        else if ($_GET['action'] == 'uncomplete') $Output .= $this->Uncomplete();
        else if ($_GET['action'] == 'repairversion') $Output .= $this->RepairVersionEnd();
        else if ($_GET['action'] == 'dbcstructure') $Output .= $this->DbcStructure();
        else if ($_GET['action'] == 'merge') $Output .= $this->MergeSameText();
        else $Output .= $this->ShowMenu();
      } else $Output .= $this->ShowMenu();
    } else $Output .= ShowMessage(T('Access denied'), MESSAGE_CRITICAL);
    return $Output;
  }
}
