<?php

declare(strict_types=1);

namespace WOWGmbH\Wownaechtebuch\Controller;


/**
 * This file is part of the "WOW Naechtebuch" Extension for TYPO3 CMS.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * (c) 2024 WOW-GmbH <technik@wow.gmbh>, WOW-GmbH
 */

use TYPO3\CMS\Core\Utility\DebugUtility;
use \TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Http\ForwardResponse;
use TYPO3\CMS\Extbase\Mvc\Controller\MvcPropertyMappingConfiguration;
use WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord;
use WOWGmbH\Wownaechtebuch\Event\AfterSendProtocolsEvent;

/**
 * SurveyRecordController
 */
class SurveyRecordController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController
{
    /**
     * surveyRepository
     *
     * @var \WOWGmbH\Wownaechtebuch\Domain\Repository\SurveyRepository
     */
    protected $surveyRepository;

    /**
     * questionRecordRepository
     *
     * @var \WOWGmbH\Wownaechtebuch\Domain\Repository\QuestionRecordRepository
     */
    protected $questionRecordRepository;

    /**
     * surveyRecordRepository
     *
     * @var \WOWGmbH\Wownaechtebuch\Domain\Repository\SurveyRecordRepository
     */
    protected $surveyRecordRepository;

    /**
     * treatmentRunRepository
     *
     * @var \WOWGmbH\Wownaechtebuch\Domain\Repository\TreatmentRunRepository
     */
    protected $treatmentRunRepository;

    /**
     * persistenceManager
     *
     * @var \TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager
     */
    protected $persistenceManager;
    public function __construct() {}

    /**
     * @param \TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager $persistenceManager
     */
    public function injectPersistenceManager(\TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager $persistenceManager)
    {
        $this->persistenceManager = $persistenceManager;
    }

    /**
     * @param \WOWGmbH\Wownaechtebuch\Domain\Repository\TreatmentRunRepository $treatmentRunRepository
     */
    public function injectTreatmentRunRepository(\WOWGmbH\Wownaechtebuch\Domain\Repository\TreatmentRunRepository $treatmentRunRepository)
    {
        $this->treatmentRunRepository = $treatmentRunRepository;
    }

    /**
     * @param \WOWGmbH\Wownaechtebuch\Domain\Repository\QuestionRecordRepository $questionRecordRepository
     */
    public function injectQuestionRecordRepository(\WOWGmbH\Wownaechtebuch\Domain\Repository\QuestionRecordRepository $questionRecordRepository)
    {
        $this->questionRecordRepository = $questionRecordRepository;
    }

    /**
     * @param \WOWGmbH\Wownaechtebuch\Domain\Repository\SurveyRecordRepository $surveyRecordRepository
     */
    public function injectSurveyRecordRepository(\WOWGmbH\Wownaechtebuch\Domain\Repository\SurveyRecordRepository $surveyRecordRepository)
    {
        $this->surveyRecordRepository = $surveyRecordRepository;
    }

    /**
     * @param \WOWGmbH\Wownaechtebuch\Domain\Repository\SurveyRepository $surveyRepository
     */
    public function injectSurveyRepository(\WOWGmbH\Wownaechtebuch\Domain\Repository\SurveyRepository $surveyRepository)
    {
        $this->surveyRepository = $surveyRepository;
    }

    /**
     * action index
     *
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function indexAction(): \Psr\Http\Message\ResponseInterface
    {
        return $this->htmlResponse();
    }

    /**
     * action list
     *
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function listAction(): \Psr\Http\Message\ResponseInterface
    {
        $surveyRecords = $this->surveyRecordRepository->findAll();
        $this->view->assign('pluginName', $this->request->getPluginName());
        $this->view->assign('surveyRecords', $surveyRecords);
        return $this->htmlResponse();
    }

    /**
     * action show
     *
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord $surveyRecord
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function showAction(\WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord $surveyRecord): \Psr\Http\Message\ResponseInterface
    {
        $this->view->assign('surveyRecord', $surveyRecord);
        return $this->htmlResponse();
    }

    /**
     * action new
     *
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function newAction(\WOWGmbH\Wownaechtebuch\Domain\Model\TreatmentRun $treatmentRun): \Psr\Http\Message\ResponseInterface
    {
        $surveys = $this->surveyRepository->findAll();
        $this->view->assign('surveys', $surveys);
        $this->view->assign('treatmentRun', $treatmentRun);
        return $this->htmlResponse();
    }

    /**
     * action create
     *
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord $newSurveyRecord
     */
    public function createAction(\WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord $newSurveyRecord): \Psr\Http\Message\ResponseInterface
    {
        $survey = $newSurveyRecord->getSurvey();

        $newSurveyRecord->setSurveyName($survey->getName());

        foreach ($survey->getQuestions()->toArray() as $key => $question) {
            $questionRecord = GeneralUtility::makeInstance(\WOWGmbH\Wownaechtebuch\Domain\Model\QuestionRecord::class);
            $questionRecord->setSurveyRecord($newSurveyRecord);
            $questionRecord->setAnswerType($question->getAnswerType());
            $questionRecord->setIsSensetive(true);
            $questionRecord->setQuestionText($question->getText());
            $questionRecord->setQuestionOptions($question->getOptions() ?? '');
            $newSurveyRecord->addQuestionRecord($questionRecord);
            $this->questionRecordRepository->add($questionRecord);
        }

        $this->surveyRecordRepository->add($newSurveyRecord);
        return $this->redirect('list');
    }

