<?php

class PageTranslationSave extends Page
{
  function Translate($Group, $TextID, $Complete, $Language)
  {
    $User = ModuleUser::Cast($this->System->GetModule('User'))->User;
    $Output = '';
    $Table = $Group['TablePrefix'];
    $CompleteText = array(T('unfinished'), T('finished'));

    // Get source text record from database by ID
    $DbResult = $this->Database->query('SELECT * FROM `'.$Table.'` WHERE `ID`='.$TextID);
    if ($DbResult->num_rows > 0)
    {
      $SourceText = $DbResult->fetch_assoc();

      // Get data for english original
      $DbResult = $this->Database->query('SELECT * FROM `'.$Table.'` WHERE (`Entry`='.$SourceText['Entry'].') '.
        'AND (`Language` = '.Core::Cast($this->System)->Config['OriginalLanguage'].') AND (`VersionStart` = '.$SourceText['VersionStart'].') '.
        'AND (`VersionEnd` = '.$SourceText['VersionEnd'].')');
      if ($DbResult->num_rows > 0)
      {
        $EnglishText = $DbResult->fetch_assoc();

        // Get all similar english texts
        $Filter = array();
        foreach ($Group['Items'] as $GroupItem)
        {
          if (($GroupItem['Visible'] == 1) and ($EnglishText[$GroupItem['Column']] != ''))
            $Filter[] = '(`'.$GroupItem['Column'].'` = "'.addslashes($EnglishText[$GroupItem['Column']]).'")';
        }
        if (count($Filter) > 0) $Filter = ' AND ('.implode(' OR ', $Filter).')';
          else $Filter = ' AND 0';

          $Query = 'SELECT * FROM `'.$Table.'` WHERE (`Language` = '.Core::Cast($this->System)->Config['OriginalLanguage'].')'.$Filter;
          $DbResult = $this->Database->query($Query);
          while ($EnglishFound = $DbResult->fetch_assoc())
          {
            // Get user translation paired to found english item entry
            $DbResult2 = $this->Database->query('SELECT * FROM `'.$Table.'` WHERE (`User` = '.$User->Id.
              ') AND (`Entry` = '.$EnglishFound['Entry'].') AND (`VersionStart` = '.$EnglishFound['VersionStart'].
              ') AND (`VersionEnd` = '.$EnglishFound['VersionEnd'].')');
            if ($DbResult2->num_rows > 0)
            {
              // Update existed user translation
              $ExistedText = $DbResult2->fetch_assoc();
              $Modified = false;
              $Values = '`Language` = '.$Language;
              if ($Language != $ExistedText['Language']) $Modified = true;

              $Completable = true;
              $CompleteParts = $ExistedText['CompleteParts'];
              foreach ($Group['Items'] as $GroupItem)
              {
                if ($GroupItem['Visible'] == 1)
                {
                  if ($EnglishFound[$GroupItem['Column']] == $EnglishText[$GroupItem['Column']])
                  {
                    if (array_key_exists($GroupItem['Column'], $_POST))
                    {
                      if ($_POST[$GroupItem['Column']] != $ExistedText[$GroupItem['Column']])
                        $Modified = true;

                      $Values .= ', `'.$GroupItem['Column'].'` = "'.$_POST[$GroupItem['Column']].'"';
                      $CompleteParts |= (1 << ($GroupItem['Sequence'] - 1));
                    }
                  }
                  if ((($CompleteParts & (1 << ($GroupItem['Sequence'] - 1))) == 0) and
                      ($EnglishFound[$GroupItem['Column']] != '')) $Completable = false;
                }
              }
              if ($Completable) $NewComplete = 1; // All parts of text are completed. Make entire text as completed
                else $NewComplete = 0;

              // Update completion status for edited translation item
              if ($SourceText['ID'] == $ExistedText['ID'])
              {
                $NewComplete = $Complete; // Our original user text, set complete according user choice
                if ($Complete == 1)
                {
                  foreach ($Group['Items'] as $GroupItem)
                    if ($GroupItem['Visible'] == 1) $CompleteParts |= (1 << ($GroupItem['Sequence'] - 1));
                }
              }
              $Values .= ', `Complete`='.$NewComplete.', `CompleteParts` = '.$CompleteParts;
              if (($NewComplete != $ExistedText['Complete']) or ($CompleteParts != $ExistedText['CompleteParts']))
                $Modified = true;

              $Values .= ', `ModifyTime` = NOW()';
              if ($Modified)
              {
                // Update user translation
                $this->Database->query('UPDATE `'.$Table.'` SET '.$Values.' WHERE `ID` = '.$ExistedText['ID']);

                $Output .= sprintf(T('Modifications in translation %s stored as %s'),
                  '<a href="'.$this->System->Link('/form.php?group='.
                  $Group['Id'].'&amp;ID='.$ExistedText['ID']).'">'.$ExistedText['ID'].'</a> ('.
                  $ExistedText['Entry'].')', $CompleteText[$NewComplete]).'<br/>';
                $this->System->ModuleManager->Modules['Log']->WriteLog(
                  sprintf(T('Modifications in translation %s stored as %s'),
                  '<a href="'.$this->System->Link('/form.php?group='.
                  $Group['Id'].'&amp;ID='.$ExistedText['ID']).'">'.$ExistedText['ID'].'</a> ('.
                  $ExistedText['Entry'].')', $CompleteText[$NewComplete]),
                  LOG_TYPE_TRANSLATION);
              }
            } else
            {
              // Insert new user translation
              $TakeID = $EnglishFound['ID'];
              $Columns = '`Entry`, `VersionStart`, `VersionEnd`, `Language`, `User`, `Take`, `ModifyTime`';
              $Values = $EnglishFound['Entry'].', '.$EnglishFound['VersionStart'].', '.
                  $EnglishFound['VersionEnd'].', '.$Language.', '.$User->Id.', '.$TakeID.', NOW()';

              $CompleteParts = 0;
              $Completable = true;
              foreach ($Group['Items'] as $GroupItem)
              {
                $Columns .= ', `'.$GroupItem['Column'].'`';
                if ($GroupItem['Visible'] == 1)
                {
                  if ($EnglishFound[$GroupItem['Column']] == $EnglishText[$GroupItem['Column']])
                  {
                    // Read form user data
                    if (array_key_exists($GroupItem['Column'], $_POST))
                    {
                      $Values .= ', "'.$_POST[$GroupItem['Column']].'"';
                      $CompleteParts |= (1 << ($GroupItem['Sequence'] - 1));
                    } else $Values .= ', "'.addslashes($EnglishFound[$GroupItem['Column']]).'"';
                  } else $Values .= ', "'.addslashes($EnglishFound[$GroupItem['Column']]).'"';
                  if ((($CompleteParts & (1 << ($GroupItem['Sequence'] - 1))) == 0) and ($EnglishFound[$GroupItem['Column']] != '')) $Completable = false;
                } else
                {
                  // Read from english text
                  $Values .= ', "'.$EnglishFound[$GroupItem['Column']].'"';
                }
              }
              if ($Completable) $NewComplete = 1; // All parts of text are completed. Make entire text as completed
                else $NewComplete = 0;
              // Update completion status for edited translation item
              if ($SourceText['ID'] == $EnglishFound['ID'])
              {
                $TakeID = $TextID;
                $NewComplete = $Complete; // Our original user text, set complete according user choice
                if ($Complete == 1)
                {
                  foreach ($Group['Items'] as $GroupItem)
                    if ($GroupItem['Visible'] == 1) $CompleteParts |= (1 << ($GroupItem['Sequence'] - 1));
                }
              }
              $Columns .= ', `Complete`, `CompleteParts`';
              $Values .= ', '.$NewComplete.', '.$CompleteParts;
              $this->Database->query('INSERT INTO `'.$Table.'` ('.$Columns.') VALUES ('.$Values.')');
              $LastID = $this->Database->insert_id;

              $Output .= sprintf(T('Text %s from group %s saved as %s. Handed over from %s.'),
                '<a href="'.$this->System->Link('/form.php?group='.
                $Group['Id'].'&amp;ID='.$LastID).'">'.$LastID.'</a>',
                '<a href="'.$this->System->Link('/TranslationList.php?group='.
                $Group['Id'].'&amp;user=0&amp;action=filter').'">'.$Group['Name'].'</a>',
                $CompleteText[$NewComplete], '<a href="'.$this->System->Link('/form.php?group='.$Group['Id'].'&amp;ID='.$TakeID).'">'.$TakeID.'</a>').
                '<br/>';
              $this->System->ModuleManager->Modules['Log']->WriteLog(sprintf(T('Text %s from group %s saved as %s. Handed over from %s.'),
                '<a href="'.$this->System->Link('/form.php?group='.
                $Group['Id'].'&amp;ID='.$LastID).'">'.$LastID.'</a>',
                '<a href="'.$this->System->Link('/TranslationList.php?group='.
                $Group['Id'].'&amp;user=0&amp;action=filter').'">'.$Group['Name'].'</a>',
                $CompleteText[$NewComplete], '<a href="'.$this->System->Link('/form.php?group='.$Group['Id'].'&amp;ID='.$TakeID).'">'.$TakeID.'</a>'),
                LOG_TYPE_TRANSLATION);
            }
          }
      } else $Output .= ShowMessage('Anglický originál k překladu nenalezen.', MESSAGE_CRITICAL);
    } else $Output .= ShowMessage('Zadaná položka nenalezena.', MESSAGE_CRITICAL);
    return $Output;
  }

