<?php

declare(strict_types=1);

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

namespace vonRotenberg\WeinanlieferungBundle\Controller\Frontend\Module;

use Contao\Controller;
use Contao\CoreBundle\Controller\FrontendModule\AbstractFrontendModuleController;
use Contao\CoreBundle\Exception\ResponseException;
use Contao\CoreBundle\InsertTag\InsertTagParser;
use Contao\CoreBundle\ServiceAnnotation\FrontendModule;
use Contao\Date;
use Contao\ModuleModel;
use Contao\StringUtil;
use Contao\Template;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use vonRotenberg\WeinanlieferungBundle\Model\WeinanlieferungRebsorteModel;
use vonRotenberg\WeinanlieferungBundle\Model\WeinanlieferungSlotsModel;

/**
 * @FrontendModule(WeinanlieferungSlotsListModuleController::TYPE, category="miscellaneous")
 */
class WeinanlieferungSlotsListModuleController extends AbstractFrontendModuleController
{
    public const TYPE = 'wa_slots_list';

    private $insertTagParser;

    public function __construct(InsertTagParser $insertTagParser)
    {
        $this->insertTagParser = $insertTagParser;
    }


    protected function getResponse(Template $template, ModuleModel $model, Request $request): ?Response
    {
        $standortIds = StringUtil::deserialize($model->vr_wa_standortId);
        $arrData = $template->getData();
        $arrOptions = [];

        // Add filter values
        if (!empty($_GET['filter_kapazitaet']))
        {
            $arrData['filter']['kapazitaet']['selected'] = $_GET['filter_kapazitaet'];
            $arrOptions['column'][] = 'behaelter = ?';
            $arrOptions['value'][] = $_GET['filter_kapazitaet'];
        }
        if (!empty($_GET['filter_sorte']))
        {
            $arrData['filter']['sorte']['selected'] = $_GET['filter_sorte'];
            $arrOptions['column'][] = 'FIND_IN_SET(?,sorte)';
            $arrOptions['value'][] = $_GET['filter_sorte'];
        }
        $arrData['filter']['kapazitaet']['options'] = range(1,30);

        if (($Sorten = WeinanlieferungRebsorteModel::findAll(['order'=>'title ASC'])) !== null)
        {
            $arrData['filter']['sorte']['options'] = array_combine($Sorten->fetchEach('id'),$Sorten->fetchEach('title'));
        }

        // Get available slots
        if (($slots = WeinanlieferungSlotsModel::findMultiplePublishedByPids($standortIds,$arrOptions)) !== null)
        {
            /** @var WeinanlieferungSlotsModel $slot */
            foreach ($slots as $slot)
            {
                $day = new Date($slot->date);
                $arrSorten = [];
                $intAvailableBehaelter = $slot->getAvailableBehaelter();

                if (($Sorten = $slot->getRelated('sorte')) !== null)
                {
                    $arrSorten = $Sorten->fetchEach('title');
                }

                $arrData['days'][$day->dayBegin][] = array_merge($slot->row(),[
                    'sorte' => $arrSorten,
                    'behaelterAvailable' => $intAvailableBehaelter,
                    'buchbar' => (boolean) $intAvailableBehaelter
                ]);
            }
        }

        $template->setData($arrData);

        // Handle ajax
        if ($request->headers->get('VR-Ajax') == 'WaSlotsModule')
        {
            throw new ResponseException(new Response($this->insertTagParser->replace($template->parse())));
        }

        return $template->getResponse();
    }

}