    /**
     * action createForCM
     *
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord $newSurveyRecord
     */
    public function createForCMAction(\WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord $newSurveyRecord): \Psr\Http\Message\ResponseInterface
    {
        $survey = $newSurveyRecord->getSurvey();

        $newSurveyRecord->setSurveyName($survey->getName());

        foreach ($survey->getQuestions()->toArray() as $key => $question) {
            $questionRecord = GeneralUtility::makeInstance(\WOWGmbH\Wownaechtebuch\Domain\Model\QuestionRecord::class);
            $questionRecord->setSurveyRecord($newSurveyRecord);
            $questionRecord->setAnswerType($question->getAnswerType());
            $questionRecord->setIsSensetive(true);
            $questionRecord->setQuestionText($question->getText());
            $questionRecord->setQuestionOptions($question->getOptions() ?? '');
            $newSurveyRecord->addQuestionRecord($questionRecord);
            $this->questionRecordRepository->add($questionRecord);
        }

        $this->surveyRecordRepository->add($newSurveyRecord);
        return $this->redirect('list');
    }

    /**
     * action fill
     *
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\Survey $survey
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\Child $child
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("surveyRecord")
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function fillAction(\WOWGmbH\Wownaechtebuch\Domain\Model\Survey $survey, \WOWGmbH\Wownaechtebuch\Domain\Model\Child $child): \Psr\Http\Message\ResponseInterface
    {
        $treatmentRun = $this->treatmentRunRepository->findLatestByChild($child);

        $newSurveyRecord = GeneralUtility::makeInstance(\WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord::class);
        $newSurveyRecord->setWeek(0);
        $newSurveyRecord->setDay(0);
        $newSurveyRecord->setState(0);
        $newSurveyRecord->setTreatmentRun($treatmentRun);
        $newSurveyRecord->setSurvey($survey);
        $newSurveyRecord->setSurveyName($survey->getName());

        if (array_key_exists('registration-survey', $this->settings) && $survey->getUid() == $this->settings['registration-survey']) {
            $child->setRegistrationSurveyRecord($newSurveyRecord);
        }

        $treatmentRun->addSurveyRecord($newSurveyRecord);

        foreach ($survey->getQuestions()->toArray() as $key => $question) {
            $questionRecord = GeneralUtility::makeInstance(\WOWGmbH\Wownaechtebuch\Domain\Model\QuestionRecord::class);
            $questionRecord->setSurveyRecord($newSurveyRecord);
            $questionRecord->setAnswerType($question->getAnswerType());
            $questionRecord->setIsSensetive(true);
            $questionRecord->setQuestionText($question->getText());
            $questionRecord->setQuestionOptions($question->getOptions() ?? '');
            $questionRecord->setQuestionPage($question->getPage() ?? 0);
            $newSurveyRecord->addQuestionRecord($questionRecord);
            $this->questionRecordRepository->add($questionRecord);
        }

        $this->surveyRecordRepository->add($newSurveyRecord);
        $this->treatmentRunRepository->update($treatmentRun);

        $this->persistenceManager->persistAll();

        return $this->redirect('edit', null, null, ['surveyRecord' => $newSurveyRecord]);
    }

    /**
     * action fillRegistrationSurvey
     *
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\Survey $survey
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\Child $child
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("surveyRecord")
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("child")
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function fillRegistrationSurveyAction(\WOWGmbH\Wownaechtebuch\Domain\Model\Survey $survey, \WOWGmbH\Wownaechtebuch\Domain\Model\Child $child): \Psr\Http\Message\ResponseInterface
    {
        $treatmentRun = $this->treatmentRunRepository->findLatestByChild($child);

        $newSurveyRecord = GeneralUtility::makeInstance(\WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord::class);
        $newSurveyRecord->setWeek(0);
        $newSurveyRecord->setDay(0);
        $newSurveyRecord->setState(0);
        $newSurveyRecord->setTreatmentRun($treatmentRun);
        $newSurveyRecord->setSurvey($survey);
        $newSurveyRecord->setSurveyName($survey->getName());

        $treatmentRun->addSurveyRecord($newSurveyRecord);

        foreach ($survey->getQuestions()->toArray() as $key => $question) {
            $questionRecord = GeneralUtility::makeInstance(\WOWGmbH\Wownaechtebuch\Domain\Model\QuestionRecord::class);
            $questionRecord->setSurveyRecord($newSurveyRecord);
            $questionRecord->setAnswerType($question->getAnswerType());
            $questionRecord->setIsSensetive(true);
            $questionRecord->setQuestionText($question->getText());
            $questionRecord->setQuestionOptions($question->getOptions() ?? '');
            $questionRecord->setQuestionPage($question->getPage() ?? 0);
            $newSurveyRecord->addQuestionRecord($questionRecord);
            $this->questionRecordRepository->add($questionRecord);
        }

        $this->surveyRecordRepository->add($newSurveyRecord);
        $this->treatmentRunRepository->update($treatmentRun);

        $this->persistenceManager->persistAll();

        return $this->redirect('editRegistrationSurvey', null, null, ['surveyRecord' => $newSurveyRecord]);
    }

    /**
     * action fillRegistrationSurvey
     *
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\Survey $survey
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\Child $child
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("surveyRecord")
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("child")
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function fillRegistrationSurveyForCMAction(\WOWGmbH\Wownaechtebuch\Domain\Model\Survey $survey, \WOWGmbH\Wownaechtebuch\Domain\Model\Child $child): \Psr\Http\Message\ResponseInterface
    {
        $treatmentRun = $this->treatmentRunRepository->findLatestByChild($child);

        $newSurveyRecord = GeneralUtility::makeInstance(\WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord::class);
        $newSurveyRecord->setWeek(0);
        $newSurveyRecord->setDay(0);
        $newSurveyRecord->setState(0);
        $newSurveyRecord->setTreatmentRun($treatmentRun);
        $newSurveyRecord->setSurvey($survey);
        $newSurveyRecord->setSurveyName($survey->getName());

        $treatmentRun->addSurveyRecord($newSurveyRecord);

        foreach ($survey->getQuestions()->toArray() as $key => $question) {
            $questionRecord = GeneralUtility::makeInstance(\WOWGmbH\Wownaechtebuch\Domain\Model\QuestionRecord::class);
            $questionRecord->setSurveyRecord($newSurveyRecord);
            $questionRecord->setAnswerType($question->getAnswerType());
            $questionRecord->setIsSensetive(true);
            $questionRecord->setQuestionText($question->getText());
            $questionRecord->setQuestionOptions($question->getOptions() ?? '');
            $questionRecord->setQuestionPage($question->getPage() ?? 0);
            $newSurveyRecord->addQuestionRecord($questionRecord);
            $this->questionRecordRepository->add($questionRecord);
        }

        $this->surveyRecordRepository->add($newSurveyRecord);
        $this->treatmentRunRepository->update($treatmentRun);

        $this->persistenceManager->persistAll();

        return $this->redirect('editRegistrationSurveyForCM', null, null, ['surveyRecord' => $newSurveyRecord]);
    }

    /**
     * action fillForCM
     *
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\Survey $survey
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\Child $child
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("surveyRecord")
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function fillForCMAction(\WOWGmbH\Wownaechtebuch\Domain\Model\Survey $survey, \WOWGmbH\Wownaechtebuch\Domain\Model\Child $child): \Psr\Http\Message\ResponseInterface
    {
        $treatmentRun = $this->treatmentRunRepository->findLatestByChild($child);

        $newSurveyRecord = GeneralUtility::makeInstance(\WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord::class);
        $newSurveyRecord->setWeek(0);
        $newSurveyRecord->setDay(0);
        $newSurveyRecord->setState(0);
        $newSurveyRecord->setTreatmentRun($treatmentRun);
        $newSurveyRecord->setSurvey($survey);
        $newSurveyRecord->setSurveyName($survey->getName());

        if (array_key_exists('registration-survey', $this->settings) && $survey->getUid() == $this->settings['registration-survey']) {
            $child->setRegistrationSurveyRecord($newSurveyRecord);
        }

        $treatmentRun->addSurveyRecord($newSurveyRecord);

        foreach ($survey->getQuestions()->toArray() as $key => $question) {
            $questionRecord = GeneralUtility::makeInstance(\WOWGmbH\Wownaechtebuch\Domain\Model\QuestionRecord::class);
            $questionRecord->setSurveyRecord($newSurveyRecord);
            $questionRecord->setAnswerType($question->getAnswerType());
            $questionRecord->setIsSensetive(true);
            $questionRecord->setQuestionText($question->getText());
            $questionRecord->setQuestionOptions($question->getOptions() ?? '');
            $questionRecord->setQuestionPage($question->getPage() ?? 0);
            $newSurveyRecord->addQuestionRecord($questionRecord);
            $this->questionRecordRepository->add($questionRecord);
        }

        $this->surveyRecordRepository->add($newSurveyRecord);
        $this->treatmentRunRepository->update($treatmentRun);

        $this->persistenceManager->persistAll();

        return $this->redirect('editForCM', null, null, ['surveyRecord' => $newSurveyRecord]);
    }

    /**
     * action edit
     *
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord $surveyRecord
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("surveyRecord")
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function editAction(\WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord $surveyRecord): \Psr\Http\Message\ResponseInterface
    {

        $pages = [];
        $i = 0;
        foreach ($surveyRecord->getQuestionRecords() as $questionRecord) {
            $pages[$questionRecord->getQuestionPage()][] = ['qr' => $questionRecord, 'i' => $i];
            $i++;
        }

        ksort($pages);

        $this->view->assign('pluginName', $this->request->getPluginName());
        $this->view->assign('pages', $pages);
        $this->view->assign('surveyRecord', $surveyRecord);
        return $this->htmlResponse();
    }

    /**
     * action editRegistrationSurvey
     *
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord $surveyRecord
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("surveyRecord")
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function editRegistrationSurveyAction(\WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord $surveyRecord): \Psr\Http\Message\ResponseInterface
    {

        $pages = [];
        $i = 0;
        foreach ($surveyRecord->getQuestionRecords() as $questionRecord) {
            $pages[$questionRecord->getQuestionPage()][] = ['qr' => $questionRecord, 'i' => $i];
            $i++;
        }

        ksort($pages);

        $this->view->assign('pluginName', $this->request->getPluginName());
        $this->view->assign('pages', $pages);
        $this->view->assign('surveyRecord', $surveyRecord);
        return $this->htmlResponse();
    }

    /**
     * action editRegistrationSurveyForCM
     *
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord $surveyRecord
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("surveyRecord")
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function editRegistrationSurveyForCMAction(\WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord $surveyRecord): \Psr\Http\Message\ResponseInterface
    {

        $pages = [];
        $i = 0;
        foreach ($surveyRecord->getQuestionRecords() as $questionRecord) {
            $pages[$questionRecord->getQuestionPage()][] = ['qr' => $questionRecord, 'i' => $i];
            $i++;
        }

        ksort($pages);

        $this->view->assign('pluginName', $this->request->getPluginName());
        $this->view->assign('pages', $pages);
        $this->view->assign('surveyRecord', $surveyRecord);
        return $this->htmlResponse();
    }

    /**
     * action editForCM
     *
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord $surveyRecord
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("surveyRecord")
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function editForCMAction(\WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord $surveyRecord): \Psr\Http\Message\ResponseInterface
    {

        $pages = [];
        $i = 0;
        foreach ($surveyRecord->getQuestionRecords() as $questionRecord) {
            $pages[$questionRecord->getQuestionPage()][] = ['qr' => $questionRecord, 'i' => $i];
            $i++;
        }

        ksort($pages);

        $this->view->assign('pluginName', $this->request->getPluginName());
        $this->view->assign('pages', $pages);
        $this->view->assign('surveyRecord', $surveyRecord);
        return $this->htmlResponse();
    }

    /**
     * action editProtocol
     *
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\Child $child
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("child")
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function editProtocolAction(\WOWGmbH\Wownaechtebuch\Domain\Model\Child $child, int $week = null): \Psr\Http\Message\ResponseInterface
    {
        $latestTreatmentRun = $this->treatmentRunRepository->findLatestByChild($child);
        $week = $week == null ? $this->surveyRecordRepository->getLatestWeek($latestTreatmentRun) + 1 : $week;
        $surveyRecords = $this->surveyRecordRepository->findBy(['week' => $week, 'treatmentRun.child' => $child])->toArray();

        // create Records until there is atleast one per day in the week
        $count = count($surveyRecords);
        for ($i = $count; $i < 7; $i++) {
            $surveyRecords[] = $this->createProtocol($latestTreatmentRun, $week, $i + 1);
        }
        $this->persistenceManager->persistAll();

        usort($surveyRecords,  fn($a, $b) => $a->getDay() - $b->getDay());

        $this->view->assign('wasSent', $surveyRecords[0]->getState() == SurveyRecord::STATE_SENT);
        $this->view->assign('surveyRecords', $surveyRecords);
        $this->view->assign('treatmentRun', $latestTreatmentRun);
        $this->view->assign('week', $week);
        return $this->htmlResponse();
    }

    /**
     * action editProtocolForCM
     *
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\Child $child
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("child")
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function editProtocolForCMAction(\WOWGmbH\Wownaechtebuch\Domain\Model\Child $child, int $week = null): \Psr\Http\Message\ResponseInterface
    {
        $latestTreatmentRun = $this->treatmentRunRepository->findLatestByChild($child);
        $week = $week == null ? $this->surveyRecordRepository->getLatestWeek($latestTreatmentRun) + 1 : $week;
        $surveyRecords = $this->surveyRecordRepository->findBy(['week' => $week, 'treatmentRun.child' => $child])->toArray();

        // create Records until there is atleast one per day in the week
        $count = count($surveyRecords);
        for ($i = $count; $i < 7; $i++) {
            $surveyRecords[] = $this->createProtocol($latestTreatmentRun, $week, $i + 1);
        }
        $this->persistenceManager->persistAll();

        usort($surveyRecords,  fn($a, $b) => $a->getDay() - $b->getDay());

        $this->view->assign('wasSent', $surveyRecords[0]->getState() == SurveyRecord::STATE_SENT);
        $this->view->assign('surveyRecords', $surveyRecords);
        $this->view->assign('treatmentRun', $latestTreatmentRun);
        $this->view->assign('week', $week);
        return $this->htmlResponse();
    }

    /**
     * action listProtocol
     *
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\Child $child
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("child")
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function listProtocolAction(\WOWGmbH\Wownaechtebuch\Domain\Model\Child $child): \Psr\Http\Message\ResponseInterface
    {
        $latestTreatmentRun = $this->treatmentRunRepository->findLatestByChild($child);
        $surveyRecords = $this->surveyRecordRepository->findBy(['treatmentRun' => $latestTreatmentRun, 'surveyName' => 'Protokoll']);

        $this->view->assign('surveyRecords', $surveyRecords);
        $this->view->assign('treatmentRun', $latestTreatmentRun);
        return $this->htmlResponse();
    }

    /**
     * action listProtocolForCM
     *
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\Child $child
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("child")
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function listProtocolForCMAction(\WOWGmbH\Wownaechtebuch\Domain\Model\Child $child): \Psr\Http\Message\ResponseInterface
    {
        $latestTreatmentRun = $this->treatmentRunRepository->findLatestByChild($child);
        $surveyRecords = $this->surveyRecordRepository->findBy(['treatmentRun' => $latestTreatmentRun, 'surveyName' => 'Protokoll']);

        $this->view->assign('surveyRecords', $surveyRecords);
        $this->view->assign('treatmentRun', $latestTreatmentRun);
        return $this->htmlResponse();
    }

    /**
     * action listForAdminByChild
     *
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\Child $child
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("child")
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function listForAdminByChildAction(\WOWGmbH\Wownaechtebuch\Domain\Model\Child $child): \Psr\Http\Message\ResponseInterface
    {
        $latestTreatmentRun = $this->treatmentRunRepository->findLatestByChild($child);
        $surveyRecords = $this->surveyRecordRepository->findBy(['treatmentRun' => $latestTreatmentRun, 'surveyName' => 'Protokoll', 'state' => SurveyRecord::STATE_SENT]);

        $this->view->assign('surveyRecords', $surveyRecords);
        $this->view->assign('treatmentRun', $latestTreatmentRun);
        return $this->htmlResponse();
    }

    /**
     * action listForCMByChild
     *
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\Child $child
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("child")
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function listForCMByChildAction(\WOWGmbH\Wownaechtebuch\Domain\Model\Child $child): \Psr\Http\Message\ResponseInterface
    {
        $latestTreatmentRun = $this->treatmentRunRepository->findLatestByChild($child);
        $surveyRecords = $this->surveyRecordRepository->findBy(['treatmentRun' => $latestTreatmentRun, 'surveyName' => 'Protokoll', 'state' => SurveyRecord::STATE_SENT]);

        $this->view->assign('surveyRecords', $surveyRecords);
        $this->view->assign('treatmentRun', $latestTreatmentRun);
        return $this->htmlResponse();
    }

    public function initializeSaveProtocolsAction()
    {
        // Not nedded because saved a String :/
        // if ($this->arguments->hasArgument('protocolData')) {
        //     $this->arguments['protocolData']->getPropertyMappingConfiguration()->getConfigurationFor('surveyRecords')->getConfigurationFor('start')->setTypeConverterOption(
        //     'TYPO3\\CMS\\Extbase\\Property\\TypeConverter\\DateTimeConverter', 
        //     \TYPO3\CMS\Extbase\Property\TypeConverter\DateTimeConverter::CONFIGURATION_DATE_FORMAT, 
        //     'd-m-Y'
        //     );
        // }
    }

    /**
     * action saveProtocols
     *
     * @param \WOWGmbH\Wownaechtebuch\DTO\ProtocolData $protocolData
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("protocolData")
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function saveProtocolsAction(\WOWGmbH\Wownaechtebuch\DTO\ProtocolData $protocolData): \Psr\Http\Message\ResponseInterface
    {
        foreach ($protocolData->getSurveyRecords()->toArray() as $key => $surveyRecord) {
            if ($surveyRecord->getState() !=  SurveyRecord::STATE_OPEN) continue;
            $surveyRecord->setState($protocolData->getState() ?? 0);
            $this->surveyRecordRepository->update($surveyRecord);
        }

        $child = $protocolData->getSurveyRecords()->toArray()[0]->getTreatmentRun()->getChild();
        $week = $protocolData->getSurveyRecords()->toArray()[0]->getWeek();
        if ($protocolData->getSave()) {
            return $this->redirect('sendProtocols', null, null, ['child' => $child, 'week' => ($week)]);
        }
        return $this->redirect('editProtocol', null, null, ['child' => $child, 'week' => ($week + 1)]);
        // return $this->redirect('editProtocol', null, null, ['child' => $child, 'week' => ($week)]);
    }
     
    
    /**
     * action saveProtocolsKeepWeek
     *
     * @param \WOWGmbH\Wownaechtebuch\DTO\ProtocolData $protocolData
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("protocolData")
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function saveProtocolsKeepWeekAction(\WOWGmbH\Wownaechtebuch\DTO\ProtocolData $protocolData): \Psr\Http\Message\ResponseInterface
    {
        foreach ($protocolData->getSurveyRecords()->toArray() as $key => $surveyRecord) {
            if ($surveyRecord->getState() !=  SurveyRecord::STATE_OPEN) continue;
            $surveyRecord->setState($protocolData->getState() ?? 0);
            $this->surveyRecordRepository->update($surveyRecord);
        }

        $child = $protocolData->getSurveyRecords()->toArray()[0]->getTreatmentRun()->getChild();
        $week = $protocolData->getSurveyRecords()->toArray()[0]->getWeek();
        if ($protocolData->getSave()) {
            return $this->redirect('sendProtocols', null, null, ['child' => $child, 'week' => ($week)]);
        }
        // return $this->redirect('editProtocol', null, null, ['child' => $child, 'week' => ($week + 1)]);
        return $this->redirect('editProtocol', null, null, ['child' => $child, 'week' => ($week)]);
    }


    ////// Altes saveProtocolsForCM
    // /**
    //  * action saveProtocolsForCM
    //  *
    //  * @param \WOWGmbH\Wownaechtebuch\DTO\ProtocolData $protocolData
    //  * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("protocolData")
    //  * @return \Psr\Http\Message\ResponseInterface
    //  */
    // public function saveProtocolsForCMAction(\WOWGmbH\Wownaechtebuch\DTO\ProtocolData $protocolData): \Psr\Http\Message\ResponseInterface
    // {
    //     foreach ($protocolData->getSurveyRecords()->toArray() as $key => $surveyRecord) {
    //         if ($surveyRecord->getState() !=  SurveyRecord::STATE_OPEN) continue;
    //         $surveyRecord->setState($protocolData->getState() ?? 0);
    //         $this->surveyRecordRepository->update($surveyRecord);
    //     }

