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

namespace vonRotenberg\RealEstateListingBundle\Controller\FrontendModule;

use Contao\CoreBundle\DependencyInjection\Attribute\AsFrontendModule;
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;

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

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

        $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();
        }

        $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
            ]);
            dump($arrItem);

            // 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;
            }

        }

        $template->set('groups',$arrGroups);
        return $template->getResponse();
    }

}
