<?php

include_once('ExportOutput.php');

define('TAB_GENERAL', 0);
define('TAB_TRANSLATORS', 1);
define('TAB_GROUPS', 2);
define('TAB_LANGUAGES', 3);
define('TAB_OUTPUT_FORMAT', 4);
define('TAB_VERSION', 5);
define('TAB_STAT', 6);
define('TAB_OUTPUT', 7);

class PageExport extends Page
{
  function ExportList()
  {
    $Output = '<a href="?Action=ViewList">'.T('All').'</a>';
    if($this->System->User->Licence(LICENCE_USER))
    {
      $Output .= ' <a href="?Action=ViewList&amp;Filter=Others">Ostatních</a>'.
          ' <a href="?Action=ViewList&amp;Filter=My">'.T('Mine').'</a>';
    }

    if($this->System->User->Licence(LICENCE_USER))
      $Output .= '<br/><div style="text-align: center;"><a href="?Action=Create">'.T('Create new export').'</a></div><br/>';

    $Filter = '';
    if(array_key_exists('Filter', $_GET))
    {
      if($_GET['Filter'] == 'My') $Filter = ' WHERE `Export`.`User` = '.$this->System->User->Id;
      if($_GET['Filter'] == 'Others') $Filter = ' WHERE `Export`.`User` != '.$this->System->User->Id;
    }

    $DbResult = $this->System->Database->query('SELECT COUNT(*) FROM `Export` '.$Filter);
    $DbRow = $DbResult->fetch_row();
    $PageList = GetPageList($DbRow[0]);

    $Output .= '<h3>'.T('List of export').'</h3>'.
        $PageList['Output'];

    $TableColumns = array(
        array('Name' => 'TimeCreate', 'Title' => T('Time made')),
        array('Name' => 'UserName', 'Title' => T('Translator')),
        array('Name' => 'Title', 'Title' => T('Name od export')),
        //  array('Name' => 'UserCount', 'Title' => 'Vybraných překladatelů'),
        //  array('Name' => 'GroupCount', 'Title' => 'Překladových skupin'),
        array('Name' => 'OutputType', 'Title' => T('Type of output')),
        array('Name' => 'ClientVersion', 'Title' => T('Client version')),
        array('Name' => 'UsedCount', 'Title' => T('Viewed count')),
        array('Name' => '', 'Title' => T('Action')),
    );
    $Order = GetOrderTableHeader($TableColumns, 'TimeCreate', 1);
    $Output .= '<table class="BaseTable">'.
        $Order['Output'];

    $DbResult = $this->System->Database->query('SELECT `User`.`Name` AS `UserName`, `Export`.`Id`, `Export`.`TimeCreate`, `Export`.`Title`, `Export`.`User`, `Export`.`UsedCount`, '.
      '(SELECT Version FROM `ClientVersion` WHERE `ClientVersion`.`Id`=`Export`.`ClientVersion`) AS `ClientVersion`, '.
      '(SELECT Id FROM `ClientVersion` WHERE `ClientVersion`.`Id`=`Export`.`ClientVersion`) AS `ClientVersionId`, '.
      '(SELECT Name FROM `ExportOutputType` WHERE `ExportOutputType`.`Id`=`Export`.`OutputType`) AS `OutputType`, '.
      '(SELECT COUNT(*) FROM `ExportGroup` WHERE `ExportGroup`.`Export`=`Export`.`Id`) AS `GroupCount`, '.
      '(SELECT COUNT(*) FROM `ExportUser` WHERE `ExportUser`.`Export`=`Export`.`Id`) AS `UserCount` FROM `Export` '.
      'LEFT JOIN `User` ON `User`.`ID`=`Export`.`User` '.$Filter.$Order['SQL'].$PageList['SQLLimit']);
    while($Export = $DbResult->fetch_assoc())
    {
      $Action = '<a href="?Action=View&amp;ExportId='.$Export['Id'].'&amp;Tab=0">'.T('View').'</a> '.
        '<a href="?Action=View&amp;ExportId='.$Export['Id'].'&amp;Tab=7">'.T('Make export').'</a>';
      if($Export['User'] == $this->System->User->Id) $Action .= ' <a href="?Action=Delete&amp;ExportId='.$Export['Id'].'" onclick="return confirmAction(\''.T('Realy delete item?').'\');">'.T('Delete').'</a>';
      if($this->System->User->Id != null) $Action .= ' <a href="?Action=Clone&amp;ExportId='.$Export['Id'].'" onclick="return confirmAction(\''.T('Realy clone item?').'\');">'.T('Clone').'</a>';
      $Output .= '<tr><td>'.HumanDate($Export['TimeCreate']).'</td>'.
          '<td><a href="'.$this->System->Link('/user/?user='.$Export['User']).'">'.$Export['UserName'].'</a></td>'.
          '<td>'.$Export['Title'].'</td>'.
          '<td>'.$Export['OutputType'].'</td>'.
          '<td><a href="'.$this->System->Link('/client-version/?action=item&amp;id='.$Export['ClientVersionId']).'">'.$Export['ClientVersion'].'</a></td>'.
          '<td>'.$Export['UsedCount'].'</td>'.
          '<td>'.$Action.'</td></tr>';
    }
    $Output .= '</table>'.
        $PageList['Output'];

    return($Output);
  }

  function ExportCreate()
  {
    if($this->System->User->Licence(LICENCE_USER))
    {
      $DbResult = $this->System->Database->query('SELECT COUNT(*) FROM `Export` WHERE `User`='.$this->System->User->Id);
      $DbRow = $DbResult->fetch_row();
      if($DbRow[0] < $this->System->Config['MaxExportPerUser'])
      {
        $Output = '<form action="?Action=CreateFinish" method="post">'.
            '<fieldset><legend>'.T('Creation of new export').'</legend>'.
            '<table><tr><td>'.T('Identification').':</td><td><input type="text" name="Title" /></td></tr>'.
            '<tr><td>'.T('Description').':</td><td><textarea name="Description" cols="54" rows="10"></textarea></td></tr>'.
            '<tr><td colspan="2"><input type="submit" value="'.T('Create').'" /></td></tr>'.
            '</table></fieldset></form>';
      } else $Output = ShowMessage(sprintf(T('You can\'t create another export. Max for one user is %d.'), $this->System->Config['MaxExportPerUser']), MESSAGE_CRITICAL);
    } else $Output = ShowMessage(T('Access denied'), MESSAGE_CRITICAL);
    return($Output);
  }

