<?php
/**
 * @copyright (c) Kufer Software GmbH, Oderstraße 7, D-84453 Mühldorf
 */

namespace Kufer\Web\KuferTools\Teilnehmer\KursUebersicht\Detailsreiter\Journal\ShowFilterJournal;

class ShowFilterJournalUseCase extends \Kufer\Web\KuferTools\Basis\UseCase\EinzelKursUseCase
{
  public function __construct($request)
  {
    parent::__construct($request, new ShowFilterJournalResponse());
  }

  public static function getToolId()
  {
    return \ToolsAPI::TOOL_TN;
  }

  public static function getToolSectionId()
  {
    return 298;
  }

  public function hasAccess($pToolSectionId = null)
  {
    if (!parent::hasAccess(335)) {
      return false;
    }
    if (!$this->isRechtAllowed('335.1.7')) {
      return false;
    }

    return true;
  }

  protected function getAllowedIds()
  {
    $user = $this->getUser();
    $belegungshelper = new \Kufer\Web\KuferTools\Utils\DatamodulHelper\Belegungen\TeilnehmerBelegungen($this->toolSettings, $user->tnr);

    return $belegungshelper->getIdsOhneFilter();
  }

  protected function getRequestedId()
  {
    return $this->request->belegId;
  }

  public function action()
  {
    return $this->getResponse();
  }

  protected function getResponse()
  {
    $this->response->knr = $this->request->knr;
    $this->response->belegId = $this->request->belegId;
    $this->response->showJournalZeitraum = $this->showZeitraumAllowed();
    $this->response->showJournalBuchungen = $this->showBuchungenAllowed();

    return $this->response;
  }

  private function showZeitraumAllowed()
  {
    $columnsToCheck = array('datumUhrzeit');

    return $this->showSettingAllowed($columnsToCheck);
  }

  private function showBuchungenAllowed()
  {
    if ($this->columnExists('zahlung', 'betrag_p') && $this->columnExists('zahlung', 'betrag_m')) {
      return true;
    }

    return false;
  }

  private function showSettingAllowed($columnsToCheck, $datamodul = 'zahlung')
  {
    foreach ($columnsToCheck as $columnToCheck) {
      if ($this->columnExists($datamodul, $columnToCheck)) {
        return true;
      }
    }

    return false;
  }

  
  private function columnExists($pDatamodulName, $pFieldName)
  {
    $columns = $this->getColumns($this->toolSettings);
    foreach ($columns as $column) {
      if ($column->datamodul === $pDatamodulName && $column->fieldname === $pFieldName) {
        return true;
      }
    }

    return false;
  }

  public static function getColumns(\ToolSettings $toolSettings, ?int $toolSectionId = null): array
  {
    static $columns = null;
    if (is_null($columns)) {
      $columns = parent::getColumns($toolSettings, $toolSectionId);
    }

    return $columns;
  }
}

class ShowFilterJournalRequest
{
  public $knr;
  public $belegId;
}

class ShowFilterJournalResponse extends \Kufer\Web\KuferTools\Basis\UseCase\ToolResponse
{
  public $knr;
  public $belegId;
  public $showJournalZeitraum;
  public $showJournalBuchungen;
}