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

namespace Kufer\Web\KuferTools\Basis\Anmeldung\KinderDialog;

use Kufer\Web\KuferTools\Utils\DatamodulHelper\Kurse\KursHelperFactory;

abstract class KinderDialogUseCase extends \Kufer\Web\KuferTools\Basis\UseCase\ToolUseCase
{
  public function __construct($request)
  {
    parent::__construct($request, new KinderDialogResponse());
  }

  public function hasAccess($pToolSectionId = null)
  {
    if (!parent::hasAccess($pToolSectionId)) {
      return false;
    }
    $knr = \SessionOperations::getVarValueWTIntern('anmeldung_knr', -1);
    if ($knr != -1) {
      $kurshelper = KursHelperFactory::getKursHelperByToolID(static::getToolId(), $this->toolSettings, static::getUser());
      $allowedKnrs = $kurshelper->getIdsMitFilter(static::getToolId());
      if (!in_array($knr, $allowedKnrs)) {
        return false;
      }
    }

    return true;
  }

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

  private function getKurs(): \Kurs
  {
    $knr = \SessionOperations::getVarValueWTIntern('anmeldung_knr', -1);
    $dbwKurse = new \DBWorkKurse(1, true);
    if ($knr != -1) {
      return $dbwKurse->getKurs($knr, true);
    } else {
      return $dbwKurse->getNewObject();
    }
  }

  private function getKinderfrei(): int
  {
    $kurs = $this->getKurs();
    $kinder_frei = $kurs->getKinderMax() - $kurs->getVarValue('kinderanzahl');
    if ($kinder_frei < 0) {
      $kinder_frei = 0;
    }

    return $kinder_frei;
  }

  private function isFormReadonly(): bool
  {
    return \SessionOperations::getVarValueWTIntern('AnmeldungReadonly_' . $this->getToolId()) == 1;
  }

  protected function getResponse(): KinderDialogResponse
  {
    $this->response->kinderfrei = $this->getKinderfrei();
    $this->response->readonly = $this->isFormReadonly();
    $this->response->allowKinderFunktionen = !$this->response->readonly && \System::isKuferSql5();

    return $this->response;
  }
}

class KinderDialogRequest
{
}

class KinderDialogResponse extends \Kufer\Web\KuferTools\Basis\UseCase\ToolResponse
{
  public $readonly;
  public $kinderfrei;
  public $allowKinderFunktionen;
}