  function ExportCreateFinish()
  {
    if($this->System->User->Licence(LICENCE_USER))
    {
      if(array_key_exists('Title', $_POST) and array_key_exists('Description', $_POST))
      {
        $DbResult = $this->System->Database->query('SELECT COUNT(*) FROM `Export` WHERE `User`='.$this->System->User->Id);
        $DbRow = $DbResult->fetch_row();
        if($DbRow[0] < $this->System->Config['MaxExportPerUser'])
        {
          $this->System->Database->query('INSERT INTO `Export` (`Title`, `User`, `TimeCreate`, `WithDiacritic`, `Description`) VALUES ("'.$_POST['Title'].'", '.$this->System->User->Id.', NOW(), 1, "'.$_POST['Description'].'")');
          $ExportId = $this->System->Database->insert_id;
          $Output = ShowMessage(T('New export created.<br />Direct link to export').': <a href="?Action=View&amp;ExportId='.$ExportId.'">'.T('here').'</a>');
          $this->System->ModuleManager->Modules['Log']->WriteLog(T('New export created').' <a href="'.$this->System->Link('/export/?Action=View&amp;ExportId='.$ExportId).'">'.$ExportId.'</a>.', LOG_TYPE_EXPORT);
          $_GET['Filter'] = 'my';
          $this->ExportList();
        } else $Output = ShowMessage(sprintf(T('You can\'t create another export. Max for one user is %d.'),$this->System->Config['MaxExportPerUser']), MESSAGE_CRITICAL);
      } else $Output = ShowMessage(T('Missing data in form.'), MESSAGE_CRITICAL);
    } else $Output = ShowMessage(T('Access denied'), MESSAGE_CRITICAL);
    return($Output);
  }

  function ExportDelete()
  {
    if($this->System->User->Licence(LICENCE_USER))
    {
      $DbResult = $this->System->Database->query('SELECT * FROM `Export` WHERE (`Id`='.($_GET['ExportId'] * 1).') AND (`User`='.$this->System->User->Id.')');
      if($DbResult->num_rows > 0)
      {
        $this->System->Database->query('DELETE FROM `ExportGroup` WHERE `Export`='.$_GET['ExportId']);
        $this->System->Database->query('DELETE FROM `ExportGroupItem` WHERE `Export`='.$_GET['ExportId']);
        $this->System->Database->query('DELETE FROM `ExportLanguage` WHERE `Export`='.$_GET['ExportId']);
        $this->System->Database->query('DELETE FROM `ExportTask` WHERE `Export`='.$_GET['ExportId']);
        $this->System->Database->query('DELETE FROM `ExportUser` WHERE `Export`='.$_GET['ExportId']);
        $this->System->Database->query('DELETE FROM `Export` WHERE `Id`='.$_GET['ExportId']);
        DeleteDirectory('../tmp/Export/'.$_GET['ExportId'].'/');
        $Output = ShowMessage(T('Export deleted.'));
        $_GET['Filter'] = 'my';
        $this->System->ModuleManager->Modules['Log']->WriteLog('Smazán export '.$_GET['ExportId'], LOG_TYPE_EXPORT);
        $Output .= $this->ExportList();
      } else $Output = ShowMessage(T('Export not found.'), MESSAGE_CRITICAL);
    } else $Output = ShowMessage(T('Access denied'), MESSAGE_CRITICAL);
    return($Output);
  }

  function SaveAllUsers()
  {
   global $System;
      $Export = new Export($System);
      $Export->Id = $_GET['ExportId'];
      $Export->SaveAllUsers();

  }

