<?php
namespace GI\MentorFinder\Controller;

/*
 * This file is part of the TYPO3 CMS project.
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */

use TYPO3\CMS\Extbase\Utility\LocalizationUtility;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use GI\MentorFinder\Domain\Repository\FrontendUserRepository;
use TYPO3\CMS\Core\Pagination\ArrayPaginator;
use TYPO3\CMS\Core\Pagination\SimplePagination;

/**
 * Class SearchController
 * @package GI\MentorFinder\Controller
 */

class SearchController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController
{
    const TYPE_CONTACT = 'contact';
    const TYPE_REQUEST = 'request';
    const TYPE_REPORT = 'report';

    protected FrontendUserRepository $frontendUserRepository;

    public function __construct(
        FrontendUserRepository $frontendUserRepository
    ) {
        $this->frontendUserRepository = $frontendUserRepository;
    }

    /**
     * initialize list action
     *
     * @return void
     */
    public function initializeListAction()
    {
        if ($this->arguments->hasArgument('demand')) {
            $propertyMappingConfiguration = $this->arguments['demand']->getPropertyMappingConfiguration();
            $propertyMappingConfiguration->allowAllProperties();
            $propertyMappingConfiguration->setTypeConverterOption('TYPO3\CMS\Extbase\Property\TypeConverter\PersistentObjectConverter',
                \TYPO3\CMS\Extbase\Property\TypeConverter\PersistentObjectConverter::CONFIGURATION_CREATION_ALLOWED, TRUE);
        }
    }

    /**
     * initialize form action
     *
     * @return void
     */
    public function initializeFormAction()
    {
        if ($this->arguments->hasArgument('contact')) {
            $propertyMappingConfiguration = $this->arguments['contact']->getPropertyMappingConfiguration();
            $propertyMappingConfiguration->allowAllProperties();
            $propertyMappingConfiguration->setTypeConverterOption('TYPO3\CMS\Extbase\Property\TypeConverter\PersistentObjectConverter',
                \TYPO3\CMS\Extbase\Property\TypeConverter\PersistentObjectConverter::CONFIGURATION_CREATION_ALLOWED, TRUE);
        }
    }

    /**
     * action list
     *
     * @param \GI\MentorFinder\Domain\Model\Demand $demand
     * @param int $currentPage
     * @return void
     */
    public function listAction(\GI\MentorFinder\Domain\Model\Demand $demand = NULL, int $currentPage = 1)
    {
        if (!$demand) {
            return;
        }

        if ($demand->getShowAll()) {
            $mentors = $this->frontendUserRepository->findAllNotDisabled();
        } else {
            $mentors = $this->frontendUserRepository->findAllByDemand($demand);

            if ($mentors->count() == 0) {
                $mentors = $this->frontendUserRepository->findAllNotDisabled();
                $this->view->assign('noResult', $demand);
            }
        }

        if ($GLOBALS['TSFE']->fe_user->user) {
            $this->view->assign('loggedIn', true);
        }

        $itemsPerPage = 10;
        if ($this->settings['pagination']['itemsPerPage']) {
            $itemsPerPage = $this->settings['pagination']['itemsPerPage'];
        }

        $arrayPaginator = new ArrayPaginator($mentors->toArray(), $currentPage, $itemsPerPage);
        $paging = new SimplePagination($arrayPaginator);

        $this->view->assignMultiple(
            [
                'demand' => $demand,
                'mentors' => $mentors,
                'paginator' => $arrayPaginator,
                'paging' => $paging,
                'pages' => range(1, $paging->getLastPageNumber()),
            ]
        );

    }

    /**
     * action form
     *
     * @param \GI\MentorFinder\Domain\Model\Contact $contact
     * @return void
     */
    public function formAction(\GI\MentorFinder\Domain\Model\Contact $contact = NULL)
    {
        if (!$contact) {
            return;
        }

        $user = $this->frontendUserRepository->findByUid($GLOBALS['TSFE']->fe_user->user['uid']);

        $contact->setId($user->getUid());
        $contact->setFirstName($user->getFirstname());
        $contact->setLastName($user->getLastname());
        $contact->setEmail($user->getEmail());

        $this->view->assign('contact', $contact);
    }

    /**
     * action send
     *
     * @param \GI\MentorFinder\Domain\Model\Contact $contact
     * @return void
     */
    public function sendAction(\GI\MentorFinder\Domain\Model\Contact $contact = NULL)
    {
        if (!$contact) {
            return;
        }

        $user = $this->frontendUserRepository->findByUid($GLOBALS['TSFE']->fe_user->user['uid']);
        $contact->setId($user->getUid());
        $contact->setFirstName($user->getFirstname());
        $contact->setLastName($user->getLastname());

        $mentor = $this->frontendUserRepository->findByUid($contact->getMentor());

        switch ($contact->getType()) {
            case self::TYPE_CONTACT:
                if ($mentor->getEmail() && $contact->getEmail()) {
                    $this->sendMail($this->settings['mail']['systemMailAddress'],$mentor->getEmail(),'Mentor',$mentor,$contact);
                }
                if ($this->settings['mail']['systemMailAddress'] && $contact->getEmail()) {
                    $this->sendMail($this->settings['mail']['systemMailAddress'],$contact->getEmail(),'Mentee',$contact);
                }
                $requests = $mentor->getRequests();
                $requests = $requests+1;
                $mentor->setRequests($requests);
                $this->frontendUserRepository->update($mentor);
                break;
            case self::TYPE_REQUEST:
                if ($this->settings['mail']['adminMailAddress'] && $contact->getEmail()) {
                    $this->sendMail($this->settings['mail']['systemMailAddress'],$this->settings['mail']['adminMailAddress'],'RequestAdmin',$contact);
                }
                if ($this->settings['mail']['systemMailAddress'] && $contact->getEmail()) {
                    $this->sendMail($this->settings['mail']['systemMailAddress'],$contact->getEmail(),'RequestMentee',$contact);
                }
                break;
            case self::TYPE_REPORT:
                if ($this->settings['mail']['reportMailAddress']) {
                    $this->sendMail($this->settings['mail']['systemMailAddress'],$this->settings['mail']['reportMailAddress'],'ReportAdmin',$contact,$mentor);
                }
                break;
        }

        $this->view->assign('contact', $contact);
    }

    /**
     * send mail
     *
     * @param string $from
     * @param string $to
     * @param string $type
     * @param \GI\MentorFinder\Domain\Model\Contact $contact
     * @param mixed $data
     * @return bool
     */
    protected function sendMail($from,$to,$type,$contact,$data = null)
    {
        $mailTemplate = $this->objectManager->get(\TYPO3\CMS\Fluid\View\StandaloneView::class);
        $mailTemplate->assignMultiple([
            'contact' => $contact,
            'data' => $data
        ]);

        $mailTemplate->setTemplatePathAndFilename(GeneralUtility::getFileAbsFileName($this->settings['mail']['templateFolder'].$type.'Html.html'));
        $mailTemplate->setFormat('html');
        $html = $mailTemplate->render();

        $mailTemplate->setTemplatePathAndFilename(GeneralUtility::getFileAbsFileName($this->settings['mail']['templateFolder'].$type.'Plain.html'));
        $mailTemplate->setFormat('plain');
        $plain = $mailTemplate->render();

        $mail = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Mail\MailMessage::class);
        $mail->from(new \Symfony\Component\Mime\Address($from));
        $mail->to(new \Symfony\Component\Mime\Address($to));
        $mail->subject(LocalizationUtility::translate($type.'.subject','MentorFinder'));
        $mail->text($plain);
        $mail->html($html);

        return $mail->send();
    }
}