    //     $child = $protocolData->getSurveyRecords()->toArray()[0]->getTreatmentRun()->getChild();
    //     $week = $protocolData->getSurveyRecords()->toArray()[0]->getWeek();
    //     return $this->redirect('editProtocolForCM', null, null, ['child' => $child, 'week' => $week]);
    // }

    ///// neues saveProtocolsForCM
    /**
     * action saveProtocolsForCM
     *
     * @param \WOWGmbH\Wownaechtebuch\DTO\ProtocolData $protocolData
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("protocolData")
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function saveProtocolsForCMAction(
        \WOWGmbH\Wownaechtebuch\DTO\ProtocolData $protocolData = null
    ): \Psr\Http\Message\ResponseInterface {
        $cmd = $this->request->getArgument('cmd') ?? '';
    
        if ($cmd === 'createAndSaveProtocolForCM') {
            return $this->createAndSaveProtocolForCMAction($protocolData);
        }
    
        // sonst normal speichern:
        foreach ($protocolData->getSurveyRecords()->toArray() as $key => $surveyRecord) {
            if ($surveyRecord->getState() !=  SurveyRecord::STATE_OPEN) continue;
            $surveyRecord->setState($protocolData->getState() ?? 0);
            $this->surveyRecordRepository->update($surveyRecord);
        }
    
        $child = $protocolData->getSurveyRecords()->toArray()[0]->getTreatmentRun()->getChild();
        $week = $protocolData->getSurveyRecords()->toArray()[0]->getWeek();
        return $this->redirect('editProtocolForCM', null, null, ['child'=> $child, 'week'=> $week]);
        // return $this->redirect('editProtocolForCM');
    }
    

    /**
     * action createProtocol
     *
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\Child $child
     * @param int $week
     * @param int $day
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("child")
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function createProtocolAction(\WOWGmbH\Wownaechtebuch\Domain\Model\Child $child, int $week, int $day): \Psr\Http\Message\ResponseInterface
    {
        $latestTreatmentRun = $this->treatmentRunRepository->findLatestByChild($child);

        // create Records until there is atleast one per day in the week
        $surveyRecord = $this->createProtocol($latestTreatmentRun, $week, $day);
        $this->persistenceManager->persistAll();

        return $this->redirect('editProtocol', null, null, ['child' => $child, 'week' => $week]);
    }

    /**
     * action saveProtocolsForCMTest
     *
     * @param \WOWGmbH\Wownaechtebuch\DTO\ProtocolData $protocolData
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("protocolData")
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function saveProtocolsForCMTestAction(\WOWGmbH\Wownaechtebuch\DTO\ProtocolData $protocolData): \Psr\Http\Message\ResponseInterface
    {
        foreach ($protocolData->getSurveyRecords()->toArray() as $key => $surveyRecord) {
            if ($surveyRecord->getState() !=  SurveyRecord::STATE_OPEN) continue;
            $surveyRecord->setState($protocolData->getState() ?? 0);
            $this->surveyRecordRepository->update($surveyRecord);
        }

        $child = $protocolData->getSurveyRecords()->toArray()[0]->getTreatmentRun()->getChild();
        $week = $protocolData->getSurveyRecords()->toArray()[0]->getWeek();
        return $this->redirect('editProtocolForCM', null, null, ['child' => $child, 'week' => $week]);
    }

    /**
     * action addProtocol
     *
     * @param \WOWGmbH\Wownaechtebuch\DTO\ProtocolData $protocolData
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\Child $child
     * @param int $week
     * @param int $day
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("protocolData")
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("child")
     * @return \Psr\Http\Message\ResponseInterface
     * @param \WOWGmbH\Wownaechtebuch\DTO\ProtocolData $protocolData
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("protocolData")
     * @return \Psr\Http\Message\ResponseInterface
     */