  function ExportViewTranslators()
  {
    global $TranslationTree;

    $Output = '';
    $DisabledInput = array(false => ' disabled="disabled"', true => '');
    $DbResult = $this->System->Database->query('SELECT * FROM `Export` WHERE `Id`='.$_GET['ExportId']);
    $Export = $DbResult->fetch_assoc();
    if($this->System->User->Licence(LICENCE_USER) and ($this->System->User->Id == $Export['User'])) $Editable = true;
    else $Editable = false;

    if(array_key_exists('Operation', $_POST))
    {
      if($_POST['Operation'] == 'Save')
      {
        //print_r($_POST);
        // Update user selection page
        foreach($_POST as $Index => $Value)
        {
          if(substr($Index, 0, 3) == 'seq')
          {
            $UserId = substr($Index, 3) * 1;
            if(array_key_exists('sel'.$UserId, $_POST)) $Selected = true;
            else $Selected = false;
            $Condition = ' WHERE `Export`='.$_GET['ExportId'].' AND `User`='.$UserId;
            $DbResult = $this->System->Database->query('SELECT * FROM `ExportUser` '.$Condition);
            if($DbResult->num_rows > 0)
            {
              if(!$Selected) $this->System->Database->query('DELETE FROM `ExportUser` '.$Condition);
              else $this->System->Database->query('UPDATE `ExportUser` SET `Sequence`='.$Value.$Condition);
            } else
            {
              if($Selected) $this->System->Database->query('INSERT INTO `ExportUser` (`Export`, `User`, `Sequence`) VALUES ('.$_GET['ExportId'].', '.$UserId.', '.$Value.')');
            }
          }
        }

        if (array_key_exists('AllUsers', $_POST)) {
            //add allusers to export
            $this->System->Database->query('UPDATE `Export` SET `AllUsers`=1 WHERE `Id`='.$_GET['ExportId']);

            //update export stat
            $Export['AllUsers'] = 1;
            $this->SaveAllUsers();
          } else {
            //update export stat
            $Export['AllUsers'] = 0;
            $this->System->Database->query('UPDATE `Export` SET `AllUsers`=0 WHERE `Id`='.$_GET['ExportId']);
          }

        // Recalculate sequence number
        $this->System->Database->query('SET @I = 0');
        $this->System->Database->query('UPDATE `ExportUser` SET `Sequence` = (@I := @I + 1) WHERE `Export`='.$_GET['ExportId'].' ORDER BY `Sequence`;');
        $Output .= ShowMessage(T('Select saved.'));
      }
    }

    $TableColumns = array(
        array('Name' => 'Name', 'Title' => T('Name')),
        array('Name' => 'TranslatedCount', 'Title' => T('Translated count')),
        array('Name' => 'XP', 'Title' => T('Level')),
        array('Name' => 'XP', 'Title' => T('Experience')),
        array('Name' => '', 'Title' => T('Select')),
        array('Name' => 'Sequence2', 'Title' => T('Order')),
    );
    $Order = GetOrderTableHeader($TableColumns, 'TranslatedCount', 1);
    if($Order['Column'] != 'Sequence2') $InitialOrder = ', '.substr($Order['SQL'], 10);
    else $InitialOrder = '';

    $Query = 'SELECT (@I := @I + 1) AS `Sequence2`, `TT`.* FROM (SELECT `ExportUser`.`Sequence`, `T`.`ID`, `T`.`TranslatedCount`, `T`.`Name`, `T`.`XP` FROM (SELECT `User`.`ID`, `User`.`Name`, `User`.`XP`, `TranslatedCount` FROM `User`) AS T';
    $Query .=' LEFT JOIN `ExportUser` ON `ExportUser`.`Export` = '.$_GET['ExportId'].' AND `ExportUser`.`User`=`T`.`ID`';
    $Query .=' WHERE `T`.`TranslatedCount` > 0 ORDER BY COALESCE(`ExportUser`.`Sequence`, 100000000)'.$InitialOrder.') AS `TT`';

    $DbResult = $this->System->Database->query('SELECT COUNT(*) FROM ('.$Query.') AS `X`');
    $DbRow = $DbResult->fetch_row();
    $PageList = GetPageList($DbRow[0]);

    $Output .= '<form name="Translators" action="?Action=View&amp;ExportId='.$_GET['ExportId'].'" method="post">'.
        '<h3>'.T('Translators').'</h3>';
    if($Editable)
    {
      $Output .= '<input type="submit" value="'.T('Save').'" '.$DisabledInput[$Editable].'/>'.
          '<input type="hidden" name="Operation" value="Save"/><br />'.
          ' <span onclick="CheckAllCheckbox();">'.CheckBox('CheckAll', False, 'CheckAll').' '.T('Select all on page').'</span> <br />'.
          ' <span>'.CheckBox('AllUsers', $Export['AllUsers']).' '.T('Export allways from all users').'</span> '.
          '<br />'.
          T('Select users from list which you want to export from. And edit their order.').'<br />'.
          T('Order is done by numeric value which is can be edit to desirable order. Lines with same number will be renumbered in ascending order.');
    }

    $Output .= $PageList['Output'].
    '<table class="BaseTable">'.
    $Order['Output'];

    $Query = 'SELECT * FROM ('.$Query.') AS `TX` '.$Order['SQL'].$PageList['SQLLimit'];
    $this->System->Database->query('SET @I = 0');
    $DbResult = $this->System->Database->query($Query);
    while($UserLine = $DbResult->fetch_assoc())
    {
      $XP = GetLevelMinMax($UserLine['XP']);
      $Checked = $UserLine['Sequence'] != '';
      $Selection = CheckBox('sel'.$UserLine['ID'], $Checked, '', 'CheckBox', ((!$Editable) or ($Export['AllUsers'])));
      $Sequence = '<input type="text" name="seq'.$UserLine['ID'].'" style="text-align: center; width: 40px;" value="'.$UserLine['Sequence2'].'"'.$DisabledInput[$Editable].'/>';
      $Output .= '<tr>'.
          '<td><a href="'.$this->System->Link('/TranslationList.php?user='.$UserLine['ID'].'&amp;state=2&amp;group=0').'" title="Zobrazit všechny jeho přeložené texty">'.$UserLine['Name'].'</a></td>'.
          '<td>'.$UserLine['TranslatedCount'].'</td>'.
          '<td>'.$XP['Level'].'</td>'.
          '<td>'.ProgressBar(150, round($XP['XP'] / $XP['MaxXP'] * 100, 2), $XP['XP'].' / '.$XP['MaxXP']).'</td>'.
          '<td>'.$Selection.'</td><td>'.$Sequence.'</td></tr>';
    }
    $Output .= '</table>'.
        '</form>'.
        $PageList['Output'];
    return($Output);
  }

