<?php
namespace Meramo\mrm_be\Task;

use \TYPO3\CMS\Core\Utility\GeneralUtility;
use \TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction;

class PageStatusValidator extends \TYPO3\CMS\Scheduler\Task\AbstractTask {
  public function execute(){
    $connection = GeneralUtility::makeInstance(ConnectionPool::class);

    $pageQueryBuilder = $connection->getQueryBuilderForTable('pages');
    $pageQueryBuilder->getRestrictions()->removeAll()
      ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
      ->add(GeneralUtility::makeInstance(HiddenRestriction::class))
    ;

    $postStatement = $pageQueryBuilder
                  ->update('pages')
                  ->orWhere(
                    $pageQueryBuilder->expr()->eq('red_status', 11),
                    $pageQueryBuilder->expr()->eq('red_status', 12),
                  )
                  ->andWhere(
                    $pageQueryBuilder->expr()->neq('deleted', 1),
                    $pageQueryBuilder->expr()->gt('endtime', 0),
                    $pageQueryBuilder->expr()->lte('endtime', (new \DateTime())->getTimestamp()),
                  )
                  ->set('red_status', 22)
                  ->execute();


    $pageQueryBuilderOnline = $connection->getQueryBuilderForTable('pages');
    $pageQueryBuilderOnline->getRestrictions()->removeAll()
      ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
      ->add(GeneralUtility::makeInstance(HiddenRestriction::class))
    ;

    $postStatementOnline = $pageQueryBuilderOnline
                  ->update('pages')
                  ->where(
                    $pageQueryBuilderOnline->expr()->eq('red_status', 11)
                  )
                  ->andWhere(
                    $pageQueryBuilderOnline->expr()->neq('deleted', 1),
                    $pageQueryBuilderOnline->expr()->lte('starttime', (new \DateTime())->getTimestamp()),
                  )
                  ->set('red_status', 12)
                  ->execute();
                  
    return TRUE;
  }

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

}
