<?php

namespace Ig\IgReservations\Command;

use DateTime;
use Doctrine\DBAL\ParameterType;
use Ig\IgReservations\Service\MailService;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use TYPO3\CMS\Core\Core\Bootstrap;
use TYPO3\CMS\Core\Core\SystemEnvironmentBuilder;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Http\ServerRequest;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Configuration\ConfigurationManager;
use TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface;

class AlarmCommand extends Command
{
    public function __construct(
        protected ConfigurationManager $configurationManager,
        //protected EventRepository $eventRepository
    ) {
        parent::__construct();
    }

    /**
     * Configure the command by defining the name, options and arguments
     */
    protected function configure()
    {
        $this->setDescription('Alarm email for events that are more than a week without an assigned teammember');
        $this->setHelp('Alarms the admin that an event has no assigned teammember');
    }

    /**
     * Executes the command for showing sys_log entries
     */
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);
        //$io->title($this->getDescription());
        //$io->writeln($this->getHelp());
        Bootstrap::initializeBackendAuthentication();
        
        $extbaseFrameworkConfiguration = $this->configurationManager->getConfiguration(ConfigurationManagerInterface::CONFIGURATION_TYPE_FULL_TYPOSCRIPT);
        $settings = $extbaseFrameworkConfiguration['plugin.']['tx_igreservations.']['settings.'];

        if (!isset($GLOBALS['TYPO3_REQUEST'])) {
            $GLOBALS['TYPO3_REQUEST'] = (new ServerRequest('/', 'GET'))
                                            ->withAttribute('applicationType', SystemEnvironmentBuilder::REQUESTTYPE_FE);
        } else {
            $GLOBALS['TYPO3_REQUEST'] = $GLOBALS['TYPO3_REQUEST']
                                            ->withAttribute('applicationType', SystemEnvironmentBuilder::REQUESTTYPE_FE);
        }   

        $this->configurationManager->setRequest($GLOBALS['TYPO3_REQUEST']);

        $periode = '-1 week';
        $now = new DateTime();
        $now->setTime(12, 0, 0);

        $aWeekAgo = new DateTime();
        $aWeekAgo->setTime(12, 0, 0);
        $aWeekAgo->modify($periode);


        $qb = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('tx_igreservations_domain_model_event');
        $events = $qb->select('ev.*', 'cat.name as category_name', 'st.name as status_name', 'ts.name as timeslot_name')
            ->from('tx_igreservations_domain_model_event', 'ev')
            ->join('ev', 'tx_igreservations_domain_model_reservation', 'res', 'res.event = ev.uid')
            ->leftJoin('ev', 'tx_igreservations_domain_model_status', 'st', 'st.uid = ev.status')
            ->leftJoin('ev', 'tx_igreservations_domain_model_category', 'cat', 'cat.uid = ev.category')
            ->leftJoin('ev', 'tx_igreservations_domain_model_timeslot', 'ts', 'ts.uid = ev.timeslot')
            ->where($qb->expr()->and(
                $qb->expr()->gte('start_date', $qb->createNamedParameter($now->format('Y-m-d'), ParameterType::STRING)),
                $qb->expr()->lte('ev.crdate', $qb->createNamedParameter($aWeekAgo->getTimestamp(), ParameterType::INTEGER)),
                $qb->expr()->eq('teammembers', 0),
                $qb->expr()->eq('st.needs_action', 1)
            ))
            ->executeQuery()
            ->fetchAllAssociative();
//var_dump($events);
            //$events = $this->eventRepository->findForAlarm('-1 week');

        if (count($events) > 0) {
            $io->writeln('<comment>Found ' . count($events) . ' events');
            $subject = 'Unbestätigte Buchungen';
            $from = $settings['coordinationPersonMailFrom'];
            $mailsTo = [$settings['coordinationPersonMailFrom']];

            $mailService = GeneralUtility::makeInstance(MailService::class);
            $mailService->setSettings($settings);
            $mailService->setRequest($GLOBALS['TYPO3_REQUEST']);
            $mailService->sendMail(
                $from,
                $mailsTo,
                $subject,
                'IgReservations/Command/Alarm/Admin',
                [
                    'events' => $events,
                    'settings' => $settings,
                ]
            );
        }
        return 0;
    }
}