  function ExportViewGeneral()
  {
    $DisabledInput = array(false => ' disabled="disabled"', true => '');
    $DisabledTextArea = array(false => ' readonly="yes"', true => '');
    $Output = '<h3>Obecná nastavení</h3>';
    $DbRows = $this->System->Database->query('SELECT * FROM `Export` WHERE `Id`='.$_GET['ExportId']);
    $Export = $DbRows->fetch_assoc();
    if($this->System->User->Licence(LICENCE_USER) and ($this->System->User->Id == $Export['User'])) $Editable = true;
    else $Editable = false;

    if(array_key_exists('Operation', $_POST))
      if($_POST['Operation'] == 'Save')  if($Editable and array_key_exists('Title', $_POST) and array_key_exists('Description', $_POST))
      {
        if(array_key_exists('WithDiacritic', $_POST)) $WithDiacritic = 1;
        else $WithDiacritic = 0;
        if (array_key_exists('Featured', $_POST)) $Export['Featured'] = 1;
        $this->System->Database->query('UPDATE `Export` SET `Title`="'.$_POST['Title'].
          '", `Featured`='.$Export['Featured'].', `Description`="'.$_POST['Description'].
          '", `WithDiacritic`='.$WithDiacritic.' WHERE `Id`='.$Export['Id']);
        $Export['Title'] = $_POST['Title'];
        $Export['Description'] = $_POST['Description'];
        $Export['WithDiacritic'] = $WithDiacritic;
        $Output .= ShowMessage('Nastavení uloženo.');
      }

      if($Export['WithDiacritic'] == 1) $WithDiacritic = ' checked="checked"';
      else $WithDiacritic = '';
      $Output .= '<form action="?Action=View&amp;Tab=0&amp;ExportId='.$Export['Id'].'" method="post">'.
          '<table>';
      if($this->System->User->Id != null)
      {
        $Output .= '<input type="hidden" name="Operation" value="Save"/>'.
            '<tr><td colspan="2">';
        if($Editable) $Output .= ' <input type="submit" value="Uložit" '.$DisabledInput[$Editable].'/>';
        $Output .= ' <a href="?Action=Clone&amp;ExportId='.$Export['Id'].'" onclick="return confirmAction(\''.T('Realy clone item?').'\');">'.T('Clone').'</a> ';
        if($this->System->User->Licence(LICENCE_ADMIN))
          $Output .= CheckBox('Featured', $Export['Featured'], '', 'CheckBox', !$Editable). ' '.T('Recommended').' ';
        $Output .= '</td></tr>';
      }
      $Output .= '<tr><td>'.T('Identification').':</td><td><input type="text" style="width: 400px" name="Title" value="'.$Export['Title'].'"'.$DisabledInput[$Editable].'/></td></tr>'.
          '<tr><td>Popis:</td><td><textarea name="Description" cols="54" rows="10"'.$DisabledTextArea[$Editable].'>'.$Export['Description'].'</textarea></td></tr>'.
          '<tr><td>'.T('With diacritics').'</td><td><input type="checkbox" name="WithDiacritic" '.$WithDiacritic.''.$DisabledInput[$Editable].'/></td></tr>'.
          '</table></form>';
      return($Output);
  }

  function ExportViewLanguages()
  {
    global $TranslationTree;

    $Output = '';
    $DisabledInput = array(false => ' disabled="disabled"', true => '');
    $DbRows = $this->System->Database->query('SELECT * FROM `Export` WHERE `Id`='.$_GET['ExportId']);
    $Export = $DbRows->fetch_assoc();
    if($this->System->User->Licence(LICENCE_USER) and ($this->System->User->Id == $Export['User'])) $Editable = true;
    else $Editable = false;

    if(array_key_exists('Operation', $_POST))
    {
      if($_POST['Operation'] == 'Save')
      {
        //print_r($_POST);
        // Update user selection page
        foreach($_POST as $Index => $Value)
        {
          if(substr($Index, 0, 3) == 'seq')
          {
            $LanguageId = substr($Index, 3) * 1;
            if(array_key_exists('sel'.$LanguageId, $_POST)) $Selected = true;
            else $Selected = false;
            $Condition = ' WHERE Export='.$_GET['ExportId'].' AND `Language`='.$LanguageId;
            $DbResult = $this->System->Database->query('SELECT * FROM `ExportLanguage` '.$Condition);
            if($DbResult->num_rows > 0)
            {
              if(!$Selected) $this->System->Database->query('DELETE FROM `ExportLanguage` '.$Condition);
              else $this->System->Database->query('UPDATE `ExportLanguage` SET `Sequence`='.$Value.$Condition);
            } else
            {
              if($Selected) $this->System->Database->query('INSERT INTO `ExportLanguage` (`Export`, `Language`, `Sequence`) VALUES ('.$_GET['ExportId'].', '.$LanguageId.', '.$Value.')');
            }
          }
        }

        // Recalculate sequence number
        $this->System->Database->query('SET @I = 0');
        $this->System->Database->query('UPDATE `ExportLanguage` SET `Sequence` = (@I := @I + 1) WHERE `Export`='.$_GET['ExportId'].' ORDER BY `Sequence`;');
        $Output .= ShowMessage('Výběr uložen.');
      }
    }

    $Query = 'SELECT (@I := @I + 1) AS `Sequence2`, `Sequence`, `Language`.`Id`, `Name` FROM `Language`';
    $Query .=' LEFT JOIN `ExportLanguage` ON `ExportLanguage`.`Export` = '.$_GET['ExportId'].' AND `ExportLanguage`.`Language`=`Language`.`Id`';
    $Query .=' WHERE `Language`.`Enabled` = 1 ORDER BY COALESCE(`Sequence`, 100)';

    $DbResult = $this->System->Database->query('SELECT COUNT(*) FROM ('.$Query.') AS X');
    $DbRow = $DbResult->fetch_row();
    $PageList = GetPageList($DbRow[0]);

    $TableColumns = array(
        array('Name' => 'Name', 'Title' => T('Name')),
        array('Name' => '', 'Title' => T('Select')),
        array('Name' => 'Sequence2', 'Title' => T('Order')),
    );
    $Order = GetOrderTableHeader($TableColumns, 'Sequence2');
    $Output .= '<form action="?Action=View&amp;ExportId='.$_GET['ExportId'].'" method="post">'.
        '<h3>'.T('Languages').'</h3>';
    if($Editable)
    {
      $Output .= '<input type="submit" value="'.T('Save').'" '.$DisabledInput[$Editable].'/>'.
          '<input type="hidden" name="Operation" value="Save"/>'.
          '<br />'.
          T('Select languades from list witch you want to export from. And edit theirs order.').'<br />'.
          T('Order is done by numeric value which is can be edit to desirable order. Lines with same number will be renumbered in ascending order.');
    }

    $Output .= $PageList['Output'].
    '<table class="BaseTable">'.
    $Order['Output'];

    $Query = 'SELECT * FROM ('.$Query.') AS TX '.$Order['SQL'].$PageList['SQLLimit'];
    $this->System->Database->query('SET @I = 0');
    $DbResult = $this->System->Database->query($Query);
    while($Langugage = $DbResult->fetch_assoc())
    {
      $Checked = $Langugage['Sequence'] != '';
      $Selection = CheckBox('sel'.$Langugage['Id'], $Checked, '', 'CheckBox', !$Editable);
      $Sequence = '<input type="text" name="seq'.$Langugage['Id'].'" style="text-align: center; width: 40px;" value="'.$Langugage['Sequence2'].'"'.$DisabledInput[$Editable].'/>';
      $Output .= '<tr>
      <td>'.$Langugage['Name'].'</td>
      <td>'.$Selection.'</td><td>'.$Sequence.'</td></tr>';
    }
    $Output .= '</table>'.
        '</form>'.
        $PageList['Output'];
    return($Output);
  }

