<?php

declare(strict_types=1);

/*
 * This file is part of contao-weinanlieferung-bundle.
 *
 * (c) vonRotenberg
 *
 * @license commercial
 */

namespace vonRotenberg\WeinanlieferungBundle\Controller\Backend;

use Contao\Ajax;
use Contao\Backend;
use Contao\BackendTemplate;
use Contao\Config;
use Contao\Controller;
use Contao\CoreBundle\Controller\AbstractController;
use Contao\CoreBundle\Csrf\ContaoCsrfTokenManager;
use Contao\Date;
use Contao\DC_File;
use Contao\Environment;
use Contao\FileTree;
use Contao\FrontendUser;
use Contao\Image;
use Contao\Input;
use Contao\Message;
use Contao\SelectMenu;
use Contao\StringUtil;
use Contao\System;
use Contao\TextArea;
use Contao\TextField;
use Contao\Upload;
use Contao\Widget;
use Doctrine\DBAL\Connection;
use MenAtWork\MultiColumnWizardBundle\Contao\Widgets\MultiColumnWizard;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\Translation\TranslatorInterface;
use Twig\Environment as TwigEnvironment;
use vonRotenberg\WeinanlieferungBundle\Model\WeinanlieferungLeseartModel;
use vonRotenberg\WeinanlieferungBundle\Model\WeinanlieferungRebsorteModel;
use vonRotenberg\WeinanlieferungBundle\Model\WeinanlieferungReservationModel;
use vonRotenberg\WeinanlieferungBundle\Model\WeinanlieferungSlotsModel;
use vonRotenberg\WeinanlieferungBundle\Model\WeinanlieferungSlottypesModel;

/**
 * @Route("%contao.backend.route_prefix%/weinanlieferung/daily_schedule", name=self::class, defaults={"_scope" = "backend"})
 */
class WeinanlieferungDailyScheduleController extends AbstractController
{
    private $twig;
    private $tokenManager;
    private $request;
    private $db;

    private $translator;

    protected $fields;

    public function __construct(TwigEnvironment $twig, ContaoCsrfTokenManager $tokenManager, RequestStack $requestStack, Connection $db, TranslatorInterface $translator)
    {
        $this->twig = $twig;
        $this->tokenManager = $tokenManager;
        $this->request = $requestStack->getCurrentRequest();
        $this->db = $db;
        $this->translator = $translator;

        $container = System::getContainer();
        $objSession = $container->get('session');


        $strKey = Input::get('popup') ? 'popupReferer' : 'referer';
        $strRefererId = $this->request->attributes->get('_contao_referer_id');

        $session = $objSession->get($strKey);
        $session[$strRefererId]['current'] = substr(Environment::get('requestUri'), \strlen(Environment::get('path')) + 1);
        $objSession->set($strKey, $session);
    }

    public function __invoke(): Response
    {
        System::loadLanguageFile('default');

        $GLOBALS['TL_CSS']['cirrus'] = 'bundles/vonrotenbergweinanlieferung/css/backend.css|static';
        $GLOBALS['TL_CSS']['cirrus'] = 'bundles/vonrotenbergweinanlieferung/css/daily_schedule_view.scss|static';
        $arrData = [
            'request_token' => $this->tokenManager->getDefaultTokenValue(),
            'ref'           => $this->request->attributes->get('_contao_referer_id')
        ];

        // Handle ajax request pre actions
        if ($_POST && Environment::get('isAjaxRequest'))
        {
            $this->objAjax = new Ajax(Input::post('action'));
            $this->objAjax->executePreActions();
        }

        // Handle ajax request post actions
        if ($_POST && Environment::get('isAjaxRequest'))
        {
            $dc = new DC_File('tl_vr_wa_slotassistant');
            $this->objAjax->executePostActions($dc);
        }

        // Get events
        $Tag = new Date(mktime(0,0,0,12,24,2024));
        $scheduleRows = 96;
        $scheduleRowSeconds = ($Tag->dayEnd - $Tag->dayBegin) / $scheduleRows;
        $arrOptions = [];
        $arrOptions['column'][] = 'tl_vr_wa_slot.time BETWEEN ? and ?';
        $arrOptions['value'][] = $Tag->dayBegin;
        $arrOptions['value'][] = $Tag->dayEnd;

        $arrSlots = [];
        // Todo: Add columns per location for a side by side view
        $arrColumns = [];
        $arrRows = array_flip(range(1,$scheduleRows));
        array_walk($arrRows,function(&$val) {
            $val = null;
        });
        if (($slots = WeinanlieferungSlotsModel::findMultiplePublishedByPids([1],$arrOptions)) !== null)
        {
            foreach ($slots as $slot)
            {
                $Slottime = new Date($slot->time);
                $startOffset = $slot->time - $Slottime->dayBegin;
                $endOffset = $slot->time + ($slot->duration * 60) - $Slottime->dayBegin;
                $rowStart = ceil($startOffset / $scheduleRowSeconds);
                $rowEnd = ceil($endOffset / $scheduleRowSeconds);

                $arrSlots[$rowStart] = [
                    'rowStart' => $rowStart,
                    'rowEnd' => $rowEnd,
                    'slot' => $slot->row(),
                    'location' => $slot->getRelated('pid')->row()
                ];

                for ($i=$rowStart; $i < $rowEnd; $i++)
                {
                    $arrRows = array_diff_key($arrRows, [$i=>null]);
                }
            }
        }
        $arrRows = array_replace($arrRows,$arrSlots);
        ksort($arrRows);

        $events = [
            [
                'title' => 'Morning Meeting',
                'start' => '09:00',
                'end' => '10:00',
            ],
            [
                'title' => 'Team Stand-up',
                'start' => '11:00',
                'end' => '11:30',
            ],
            [
                'title' => 'Lunch Break',
                'start' => '12:00',
                'end' => '13:00',
            ],
            [
                'title' => 'Client Call',
                'start' => '15:00',
                'end' => '16:00',
            ],
        ];

        return new Response(
            $this->twig->render(
                '@Contao_VonrotenbergWeinanlieferungBundle/be_wa_daily_schedule.html.twig',
                [
                    'events' => $arrRows,
                    'date' => new \DateTime()
                ]
            )
        );
    }
}