  function Show(): string
  {
    global $Message, $MessageType;

    $User = ModuleUser::Cast($this->System->GetModule('User'))->User;
    $Output = '';
    $TranslationTree = $this->System->ModuleManager->Modules['Translation']->GetTranslationTree();

    unset($Message);
    $this->System->ModuleManager->Modules['FrontPage']->HandleLoginForm();
    if (isset($Message)) $Output .= ShowMessage($Message, $MessageType);

    $GroupId = LoadGroupIdParameter();
    $Group = $TranslationTree[$GroupId];
    $Table = $Group['TablePrefix'];
    if ($User->Licence(LICENCE_USER))
    {
      if (array_key_exists('ID', $_POST) and is_numeric($_POST['ID']))
      {
        $Entry = $_POST['entry'] * 1;
        $TextID = $_POST['ID'] * 1;
        $Language = $_POST['Language'] * 1;
        if (array_key_exists('End', $_POST)) $Complete = 1;
          else $Complete = 0;

        $Output .= $this->Translate($Group, $TextID, $Complete, $Language);

        $Output .= $this->ShowRedirection($GroupId, $Table, $TextID);

        UserLevelUpdate($User->Id);
      } else $Output .= ShowMessage('Položka nenalezena', MESSAGE_CRITICAL);
    } else
    {
      // User automatically logged out. Show login dialog and allow to save retry.
      if (array_key_exists('ID', $_POST) and array_key_exists('entry', $_POST) and array_key_exists('Language', $_POST) and array_key_exists('user', $_POST))
      {
        $Output .= 'Byli jste automaticky odhlášeni. Pro <strong>Uložení překladu</strong> se musíte přihlásit zde:<br /><br />'.
          '<form action="save.php?action=login&amp;group='.$GroupId.'" method="post"><div>'.
          '<input type="hidden" name="entry" value="'.$_POST['entry'].'" />'.
          '<input type="hidden" name="user" value="'.$_POST['user'].'" />'.
          '<input type="hidden" name="ID" value="'.$_POST['ID'].'" />'.
          '<input type="hidden" name="Language" value="'.$_POST['Language'].'" />';

        foreach ($TranslationTree[$GroupId]['Items'] as $Index => $TextItem)
        {
          if (array_key_exists($TextItem['Column'], $_POST)) $Value = $_POST[$TextItem['Column']]; else $Value = '';
          $Output .= '<input id="'.$TextItem['Column'].'" name="'.$TextItem['Column'].'" type="hidden" value="'.htmlspecialchars($Value).'" />';
        }
        $Output .= '<table>'.
          '<tr>'.
          '<td>'.T('Name').': <input type="text" name="LoginUser" size="13" /></td>'.
          '</tr><tr>'.
          '<td>'.T('Password').': <input type="password" name="LoginPass" size="13" /></td>'.
          '</tr><tr>'.
          '<th><input type="submit" value="'.T('Login and save translation').'" /></th>'.
          '</tr>'.
          '</table>';
      } else $Output = ShowMessage('Nezadány požadované údaje.', MESSAGE_CRITICAL);
    }
    return $Output;
  }