  function ExportViewGroups()
  {
    global $TranslationTree;

    $Output = '';
    $DisabledInput = array(false => ' disabled="disabled"', true => '');
    $DbRows = $this->System->Database->query('SELECT * FROM Export WHERE Id='.$_GET['ExportId']);
    $Export = $DbRows->fetch_assoc();
    if($this->System->User->Licence(LICENCE_USER) and ($this->System->User->Id == $Export['User'])) $Editable = true;
    else $Editable = false;

    if(array_key_exists('Operation', $_POST))
    {
      if($_POST['Operation'] == 'Save')
      {
        //print_r($_POST);
        // Update user selection page
        foreach($_POST as $Index => $Value)
        {
          if(substr($Index, 0, 3) == 'seq')
          {
            $GroupId = substr($Index, 3) * 1;
            if(array_key_exists('sel'.$GroupId, $_POST)) $Selected = true;
            else $Selected = false;
            $Condition = ' WHERE `Export`='.$_GET['ExportId'].' AND `Group`='.$GroupId;
            $DbResult = $this->System->Database->query('SELECT * FROM `ExportGroup` '.$Condition);
            if($DbResult->num_rows > 0)
            {
              if(!$Selected) $this->System->Database->query('DELETE FROM `ExportGroup` '.$Condition);
            } else
            {
              if($Selected) $this->System->Database->query('INSERT INTO `ExportGroup` (`Export`, `Group`) VALUES ('.$_GET['ExportId'].', '.$GroupId.')');
            }
          }
        }
        $Output .= ShowMessage(T('Select saved.'));
      }
      //items
      foreach($TranslationTree as $Group)
      {
      //  echo $Group['Id'].' ';
        foreach($TranslationTree[$Group['Id']]['Items'] as $Column) {
          if(array_key_exists('item'.$Column['Id'], $_POST)) $Selected = true;
          else $Selected = false;
          //we will save only forbitten collums and need to be visible
          $Selected = !$Selected;
          if (!$Column['Visible']) $Selected = false;

            $Condition = ' WHERE `Export`='.$_GET['ExportId'].' AND `GroupItem`='.$Column['Id'];
            $DbResult = $this->System->Database->query('SELECT * FROM `ExportGroupItem` '.$Condition);
            if($DbResult->num_rows > 0)
            {
              if(!$Selected) $this->System->Database->query('DELETE FROM `ExportGroupItem` '.$Condition);
            } else
            {
              if($Selected) $this->System->Database->query('INSERT INTO `ExportGroupItem` (`Export`, `GroupItem`) VALUES ('.$_GET['ExportId'].', '.$Column['Id'].')');
            }

        }
      }
    }

    $Query = 'SELECT `Group`.*, `ExportGroup`.`Id` AS `ExportGroupId` FROM `Group` LEFT JOIN `ExportGroup` ON `ExportGroup`.`Export`='.$_GET['ExportId'].' AND `Group`=`Group`.`Id`';

    $DbResult = $this->System->Database->query('SELECT COUNT(*) FROM ('.$Query.') AS X');
    $DbRow = $DbResult->fetch_row();
    $PageList = GetPageList($DbRow[0]);

    $TableColumns = array(
        array('Name' => '', 'Title' => T('Select')),
        array('Name' => 'Name', 'Title' => T('Name')),
        array('Name' => 'MangosTable', 'Title' => 'Mangos/DBC/Lua'),
    //    array('Name' => 'DBCFileName', 'Title' => 'DBC soubor'),
    //    array('Name' => 'LuaFileName', 'Title' => 'Lua soubor'),
        array('Name' => '', 'Title' => T('Items of tranlation')),
    );
    $Order = GetOrderTableHeader($TableColumns, 'Name');
    $Output .= '<form action="?Action=View&amp;ExportId='.$_GET['ExportId'].'" method="post">'.
        '<h3>Překladové skupiny</h3>';
    if($Editable)
    {
      $Output .= '<input type="submit" value="'.T('Save').'" '.$DisabledInput[$Editable].'/>'.
          '<input type="hidden" name="Operation" value="Save"/>'.
          ' <span onclick="CheckAllCheckbox();">'.CheckBox('CheckAll', False, 'CheckAll').' '.T('Select all').'</span> '.
          '<br />'.
          T('Select translation groups witch you want to export.').'<br />';
    }

    $Output .= $PageList['Output'].
    '<table class="BaseTable">'.
    $Order['Output'];

    $DbResultItem = $this->System->Database->query('SELECT * FROM `ExportGroupItem` WHERE `Export`='.$_GET['ExportId']);
    while($GroupItem = $DbResultItem->fetch_assoc())
    {
      $GroupItems[$GroupItem['GroupItem']] = 1;
    }

    $Query = 'SELECT * FROM ('.$Query.') AS TX '.$Order['SQL'].$PageList['SQLLimit'];
    $DbResult = $this->System->Database->query($Query);
    while($Group = $DbResult->fetch_assoc())
    {
      $Columns = '';
      foreach($TranslationTree[$Group['Id']]['Items'] as $Column) {
        if ($Column['Visible'])  $Columns .= CheckBox('item'.$Column['Id'], !isset($GroupItems[$Column['Id']]), '', 'CheckBox', !$Editable).' '.$Column['Name'].' <br />';
      }
      $Checked = $Group['ExportGroupId'] != '';
      $Selection = CheckBox('sel'.$Group['Id'], $Checked, '', 'CheckBox', !$Editable);
      $Output .= '<tr>'.
          '<td>'.$Selection.'<input type="hidden" name="seq'.$Group['Id'].'"/></td>'.
          '<td>'.$Group['Name'].'</td><td>';
          if ($Group['MangosTable'] <> '')
            $Output .= $Group['MangosTable'].'.sql ';
          if ($Group['LuaFileName'] <> '')
            $Output .= $Group['LuaFileName'].'.lua ';
          if ($Group['DBCFileName'] <> '')
            $Output .= $Group['DBCFileName'].'.dbc ';

      $Output .=    '</td><td>';
      $Output .=  $Columns. '</td>';
      $Output .=     '</tr>';
    }
    $Output .= '</table>'.
        '</form>'.
        $PageList['Output'];
    return($Output);
  }

