<?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;
use vonRotenberg\WeinanlieferungBundle\Model\WeinanlieferungStandortModel;

/**
 * @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,9,1,2025));
        $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;

        // Todo: Add columns per location for a side by side view
        $arrColumns = [];
        $arrRowsTemplate = array_flip(range(1,$scheduleRows));
        array_walk($arrRowsTemplate,function(&$val) {
            $val = null;
        });
        if (($Locations = WeinanlieferungStandortModel::findAll()) !== null)
        {
            foreach ($Locations as $location)
            {
                $arrSlots = [];
                $arrRows = $arrRowsTemplate;

                if (($Slots = WeinanlieferungSlotsModel::findPublishedByPid($location->id,$arrOptions)) !== null)
                {
                    /** @var WeinanlieferungSlotsModel $slot */
                    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' => $location->row(),
                            'behaelterAvailable' => $slot->getAvailableBehaelter(),
                        ];

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

                $arrColumns[] = [
                    'label' => $location->title,
                    'entries' => $arrRows
                ];
            }
        }

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