    //  public function addProtocolAction(\WOWGmbH\Wownaechtebuch\Domain\Model\Child $child, int $week, int $day): \Psr\Http\Message\ResponseInterface
    public function addProtocolAction(\WOWGmbH\Wownaechtebuch\DTO\ProtocolData $protocolData): \Psr\Http\Message\ResponseInterface
    {

        saveProtocolsForCMAction($protocolData);
        // Speichern der ProtocolData
        // foreach ($protocolData->getSurveyRecords()->toArray() as $surveyRecord) {
        //     if ($surveyRecord->getState() != \WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord::STATE_OPEN) continue;
        //     $surveyRecord->setState($protocolData->getState() ?? 0);
        //     $this->surveyRecordRepository->update($surveyRecord);
        // }

        // $this->persistenceManager->persistAll();

        // Neuen Eintrag erstellen
        // $latestTreatmentRun = $this->treatmentRunRepository->findLatestByChild($child);
        // $this->createProtocol($latestTreatmentRun, $week, $day);
        // $this->persistenceManager->persistAll();

        // return $this->redirect('editProtocol', null, null, ['child' => $child, 'week' => $week]);
    }

    // /**
    //  * action createProtocolForCM
    //  *
    //  * @param \WOWGmbH\Wownaechtebuch\Domain\Model\Child $child
    //  * @param int $week
    //  * @param int $day
    //  * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("child")
    //  * @return \Psr\Http\Message\ResponseInterface
    //  */
    // public function createProtocolForCMAction(\WOWGmbH\Wownaechtebuch\Domain\Model\Child $child, int $week, int $day): \Psr\Http\Message\ResponseInterface
    // {
    //     $latestTreatmentRun = $this->treatmentRunRepository->findLatestByChild($child);