  function ExportViewOutputFormat()
  {
    $Output = '';
    $DisabledInput = array(false => ' disabled="disabled"', true => '');
    if(array_key_exists('ExportId', $_GET))
    {
      $DbRows = $this->System->Database->query('SELECT * FROM `Export` WHERE `Id`='.$_GET['ExportId']);
      if($DbRows->num_rows > 0)
      {
        $Export = $DbRows->fetch_assoc();
        if($this->System->User->Licence(LICENCE_USER) and ($this->System->User->Id == $Export['User'])) $Editable = true;
        else $Editable = false;

        if(array_key_exists('Operation', $_POST))
          if($_POST['Operation'] == 'Save')
          {
            if(array_key_exists('OutputType', $_POST) and ($_POST['OutputType'] * 1 > 0))
            {
              $this->System->Database->query('UPDATE Export SET OutputType='.$_POST['OutputType'].' WHERE Id='.$_GET['ExportId']);
              $Output .= ShowMessage(T('Select saved.'));
            } else $Output .= ShowMessage(T('Format wasn\'t selected'), MESSAGE_CRITICAL);
          }

          $DbResult = $this->System->Database->query('SELECT * FROM `Export` WHERE `Id`='.$_GET['ExportId']);
          $Export = $DbResult->fetch_assoc();

          $Output .= '<h3>'.T('Format the generated output').'</h3>'.
              '<form action="?Action=View&amp;ExportId='.$_GET['ExportId'].'" method="post">';
          if($Editable)
          {
            $Output .= '<input type="submit" value="'.T('Save').'" '.$DisabledInput[$Editable].'/>'.
                '<input type="hidden" name="Operation" value="Save"/>'.
                '<br />';
          }
          $DbResult = $this->System->Database->query('SELECT * FROM `ExportOutputType` ORDER BY `Name`');
          while($ExportFormat = $DbResult->fetch_assoc())
          {
            $Output .= RadioButton('OutputType', $ExportFormat['Id'], $Export['OutputType'] == $ExportFormat['Id'], '', !$Editable).' '.$ExportFormat['Name'].'<br/>';
          }
          $Output .= '</form>';
      } else $Output .= ShowMessage(T('Item not found'), MESSAGE_CRITICAL);
    } else $Output .= ShowMessage(T('Is isn\'t select'), MESSAGE_CRITICAL);
    return($Output);
  }

  function ExportViewVersion()
  {
    $Output = '';
    $DisabledInput = array(false => ' disabled="disabled"', true => '');
    $DbRows = $this->System->Database->query('SELECT * FROM `Export` WHERE `Id`='.$_GET['ExportId']);
    $Export = $DbRows->fetch_assoc();
    if($this->System->User->Licence(LICENCE_USER) and ($this->System->User->Id == $Export['User'])) $Editable = true;
    else $Editable = false;

    if(array_key_exists('Operation', $_POST))
      if(($_POST['Operation'] == 'Save') and (array_key_exists('ClientVersion', $_POST)))
      {
        $this->System->Database->query('UPDATE `Export` SET `ClientVersion`='.$_POST['ClientVersion'].' WHERE `Id`='.$_GET['ExportId']);
        $Output .= ShowMessage(T('Select saved.'));
      }

      $DbResult = $this->System->Database->query('SELECT * FROM `Export` WHERE `Id`='.$_GET['ExportId']);
      $Export = $DbResult->fetch_assoc();

      if($Export['OutputType'] == '') $Output .= ShowMessage('Nevybrán typ exportu', MESSAGE_CRITICAL);
      else {
        $Query = 'SELECT `ClientVersion`.* FROM `ExportVersion` '.
          'LEFT JOIN `ClientVersion` ON `ClientVersion`.`Id`=`ExportVersion`.`ClientVersion` WHERE `ExportType`='.$Export['OutputType'];

        $DbResult = $this->System->Database->query('SELECT COUNT(*) FROM ('.$Query.') AS `X`');
        $DbRow = $DbResult->fetch_row();
        $PageList = GetPageList($DbRow[0]);

        $TableColumns = array(
            array('Name' => 'Version', 'Title' => T('Version')),
            array('Name' => 'BuildNumber', 'Title' => T('Build')),
            array('Name' => 'ReleaseDate', 'Title' => T('Release date')),
            array('Name' => 'Title', 'Title' => T('Name2')),
            array('Name' => '', 'Title' => T('Select')),
        );
        $Order = GetOrderTableHeader($TableColumns, 'BuildNumber', 1);
        $Output .= '<form action="?Action=View&amp;ExportId='.$_GET['ExportId'].'" method="post">'.
            '<h3>'.T('Client version').'</h3>';

        if($Editable)
        {
          $Output .= '<input type="submit" value="'.T('Save').'" '.$DisabledInput[$Editable].'/>'.
              '<input type="hidden" name="Operation" value="Save"/>'.
              '<br />'.
              T('Select version of game client witch you want to export.').'<br />';
        }
        $Output .= $PageList['Output'].
        '<table class="BaseTable">'.
        $Order['Output'];

        $Query = 'SELECT * FROM ('.$Query.') AS `TX` '.$Order['SQL'].$PageList['SQLLimit'];
        $DbResult = $this->System->Database->query($Query);
        while($Version = $DbResult->fetch_assoc())
        {
          $Output .= '<tr><td><a href="'.$this->System->Link('/client-version/?action=item&amp;id='.$Version['Id']).'">'.
              $Version['Version'].'</a></td><td>'.$Version['BuildNumber'].'</td><td>'.
              HumanDate($Version['ReleaseDate']).'</td><td>'.$Version['Title'].'</td><td>'.
              RadioButton('ClientVersion', $Version['Id'], $Export['ClientVersion'] == $Version['Id'], '', !$Editable
              ).'</td></tr>';

        }
        $Output .= '</table>'.
            '</form>'.
            $PageList['Output'];
      }
      return($Output);
  }

