<?php

declare(strict_types=1);

namespace Medienreaktor\Courses\Controller;

use TYPO3\CMS\Core\Utility\GeneralUtility;
use Medienreaktor\Courses\Domain\Repository\SubjectRepository;
use TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface;
use TYPO3\CMS\Core\MetaTag\MetaTagManagerRegistry;
use Medienreaktor\Courses\PageTitle;
/**
 * This file is part of the "Courses" 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) 2023 Matthias Schieber <matthias.schieber@medienreaktor.de>, Medienreaktor
 */

/**
 * CourseController
 */
class CourseController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController
{
    /**
     * courseRepository
     *
     * @var \Medienreaktor\Courses\Domain\Repository\CourseRepository
     */
    protected $courseRepository = null;

    /**
     * subjectRepository
     *
     * @var \Medienreaktor\Courses\Domain\Repository\SubjectRepository
     */
    protected $subjectRepository = null;

    /**
     * professionRepository
     *
     * @var \Medienreaktor\Courses\Domain\Repository\ProfessionRepository
     */
    protected $professionRepository = null;

    /**
     * action list
     *
     * @param Medienreaktor\Course\Domain\Model\Course
     * @return string|object|null|void
     */

    /**
     * @var ConfigurationManagerInterface
     */
    protected $configurationManager;

    public function __construct(\TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface $configurationManager, \Medienreaktor\Courses\Domain\Repository\CourseRepository $courseRepository)
    {
        $this->configurationManager = $configurationManager;
        $this->courseRepository = $courseRepository;
    }
    public function listAction(): \Psr\Http\Message\ResponseInterface
    {
        $piFlexFormValues = $this->request->getAttribute('currentContentObject')->data['pi_flexform'];

        $flexFormValues = GeneralUtility::xml2array($piFlexFormValues);

        $subjectTypes = $flexFormValues['data']['sDEF']['lDEF']['settings.listTypes']['vDEF'];
        $professionTypes = $flexFormValues['data']['sDEF']['lDEF']['settings.professionTypes']['vDEF'];
        $showPage = $flexFormValues['data']['sDEF']['lDEF']['settings.detailPidList']['vDEF'];

        if($subjectTypes && $subjectTypes != "none" && !$professionTypes){
            $courses = $this->courseRepository->findByType($subjectTypes);

        } else if($professionTypes){
            $types = explode(",", $professionTypes);

            foreach ($types as $name) {
                $results[] = $this->courseRepository->findByProfession($name);
            }
            foreach ($results as $result){
                foreach ($result as $courseId){
                    $coursesIdByProfession[$courseId["course_id"]] = $courseId["course_id"];
                }
            }
            foreach ($coursesIdByProfession as $courseToGet){
                $queryResult[] = $this->courseRepository->findByImportId($courseToGet);
            }

            foreach ($queryResult as $result){
                $courses[] = $result[0];
            }
        } else{
            $courses = $this->courseRepository->findAll();
        }
        $coursesAmount = count($courses);

        $this->subjectRepository = GeneralUtility::makeInstance(SubjectRepository::class);
        $subjects = $this->subjectRepository->findAll();

        $filter = array();
        foreach ($subjects  as $subject){
            $filter[] = $subject->getTitle();
        }

        if(isset($_GET["subject"])){
            $this->view->assign('prefilter', $_GET["subject"]);
        }

        $this->view->assign('filter', $filter);
        $this->view->assign('showPage', $showPage);
        $this->view->assign('courses', $courses);
        $this->view->assign('coursesCount', $coursesAmount);
        return $this->htmlResponse();
    }