    //     // create Records until there is atleast one per day in the week
    //     $surveyRecord = $this->createProtocol($latestTreatmentRun, $week, $day);
    //     $this->persistenceManager->persistAll();

    //     return $this->redirect('editProtocolForCM', null, null, ['child' => $child, 'week' => $week]);
    // }

    /**
 * action createProtocolForCM (AJAX)
 *
 * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("child")
 */
public function createProtocolForCMAction(\WOWGmbH\Wownaechtebuch\Domain\Model\Child $child, int $week, int $day): \Psr\Http\Message\ResponseInterface
{
    $latestTreatmentRun = $this->treatmentRunRepository->findLatestByChild($child);

    // neues Protokoll anlegen
    $surveyRecord = $this->createProtocol($latestTreatmentRun, $week, $day);
    $this->persistenceManager->persistAll();

    // für Partial rendern vorbereiten
    $this->view->assignMultiple([
        'surveyRecord' => $surveyRecord,
        'week' => $week,
    ]);
    return $this->htmlResponse('<!-- Aktion erfolgreich im Hintergrund ausgeführt -->');
    // return $this->htmlResponse(); // gibt reines HTML zurück
}


    /**
     * action createAndSaveProtocolForCM
     *
     * @param \WOWGmbH\Wownaechtebuch\DTO\ProtocolData|null $protocolData
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\Child|null $child
     * @param int|null $week
     * @param int|null $day
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("protocolData")
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("child")
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function createAndSaveProtocolForCMAction(
        \WOWGmbH\Wownaechtebuch\DTO\ProtocolData $protocolData = null,
        \WOWGmbH\Wownaechtebuch\Domain\Model\Child $child = null,
        int $week = null,
        int $day = null
    ): \Psr\Http\Message\ResponseInterface {



        // $this->persistenceManager->persistAll();

        // 1. Bestehende Eingaben speichern
        if ($protocolData !== null) {
            foreach ($protocolData->getSurveyRecords()->toArray() as $surveyRecord) {
                if ($surveyRecord->getState() != SurveyRecord::STATE_OPEN) {
                    continue;
                }
                $surveyRecord->setState($protocolData->getState() ?? 0);
                $this->surveyRecordRepository->update($surveyRecord);
            }
            // if ($child !== null && $week !== null && $day !== null) {
                // $latestTreatmentRun = $this->treatmentRunRepository->findLatestByChild($child);
                // $this->createProtocol($latestTreatmentRun, $week, $day);
            // }
        }
        $child = $protocolData->getSurveyRecords()->toArray()[0]->getTreatmentRun()->getChild();
        $week = $protocolData->getSurveyRecords()->toArray()[0]->getWeek();
        $day = $protocolData->getSurveyRecords()->toArray()[0]->getDay();
        $latestTreatmentRun = $this->treatmentRunRepository->findLatestByChild($child);
        $surveyRecord = $this->createProtocol($latestTreatmentRun, $week, $day);

        // // 2. Neues Protokoll anlegen
        // if ($child !== null && $week !== null && $day !== null) {
        //     $latestTreatmentRun = $this->treatmentRunRepository->findLatestByChild($child);
        //     $this->createProtocol($latestTreatmentRun, $week, $day);
        // }

        // 3. Persistieren
        $this->persistenceManager->persistAll();

        // 4. Redirect
        $child = $protocolData->getSurveyRecords()->toArray()[0]->getTreatmentRun()->getChild();
        $week = $protocolData->getSurveyRecords()->toArray()[0]->getWeek();
        return $this->redirect('editProtocolForCM', null, null, ['child'=> $child, 'week'=> $week]);
        // return $this->redirect('editProtocolForCM');
        // return $this->redirect('editProtocolForCM', null, null, [
        //     'child' => $child,
        //     'week' => $week
        // ]);
    }


    public function listByChildAction(\WOWGmbH\Wownaechtebuch\Domain\Model\Child $child): \Psr\Http\Message\ResponseInterface
    {
        $latestTreatmentRun = $this->treatmentRunRepository->findLatestByChild($child);
        $surveyRecords = $this->surveyRecordRepository->findBy(['treatmentRun' => $latestTreatmentRun]);

        $this->view->assign('surveyRecords', $surveyRecords);
        $this->view->assign('treatmentRun', $latestTreatmentRun);
        return $this->htmlResponse();
    }

    /**
     * action editNextProtocol
     *
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\Child $child
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("child")
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function editNextProtocolAction(\WOWGmbH\Wownaechtebuch\Domain\Model\Child $child, int $week): \Psr\Http\Message\ResponseInterface
    {
        return $this->redirect('editProtocol', null, null, ['child' => $child, 'week' => ($week + 1)]);
    }

    /**
     * action editNextProtocolForCM
     *
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\Child $child
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("child")
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function editNextProtocolForCMAction(\WOWGmbH\Wownaechtebuch\Domain\Model\Child $child, int $week): \Psr\Http\Message\ResponseInterface
    {
        return $this->redirect('editProtocolForCM', null, null, ['child' => $child, 'week' => ($week + 1)]);
    }

    /**
     * action editPrevProtocol
     *
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\Child $child
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("child")
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function editPrevProtocolAction(\WOWGmbH\Wownaechtebuch\Domain\Model\Child $child, int $week): \Psr\Http\Message\ResponseInterface
    {
        return $this->redirect('editProtocol', null, null, ['child' => $child, 'week' => ($week - 1)]);
    }

    /**
     * action editPrevProtocolForCM
     *
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\Child $child
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("child")
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function editPrevProtocolForCMAction(\WOWGmbH\Wownaechtebuch\Domain\Model\Child $child, int $week): \Psr\Http\Message\ResponseInterface
    {
        return $this->redirect('editProtocolForCM', null, null, ['child' => $child, 'week' => ($week - 1)]);
    }

    /**
     * action sendProtocols
     *
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\Child $child
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("child")
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function sendProtocolsAction(\WOWGmbH\Wownaechtebuch\Domain\Model\Child $child, int $week): \Psr\Http\Message\ResponseInterface
    {
        $latestTreatmentRun = $this->treatmentRunRepository->findLatestByChild($child);
        $surveyRecords = $this->surveyRecordRepository->findBy(['treatmentRun' => $latestTreatmentRun, 'surveyName' => 'Protokoll']);

        foreach ($surveyRecords as $protocol) {
            if ($protocol->getWeek() > $week || $protocol->getState() != SurveyRecord::STATE_OPEN) continue;
            $protocol->setState(SurveyRecord::STATE_SENT);
            $this->surveyRecordRepository->update($protocol);
        }

        /** @var AfterSendProtocolsEvent $event */
        $event = $this->eventDispatcher->dispatch(
            new AfterSendProtocolsEvent($child, $week),
        );