  function ShowRedirection($GroupId, $Table, $TextID)
  {
    $User = ModuleUser::Cast($this->System->GetModule('User'))->User;
    // Address and redirecting
    $Output = '<br />'.T('Translate').': <a href="'.$this->System->Link('/TranslationList.php?group='.$GroupId.'&amp;state=1&amp;user=0&entry=').'">'.T('Not translated').'</a> ';

    $prev = FollowingTran($TextID, $Table, $GroupId, True);
    $next = FollowingTran($TextID, $Table, $GroupId);
    $Output .= '<br /><br />';
    $DbResult = $this->Database->query('SELECT `Redirecting` FROM `User` WHERE `ID`='.$User->Id);
    $redirecting = $DbResult->fetch_assoc();

    switch ($redirecting['Redirecting'])
    {
      case 1:
        $Output .= '<script type="text/javascript" language="JavaScript" charset="utf-8">'.
          'setTimeout("parent.location.href=\''.htmlspecialchars_decode('TranslationList.php?group='.$GroupId.'&amp;state=1&amp;user=0').'\'", 1500)'.
          '</script>';
        break;
      case 2:
        if ($next <> '')
          $Output .= '<script type="text/javascript" language="JavaScript" charset="utf-8">'.
            'setTimeout("parent.location.href=\''.htmlspecialchars_decode($next).'\'", 1500)'.
            '</script>';
          break;
      case 3:
        if ($prev <> '')
          $Output .= '<script type="text/javascript" language="JavaScript" charset="utf-8">'.
            'setTimeout("parent.location.href=\''.htmlspecialchars_decode($prev).'\'", 1500)'.
            '</script>';
          break;
    }

    $Output .= sprintf(T('You can be redirected automatically from this page. You can set where you want to be transfered here: %s'), '<a href="'.
      $this->System->Link('/options/').'" title="'.T('User settings').'">'.T('Options').'</a>');
    return $Output;
  }
}