  function ExportViewOutput()
  {
    $Output = '';
    $DbResult = $this->System->Database->query('SELECT * FROM `Export` WHERE `Id`='.$_GET['ExportId']);
    $Export = $DbResult->fetch_assoc();
    if($Export['OutputType'] == '') $Output .= ShowMessage('Nevybrán typ exportu', MESSAGE_CRITICAL);
    else if($Export['ClientVersion'] == '') $Output .= ShowMessage(T('Export don\'t have selected version of client'), MESSAGE_CRITICAL);
    else {
      $DbResult = $this->System->Database->query('SELECT * FROM `ExportOutputType` WHERE `Id`='.$Export['OutputType']);
      if($DbResult->num_rows > 0)
      {
        $DbResult = $this->System->Database->query('SELECT * FROM `ExportVersion` WHERE (`ExportType`='.$Export['OutputType'].') AND (`ClientVersion`='.$Export['ClientVersion'].')');
        if($DbResult->num_rows > 0)
        {
          if (array_key_exists('Auto', $_GET) == false)
            $this->System->Database->query('UPDATE `Export` SET `UsedCount` = `UsedCount` + 1 WHERE `Id`='.$Export['Id']);
          $Output = ExportOutput($Export['Id'], $Export['OutputType']);
        } else $Output = ShowMessage(T('Export don\'t have selected version of client'), MESSAGE_CRITICAL);
      } else $Output = ShowMessage(T('Format output isn\'t select').'.', MESSAGE_CRITICAL);
    }
    return($Output);
  }

  function ExportViewStat($Where = '')
  {
    $Export = new Export($this->System);
    $Export->Id = $_GET['ExportId'];
    $Export->Init();
    $Export->LoadFilters();

    if(($Export->Export['ClientVersion'] == '') or ($Export->ClientVersion['BuildNumber'] == ''))
      $Output = ShowMessage(T('Export don\'t have selected version of client'), MESSAGE_CRITICAL);
    else {
      $GroupListQuery = 'SELECT `Group`.* FROM `Group` '.
          ' JOIN `ExportGroup` ON (`ExportGroup`.`Export`='.$Export->Id.') AND (`ExportGroup`.`Group`=`Group`.`Id`)';
      $Query = '';
      $UnionItems = array();
      $DbResult = $this->System->Database->query($GroupListQuery.$Where);
      while($DbRow = $DbResult->fetch_assoc())
      {
        $UnionItems[] = 'SELECT (SELECT COUNT(DISTINCT(`Entry`)) FROM ('.
            ' SELECT `T`.* FROM `'.$DbRow['TablePrefix'].'` AS `T`'.
            ' JOIN `ExportUser` ON (`ExportUser`.`User`=`T`.`User`) AND (`ExportUser`.`Export`='.$Export->Id.') '.
            ' JOIN `ExportLanguage` ON (`ExportLanguage`.`Export`='.$Export->Id.')'.
            ' WHERE (`Complete` = 1) AND (`VersionStart` <= '.$Export->ClientVersion['BuildNumber'].') AND (`VersionEnd` >= '.$Export->ClientVersion['BuildNumber'].')'.
            ') AS `C1`) AS `Translated`, '.
            '(SELECT COUNT(DISTINCT(`Entry`)) FROM ('.
            ' SELECT `T`.* FROM `'.$DbRow['TablePrefix'].'` AS `T`'.
            ' WHERE (`Language` = '.$this->System->Config['OriginalLanguage'].') AND (`VersionStart` <= '.$Export->ClientVersion['BuildNumber'].') AND (`VersionEnd` >= '.$Export->ClientVersion['BuildNumber'].')'.
            ') AS `C2`) AS `Total`, "'.$DbRow['Name'].'" AS `Name`';
      }
      $Query = substr($Query, 0, - 6);

      $DbResult = $this->System->Database->query('SELECT COUNT(*) FROM ('.$GroupListQuery.') AS `T`');
      $DbRow = $DbResult->fetch_row();
      $PageList = GetPageList($DbRow[0]);
      $Output = '<h3>'.T('Statistic of coplection selected groups').'</h3>'.
        $PageList['Output'];

      $Output .= '<table class="BaseTable">';
      $TableColumns = array(
        array('Name' => 'Name', 'Title' => T('Name')),
        array('Name' => 'Translated', 'Title' => T('Translated count')),
        array('Name' => 'Total', 'Title' => T('English')),
        array('Name' => 'Percent', 'Title' => T('Percent')),
      );

      $Order = GetOrderTableHeader($TableColumns, 'Name', 0);
      $Output .= $Order['Output'];

      $Translated = 0;
      $Total = 0;
      if(count($UnionItems) > 0)
      {
        $ID = $this->System->Database->query('SELECT *, ROUND(`Translated` / `Total` * 100, 2) AS `Percent` FROM ('.implode(' UNION ALL ', $UnionItems).') AS `C3` '.$Order['SQL'].$PageList['SQLLimit']);
        while($Group = $ID->fetch_assoc())
        {
          $Output .= '<tr><td>'.$Group['Name'].'</td><td>'.$Group['Translated'].'</td><td>'.$Group['Total'].'</td><td>'.ProgressBar(150, $Group['Percent']).'</td></tr>';
          $Translated += $Group['Translated'];
          $Total += $Group['Total'];
        }
      }
      if($Total > 0) $Percent = $Translated / $Total * 100;
      else $Percent = 100;

      $Output .= '<tr><td><strong>'.T('Altogether').'</strong></td><td><strong>'.$Translated.'</strong></td><td><strong>'.$Total.'</strong></td><td><strong>'.ProgressBar(150, round($Percent, 2)).'</strong></td></tr>';
      $Output .= '</table>';
    }
    return($Output);
  }

