<?php
/**
 * @copyright (c) Kufer Software GmbH, Loisachstrasse 4, D-84453 Mühldorf
 */

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

class ShowFilterJournalUseCase extends \Kufer\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\KuferTools\Utils\DatamodulHelper\BelegungsHelper\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();
    foreach ($columns as $column) {
      if ($column->datamodul === $pDatamodulName && $column->fieldname === $pFieldName) {
        return true;
      }
    }

    return false;
  }

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

    return $columns;
  }
}

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

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