<?php
/**
 * OBG Customizations
 *
 * Copyright (c) 2021 vonRotenberg
 *
 * @license commercial
 */

namespace vonRotenberg\RealEstateListingBundle\Controller\FrontendModule;

use Contao\CoreBundle\DependencyInjection\Attribute\AsFrontendModule;
use Contao\CoreBundle\Exception\ResponseException;
use Contao\CoreBundle\Image\Studio\Studio;
use Contao\CoreBundle\Twig\FragmentTemplate;
use Contao\ModuleModel;
use Contao\PageModel;
use Contao\StringUtil;
use Contao\System;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\Translation\TranslatorInterface;

#[AsFrontendModule(RealEstateAssetsListController::TYPE, category: 'miscellaneous')]
class RealEstateAssetsListController extends RealEstateAssetsModuleController
{
    public const TYPE = 'vr_re_assets_list';

    /**
     * @var TranslatorInterface
     */
    protected $translator;

    public function __construct(TranslatorInterface $translator)
    {
        $this->translator = $translator;
    }


    protected function getResponse(FragmentTemplate $template, ModuleModel $model, Request $request): Response
    {
        $arrGroups = [];
        $arrFilterOptions = [];

        $jumpTo = PageModel::findByPk($model->jumpTo);
        $urlGenerator = System::getContainer()->get('contao.routing.content_url_generator');


        if (($assets = $this->getRealEstateAssets(StringUtil::deserialize($model->vr_re_categories))) === null)
        {
            return $template->getResponse();
        }

        // Figure Builder
        $figureBuilder = System::getContainer()
            ->get('contao.image.studio')
            ->createFigureBuilder()
            ->setSize($model->imgSize)
            ->setLightboxGroupIdentifier('lb' . $model->id);

        foreach ($assets as $asset)
        {
            $arrItem = array_merge($asset->row(), [
                'teaserFigure' => $this->getImageFigures($asset->gallerySRC, $figureBuilder, $asset->orderSRC, 1),
                'detailsUrl'   => $jumpTo !== null ? $urlGenerator->generate($jumpTo, ['parameters'=>'/items/'.$asset->id]) : null
            ]);

            // Grouping
            if ($model->vr_re_grouped)
            {
                if (!isset($arrGroups[$arrItem['pid']]))
                {
                    $Group = $asset->getRelated('pid');
                    $arrGroups[$arrItem['pid']] = [
                        'label' => $Group->title,
                        'items' => []
                    ];
                }

                $arrGroups[$arrItem['pid']]['items'][] = $arrItem;
            } else {
                $arrGroups['nogroup']['items'][] = $arrItem;
            }

            // Filter options
            if (!empty($asset->numberOfRooms))
            {
                $arrFilterOptions['rooms'][] = ['value'=>$asset->numberOfRooms, 'label'=>$asset->numberOfRooms . ' ' . ($asset->numberOfRooms > 1 ? $this->translator->trans('MSC.re_rooms', [], 'contao_default') : $this->translator->trans('MSC.re_room', [], 'contao_default'))];
            }

        }

        $arrFilterOptions = array_unique($arrFilterOptions);

        $template->set('filterOptions',$arrFilterOptions);
        $template->set('groups',$arrGroups);

        // Handle ajax
        if ($request->headers->get('VR-Ajax') == 'ReAssetsList')
        {
            throw new ResponseException($template->getResponse());
        }

        return $template->getResponse();
    }

}