        return $this->redirect('editProtocol', null, null, ['child' => $child, 'week' => ($week + 1)]);
    }

    /**
     * action sendProtocolsForCM
     *
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\Child $child
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("child")
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function sendProtocolsForCMAction(\WOWGmbH\Wownaechtebuch\Domain\Model\Child $child, int $week): \Psr\Http\Message\ResponseInterface
    {
        $latestTreatmentRun = $this->treatmentRunRepository->findLatestByChild($child);
        $surveyRecords = $this->surveyRecordRepository->findBy(['treatmentRun' => $latestTreatmentRun, 'surveyName' => 'Protokoll']);

        foreach ($surveyRecords as $protocol) {
            if ($protocol->getWeek() > $week || $protocol->getState() != SurveyRecord::STATE_OPEN) continue;
            $protocol->setState(SurveyRecord::STATE_SENT);
            $this->surveyRecordRepository->update($protocol);
        }

        return $this->redirect('editProtocolForCM', null, null, ['child' => $child, 'week' => ($week + 1)]);
    }

    /**
     * action editNext
     *
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord $surveyRecord
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("surveyRecord")
     * @return \Psr\Http\Message\ResponseInterface
     */
    // public function editNextAction(\WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord $surveyRecord, int $page): \Psr\Http\Message\ResponseInterface
    // {
    //     // $this->surveyRecordRepository->update($surveyRecord);
    //     foreach ($surveyRecord->getQuestionRecords() as $questionRecord) {
    //         $this->questionRecordRepository->update($questionRecord);   
    //     }
    //     return $this->redirect('edit', null, null, ['surveyRecord'=> $surveyRecord, 'page'=> ($page + 1)]);
    // }

    /**
     * action update
     *
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord $surveyRecord
     */
    public function updateAction(\WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord $surveyRecord): \Psr\Http\Message\ResponseInterface
    {
        $this->surveyRecordRepository->update($surveyRecord);
        return $this->redirect('listForSurvey', "Child", null,  ['child' => $surveyRecord->getTreatmentRun()->getChild()]);
    }

    /**
     * action updateRegistrationSurvey
     *
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("surveyRecord")
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord $surveyRecord
     */
    public function updateRegistrationSurveyAction(\WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord $surveyRecord): \Psr\Http\Message\ResponseInterface
    {
        $this->surveyRecordRepository->update($surveyRecord);
        return (new ForwardResponse('editForUser'))
            ->withControllerName('ParentUser')
            ->withArguments(['parentUser' => $surveyRecord->getTreatmentRun()->getChild()->getParentUser()]);
    }

    /**
     * action updateRegistrationSurveyForCM
     *
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("surveyRecord")
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord $surveyRecord
     */
    public function updateRegistrationSurveyForCMAction(\WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord $surveyRecord): \Psr\Http\Message\ResponseInterface
    {
        $this->surveyRecordRepository->update($surveyRecord);
        return (new ForwardResponse('editForCM'))
            ->withControllerName('ParentUser')
            ->withArguments(['parentUser' => $surveyRecord->getTreatmentRun()->getChild()->getParentUser()]);
    }

    /**
     * action updateForCM
     *
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord $surveyRecord
     */
    public function updateForCMAction(\WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord $surveyRecord): \Psr\Http\Message\ResponseInterface
    {
        $this->surveyRecordRepository->update($surveyRecord);
        return $this->redirect('listForCM', "Child", null, ['child' => $surveyRecord->getTreatmentRun()->getChild()]);
    }

    /**
     * action deleteProtocol
     *
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord $surveyRecord
     */
    public function deleteProtocolAction(\WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord $surveyRecord, int $week): \Psr\Http\Message\ResponseInterface
    {
        $this->surveyRecordRepository->remove($surveyRecord);
        $child = $surveyRecord->getTreatmentRun()->getChild();
        return $this->redirect('editProtocol', null, null, ['child' => $child, 'week' => $week]);
    }

    /**
     * action deleteProtocolForCM
     *
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord $surveyRecord
     */
    public function deleteProtocolForCMAction(\WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord $surveyRecord, int $week): \Psr\Http\Message\ResponseInterface
    {
        $this->surveyRecordRepository->remove($surveyRecord);
        $child = $surveyRecord->getTreatmentRun()->getChild();
        return $this->redirect('editProtocolForCM', null, null, ['child' => $child, 'week' => $week]);
    }

    /**
     * action handleProtocolForCM
     *
     * @param \WOWGmbH\Wownaechtebuch\Domain\Model\Child|null $child
     * @param int|null $week
     * @param int|null $day
     * @param \WOWGmbH\Wownaechtebuch\DTO\ProtocolData|null $protocolData
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation({"child", "protocolData"})
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function handleProtocolForCMAction(
        ?\WOWGmbH\Wownaechtebuch\Domain\Model\Child $child = null,
        ?int $week = null,
        ?int $day = null,
        ?\WOWGmbH\Wownaechtebuch\DTO\ProtocolData $protocolData = null
    ): \Psr\Http\Message\ResponseInterface {
        // Create Protocol Logic
        if ($child !== null && $week !== null && $day !== null) {
            $latestTreatmentRun = $this->treatmentRunRepository->findLatestByChild($child);

            // create Records until there is atleast one per day in the week
            $surveyRecord = $this->createProtocol($latestTreatmentRun, $week, $day);
            $this->persistenceManager->persistAll();

            // Prepare redirect parameters
            $redirectChild = $child;
            $redirectWeek = $week;
        }
        // Save Protocol Logic
        elseif ($protocolData !== null) {
            foreach ($protocolData->getSurveyRecords()->toArray() as $key => $surveyRecord) {
                if ($surveyRecord->getState() !=  SurveyRecord::STATE_OPEN) continue;
                $surveyRecord->setState($protocolData->getState() ?? 0);
                $this->surveyRecordRepository->update($surveyRecord);
            }

            // Prepare redirect parameters
            $redirectChild = $protocolData->getSurveyRecords()->toArray()[0]->getTreatmentRun()->getChild();
            $redirectWeek = $protocolData->getSurveyRecords()->toArray()[0]->getWeek();
        } else {
            // Handle the case where neither creation nor saving data is provided.
            // You might want to throw an exception, log an error, or redirect to a default page.
            // For example:
            $this->addFlashMessage('Keine gültigen Daten zum Erstellen oder Speichern gefunden.', '', \TYPO3\CMS\Core\Messaging\AbstractMessage::ERROR);
            return $this->redirect('list'); // Or another appropriate action.
        }

        // Redirect to editProtocolForCM
        return $this->redirect('editProtocolForCM', null, null, ['child' => $redirectChild, 'week' => $redirectWeek]);
    }



    /**
     * ###############
     * ### Helpers ###
     * ###############
     */

    private function createProtocol(\WOWGmbH\Wownaechtebuch\Domain\Model\TreatmentRun $treatmentRun, int $week, int $day)
    {

        $survey = $this->surveyRepository->findOneBy(['name' => 'Protokoll']);

        $newSurveyRecord = GeneralUtility::makeInstance(\WOWGmbH\Wownaechtebuch\Domain\Model\SurveyRecord::class);
        $newSurveyRecord->setWeek($week);
        $newSurveyRecord->setDay($day);
        $newSurveyRecord->setState(0);
        $newSurveyRecord->setTreatmentRun($treatmentRun);
        $newSurveyRecord->setSurvey($survey);
        $newSurveyRecord->setSurveyName($survey->getName());

        $treatmentRun->addSurveyRecord($newSurveyRecord);

        foreach ($survey->getQuestions()->toArray() as $key => $question) {
            $questionRecord = GeneralUtility::makeInstance(\WOWGmbH\Wownaechtebuch\Domain\Model\QuestionRecord::class);
            $questionRecord->setSurveyRecord($newSurveyRecord);
            $questionRecord->setAnswerType($question->getAnswerType());
            $questionRecord->setIsSensetive(true);
            $questionRecord->setQuestionText($question->getText());
            $newSurveyRecord->addQuestionRecord($questionRecord);
            $this->questionRecordRepository->add($questionRecord);
        }
        $this->surveyRecordRepository->add($newSurveyRecord);
        $this->treatmentRunRepository->update($treatmentRun);
        $this->persistenceManager->persistAll();


        return $newSurveyRecord;
    }
}
