<?php
namespace Meramo\mrm_be\UserFunc;

use \TYPO3\CMS\Core\Utility\GeneralUtility;
use \TYPO3\CMS\Core\Database\ConnectionPool;
use \TYPO3\CMS\Core\Context\Context;

class Pages
{
  function __construct(){
    $connection = GeneralUtility::makeInstance(ConnectionPool::class);
    $this->connection = $connection;
  }

  public function render_author_ro($pa, $fObj){
    $context = GeneralUtility::makeInstance(Context::class);
    $id = array_keys($_GET["edit"]["pages"])[0];
    if(!$id) return "ERR: !id";

    $queryBuilder = $this->connection->getQueryBuilderForTable('be_users');
    $queryBuilder->getRestrictions()->removeAll();
    $statement = $queryBuilder
      ->select('realName')
      ->from('be_users')
      ->innerJoin(
        'be_users',
        'pages',
        'p',
        $queryBuilder->expr()->eq('be_users.uid', $queryBuilder->quoteIdentifier('p.cruser_id'))
      )
      ->setMaxResults(1)
      ->where(
        $queryBuilder->expr()->eq('p.uid', $id)
      )
      ->execute()
    ;
    $result = $statement->fetchAll();
    if(sizeof($result) == 0) return "ERR: size==0";
    return $result[0]["realName"];
  }

  public function render_last_editor_ro($pa, $fObj){
    $context = GeneralUtility::makeInstance(Context::class);
    $id = array_keys($_GET["edit"]["pages"])[0];
    if(!$id) return "ERR: !id";

    $queryBuilder = $this->connection->getQueryBuilderForTable('be_users');
    $queryBuilder->getRestrictions()->removeAll();
    $statement = $queryBuilder
      ->select('realName')
      ->from('be_users')
      ->innerJoin(
        'be_users',
        'sys_log',
        'l',
        $queryBuilder->expr()->eq('be_users.uid', $queryBuilder->quoteIdentifier('l.userid'))
      )
      ->setMaxResults(1)
      ->where(
        $queryBuilder->expr()->eq('l.recuid', $id)
      )
      ->execute()
    ;
    $result = $statement->fetchAll();
    if(sizeof($result) == 0) return "ERR: size==0";
    return $result[0]["realName"];
  }

  private function log($msg, $isString = true){
    if(!$isString){
      $msg = json_encode($msg, JSON_PRETTY_PRINT);
    }
    file_put_contents('/var/www/html/typo3temp/debug.log', "--- UserFunc/Pages ---".PHP_EOL.$msg.PHP_EOL, FILE_APPEND);
  }
}
