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

namespace Kufer\KuferTools\Basis\UseCase;

abstract class EinzelKurstagUseCase extends ToolUseCase
{
  
  protected $dbwKurseTage;

  
  private $kurstag;

  public function __construct($request, $response)
  {
    parent::__construct($request, $response);
    $this->dbwKurseTage = new \DBWorkKurseTageWT(1, true);
  }

  public function hasAccess($pToolSectionId = null)
  {
    if (!parent::hasAccess($pToolSectionId)) {
      return false;
    }

    if (!\is_numeric($this->getKurstagId())) {
      return false;
    }

    if (!\is_numeric($this->getKurstag()->id)) {
      return false;
    }

    if (!\in_array($this->getKurstag()->knr, $this->getAllowedKursnummern())) {
      return false;
    }

    if (isset($this->request->knr) && !empty($this->request->knr) && $this->getKurstag()->knr != $this->request->knr) {
      return false;
    }

    if (!\in_array($this->getKurstag()->id, $this->getAllowedKurstageIds())) {
      return false;
    }

    return true;
  }

  
  public function getKurstag()
  {
    if (\is_null($this->kurstag)) {
      $this->kurstag = $this->dbwKurseTage->getKurstag($this->getKurstagId(), true);
    }

    return $this->kurstag;
  }

  public function getKurstagId()
  {
    return $this->request->ktId;
  }

  protected function getKursHelper()
  {
    return \Kufer\KuferTools\Utils\DatamodulHelper\KursHelper\KursHelperFactory::getKursHelperByToolID($this->getToolId(), $this->toolSettings);
  }

  
  protected function getKurstagHelperZuKurs($kurs): \Kufer\KuferTools\Utils\DatamodulHelper\KursTageHelper\KurstageZuKurs
  {
    return \Kufer\KuferTools\Utils\DatamodulHelper\KursTageHelper\KurstageZuKursHelperFactory::getKursTageHelperByToolID($this->getToolId(), $this->toolSettings, $this->getKurstag()->kurs, $this->getUser());
  }

  public function getAllowedKurstageIds()
  {
    $kurstageHelper = $this->getKurstagHelperZuKurs($this->getKurstag()->kurs);

    return $kurstageHelper->getIdsOhneFilter();
  }

  public function getAllowedKursnummern()
  {
    $kurshelper = $this->getKursHelper();

    return $kurshelper->getIdsOhneFilter();
  }
}