  function ExportView()
  {
    $Output = '';
    if(array_key_exists('ExportId', $_GET) and is_numeric($_GET['ExportId']))
    {
      $DbResult = $this->System->Database->query('SELECT * FROM `Export` WHERE `Id`='.$_GET['ExportId']);
      if($DbResult->num_rows > 0)
      {
        $Export = $DbResult->fetch_assoc();

        $DbResult = $this->System->Database->query('SELECT * FROM `User` WHERE `ID`='.$Export['User']);
        $UserLine = $DbResult->fetch_assoc();
        $Output .= 'Export <strong><a href="?Action=View&amp;Tab=6&amp;ExportId='.$Export['Id'].'">'.$_GET['ExportId'].'</a></strong> překladatele <strong>'.$UserLine['Name'].'</strong> s označením <strong>'.$Export['Title'].'</strong>';
        $Output .= ShowTabs(array(T('General'), T('Translators'), T('Translations'), T('Languages'), T('Format'), T('Version'), T('Statistic'), T('Output')));
        $Output .= '<div id="content">';
        if($_SESSION['Tab'] == TAB_GENERAL) $Output .= $this->ExportViewGeneral();
        else if($_SESSION['Tab'] == TAB_TRANSLATORS) $Output .= $this->ExportViewTranslators();
        else if($_SESSION['Tab'] == TAB_GROUPS) $Output .= $this->ExportViewGroups();
        else if($_SESSION['Tab'] == TAB_LANGUAGES) $Output .= $this->ExportViewLanguages();
        else if($_SESSION['Tab'] == TAB_OUTPUT_FORMAT) $Output .= $this->ExportViewOutputFormat();
        else if($_SESSION['Tab'] == TAB_VERSION) $Output .= $this->ExportViewVersion();
        else if($_SESSION['Tab'] == TAB_STAT) $Output .= $this->ExportViewStat();
        else if($_SESSION['Tab'] == TAB_OUTPUT) $Output .= $this->ExportViewOutput();
        else $Output .= $this->ExportViewGeneral();

        $Output .= '</div>';
      } else $Output .= ShowMessage(T('Export not found.'), MESSAGE_CRITICAL);
    } else $Output .= ShowMessage(T('Is isn\'t select'), MESSAGE_CRITICAL);
    return($Output);
  }

  function ExportClone()
  {
    if($this->System->User->Licence(LICENCE_USER))
    {
      if(array_key_exists('ExportId', $_GET) and is_numeric($_GET['ExportId']))
      {
        $DbResult = $this->System->Database->query('SELECT COUNT(*) FROM `Export` WHERE `User`='.$this->System->User->Id);
        $DbRow = $DbResult->fetch_row();
        if($DbRow[0] < $this->System->Config['MaxExportPerUser'])
        {
          $DbResult = $this->System->Database->query('SELECT * FROM `Export` WHERE `Id`='.$_GET['ExportId']);
          if($DbResult->num_rows > 0)
          {
            $DbRow = $DbResult->fetch_assoc();
            unset($DbRow['Id']);
            $DbRow['UsedCount'] = '0';
            $DbRow['User'] = $this->System->User->Id;
            $DbRow['TimeCreate'] = 'NOW()';
            $DbRow['Title'] .= ' - '.T('clone');
            $DbRow['Featured'] = 0;
            $this->System->Database->insert('Export', $DbRow);
            $ExportId = $this->System->Database->insert_id;
            $this->System->Database->query('INSERT INTO `ExportGroup` (SELECT NULL AS `Id`, '.$ExportId.' AS `Export`, `Group` FROM `ExportGroup` WHERE `Export`='.$_GET['ExportId'].')');
            $this->System->Database->query('INSERT INTO `ExportGroupItem` (SELECT NULL AS `Id`, '.$ExportId.' AS `Export`, `GroupItem` FROM `ExportGroupItem` WHERE `Export`='.$_GET['ExportId'].')');
            $this->System->Database->query('INSERT INTO `ExportLanguage` (SELECT NULL AS `Id`, '.$ExportId.' AS `Export`, `Language`, `Sequence` FROM `ExportLanguage` WHERE `Export`='.$_GET['ExportId'].')');
            $this->System->Database->query('INSERT INTO `ExportUser` (SELECT NULL AS `Id`, '.$ExportId.' AS `Export`, `User`, `Sequence` FROM `ExportUser` WHERE `Export`='.$_GET['ExportId'].')');
            $Output = ShowMessage(T('Clone export created.<br />Direct link to export').': <a href="?Action=View&amp;ExportId='.$ExportId.'">zde</a>');
            $this->System->ModuleManager->Modules['Log']->WriteLog(T('Clone export created').' <a href="'.$this->System->Link('/export/?Action=View&amp;ExportId='.$ExportId).'">'.$ExportId.'</a>.', LOG_TYPE_EXPORT);
            $_GET['Filter'] = 'my';
            $this->ExportList();
          } else $Output = ShowMessage('Zdrojový export nenalezen', MESSAGE_CRITICAL);
        } else $Output = ShowMessage(sprintf(T('You can\'t create another export. Max for one user is %d.'),
          $this->System->Config['MaxExportPerUser']), MESSAGE_CRITICAL);
      } else $Output = ShowMessage(T('Export not found.'), MESSAGE_CRITICAL);
    } else $Output = ShowMessage(T('Access denied'), MESSAGE_CRITICAL);
    return($Output);
  }

  function Show()
  {
    $this->Title = T('Export');
    if(array_key_exists('Action', $_GET))
    {
      if($_GET['Action'] == 'Create') $Output = $this->ExportCreate();
      else if($_GET['Action'] == 'CreateFinish') $Output = $this->ExportCreateFinish();
      else if($_GET['Action'] == 'View') $Output = $this->ExportView();
      else if($_GET['Action'] == 'Delete') $Output = $this->ExportDelete();
      else if($_GET['Action'] == 'Clone') $Output = $this->ExportClone();
      else $Output = $this->ExportList();
    } else $Output = $this->ExportList();
    return($Output);
  }
}