    /**
     * action show
     *
     * @param Medienreaktor\Course\Domain\Model\Course
     * @return string|object|null|void
     */
    public function showAction(\Medienreaktor\Courses\Domain\Model\Course $course): \Psr\Http\Message\ResponseInterface
    {

        $metaTagManager = GeneralUtility::makeInstance(MetaTagManagerRegistry::class)->getManagerForProperty('og:title');
        $metaTagManager->addProperty('og:title', $course->getSeoTitle());
        $metaTagManager->addProperty('og:description', $course->getSeoDescription());
        $metaTagManager->addProperty('og:type', "article");
        $metaTagManager->removeProperty('title');


        $titleProvider = GeneralUtility::makeInstance(PageTitle\CoursesPageTitleProvider::class);
        $titleProvider->setTitle($course->getSeoTitle());

        $parsedown = new \Parsedown();

        if($course->getSeoImage()){
            $metaTagManager->addProperty('og:image', "https://".$_SERVER["HTTP_HOST"]."/".$course->getSeoImage()->getOriginalResource()->getPublicUrl());
        } else{
            $subjects = $course->getSubject();
            if($subjects[0]->getImage()){
                $metaTagManager->addProperty('og:image', "https://".$_SERVER["HTTP_HOST"]."/".$subjects[0]->getImage()->getOriginalResource()->getPublicUrl());
            }
        }

        $metaTagManager = GeneralUtility::makeInstance(MetaTagManagerRegistry::class)->getManagerForProperty('description');
        $metaTagManager->addProperty('description', $course->getSeoDescription());

        $piFlexFormValues = $this->request->getAttribute('currentContentObject')->data['pi_flexform'];
        $flexFormValues = GeneralUtility::xml2array($piFlexFormValues);

        $appointmentPage = $flexFormValues['data']['sDEF']['lDEF']['settings.appointmentPage']['vDEF'];
        $requestPage = $flexFormValues['data']['sDEF']['lDEF']['settings.requestPage']['vDEF'];

        $contents = explode("\n-",$course->getContents());
        if($contents[0][0] == "-"){
        $contents[0] = substr($contents[0], 1);

        }

        $this->view->assign('appointmentPage', $appointmentPage);
        $this->view->assign('requestPage', $requestPage);
        $this->view->assign('course', $course);
        $this->view->assign('courseContent', $parsedown->text($course->getContents()));
        $this->view->assign('courseUri' ,"https://".$GLOBALS["_SERVER"]["SERVER_NAME"].$GLOBALS["_SERVER"]["REQUEST_URI"]);
        return $this->htmlResponse();
    }

    /**
     * action highlight
     *
     * @param Medienreaktor\Course\Domain\Model\Course
     * @return string|object|null|void
     */
    public function highlightAction(): \Psr\Http\Message\ResponseInterface
    {
        $piFlexFormValues = $this->request->getAttribute('currentContentObject')->data['pi_flexform'];

        $flexFormValues = GeneralUtility::xml2array($piFlexFormValues);

        $heading = $flexFormValues['data']['sDEF']['lDEF']['settings.highlightHeading']['vDEF'];
        $linkTitle = $flexFormValues['data']['sDEF']['lDEF']['settings.highlightLinkTitle']['vDEF'];
        $link = $flexFormValues['data']['sDEF']['lDEF']['settings.highlightLinkToAll']['vDEF'];
        $columns = $flexFormValues['data']['sDEF']['lDEF']['settings.highlightColumns']['vDEF'];
        $type = $flexFormValues['data']['sDEF']['lDEF']['settings.type']['vDEF'];
        $showPage = $flexFormValues['data']['sDEF']['lDEF']['settings.detailPidHighlights']['vDEF'];
        $maxAmount = isset($flexFormValues['data']['sDEF']['lDEF']['settings.highlightMaxAmount']) ? (int)$flexFormValues['data']['sDEF']['lDEF']['settings.highlightMaxAmount']['vDEF'] : 0;
        $courses = $this->courseRepository->findHighlighted();
        $coursesArr = array();

        foreach ($courses as $key => $value){
            $coursesArr[] = $value;
        }

        if($maxAmount && $maxAmount != "all"){
            if(count($coursesArr) >= $maxAmount){
                $coursesArr = array_slice($coursesArr, 0, $maxAmount);
            }
        }

        $this->view->assign('courses', $coursesArr);
        $this->view->assign('showPage', $showPage);
        $this->view->assign('type', $type);
        $this->view->assign('heading', $heading);
        $this->view->assign('link', $link);
        $this->view->assign('linkTitle', $linkTitle);
        $this->view->assign('columns', $columns);
        return $this->htmlResponse();

    }

    /**
     * action coursetype
     *
     * @return string|object|null|void
     */
    public function coursetypeAction(): \Psr\Http\Message\ResponseInterface
    {
        return $this->htmlResponse();
    }

    /**
     * action courseworkshopform
     * @param Medienreaktor\Course\Domain\Model\Course
     * @param Medienreaktor\Course\Domain\Model\Workshop
     * @param string title
     * @return string|object|null|void
     */
    public function courseworkshopformAction(\Medienreaktor\Courses\Domain\Model\Course $course = NULL, \Medienreaktor\Courses\Domain\Model\Workshop $workshop = NULL, string $title = ""): \Psr\Http\Message\ResponseInterface
    {
        if($title){
            $this->view->assign('formTitle', $title);
        }
        if($course){
            $this->view->assign('course', $course);
        }
        if($workshop){
            $this->view->assign('workshop', $workshop);
        }
        return $this->htmlResponse();
    }
}
