<?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\FrontendUser;
use Contao\ModuleModel;
use Contao\StringUtil;
use Contao\System;
use Contao\Template;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use vonRotenberg\WeinanlieferungBundle\Model\WeinanlieferungLeseartModel;
use vonRotenberg\WeinanlieferungBundle\Model\WeinanlieferungRebsorteModel;
use vonRotenberg\WeinanlieferungBundle\Model\WeinanlieferungReservationModel;
use vonRotenberg\WeinanlieferungBundle\Model\WeinanlieferungSlotsModel;

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

    private $insertTagParser;

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


    protected function getResponse(Template $template, ModuleModel $model, Request $request): ?Response
    {
        $arrData = $template->getData();

        // Get bookings
        if (($bookings = WeinanlieferungReservationModel::findBy("uid",FrontendUser::getInstance()->id,['order' => "(SELECT tl_vr_wa_slot.time FROM tl_vr_wa_slot WHERE tl_vr_wa_slot.id=tl_vr_wa_reservation.pid) ASC"])) !== null)
        {
            /** @var WeinanlieferungReservationModel $booking */
            foreach ($bookings as $booking)
            {
                if (($Slot = $booking->getRelated('pid')) !== null)
                {
                    $day = new Date($Slot->date);
                    $arrSorten = [];
                    $arrErnteart = [];

                    $SortenLeseart = explode(';',$booking->sorten);
                    foreach($SortenLeseart as $sorteLeseart)
                    {
                        list($sorte,$leseart) = explode(',',$sorteLeseart);
                        $objSorte = WeinanlieferungRebsorteModel::findByPk($sorte);
                        $objLeseart = WeinanlieferungLeseartModel::findByPk($leseart);
                        $arrSorten[$objSorte->id.','.$objLeseart->id] = ($objSorte !== null  ? $objSorte->title : '') . ' ' . ($objLeseart !== null  ? $objLeseart->title : '');
                    }

                    $strStandort = '';
                    if (($Standort = $Slot->getRelated('pid')) !== null)
                    {
                        $strStandort = $Standort->title;
                    }

                    if ($booking->ernteart !== null)
                    {
                        foreach (explode(',', $booking->ernteart) as $ernteart)
                        {
                            $arrErnteart[] = $GLOBALS['TL_LANG']['REF']['wa_ernteart'][$ernteart] ?? $ernteart;
                        }
                    }

                    $arrLage = [];
                    if (($Lage = $booking->getRelated('lage')) !== null)
                    {
                        $arrLage = $Lage->fetchEach('title');
                    }

                    $arrData['days'][$day->dayBegin][] = array_merge($booking->row(), [
                        'sorte'              => $arrSorten,
                        'slot'  => array_merge($Slot->row(),[
                            'anmerkungen' => $Slot->anmerkungen ? StringUtil::substr(strip_tags($Slot->anmerkungen),110) : '',
                        ]),
                        'standort' => $strStandort,
                        'ernteart' => $arrErnteart,
                        'lage' => $arrLage,
                    ]);
                }
            }
        }

        $template->setData($arrData);

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

        return $template->getResponse();
    }

}