<?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\Twig\FragmentTemplate;
use Contao\Input;
use vonRotenberg\RealEstateListingBundle\Model\RealEstateAssetsModel;
use Contao\Controller;
use Contao\CoreBundle\Image\Studio\Studio;
use Contao\Date;
use Contao\FrontendTemplate;
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(RealEstateAssetsReaderController::TYPE, category: 'miscellaneous')]
class RealEstateAssetsReaderController extends RealEstateAssetsModuleController
{
    public const TYPE = 'vr_re_assets_reader';

    /**
     * @var RealEstateAssetsModel|null
     */
    protected $asset;

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

    protected function getResponse(FragmentTemplate $template, ModuleModel $model, Request $request): Response
    {
        $this->translator = System::getContainer()->get('translator');
        Controller::loadLanguageFile(RealEstateAssetsModel::getTable());

        $jumpTo = PageModel::findByPk($model->jumpTo);

        // Set the item from the auto_item parameter
        if (!isset($_GET['items']) && \Config::get('useAutoItem') && isset($_GET['auto_item']))
        {
            Input::setGet('items', Input::get('auto_item'));
        }

        $this->asset = RealEstateAssetsModel::findPublishedByIdOrAlias(Input::get('items'));

        if ($this->asset === null)
        {
            return new Response();
        }

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

        $arrItem = array_merge($this->asset->row(), [
            'features'          => StringUtil::deserialize($this->asset->features,true),
            'parking'          => StringUtil::deserialize($this->asset->parking,true),
            'availableFrom'     => ($this->asset->availability == 'immediately' ? $this->translator->trans('REF.re_availability.immediately', [], 'contao_default') : Date::parse(Date::getNumericDateFormat(), $this->asset->availableFrom)),
            'deadline'          => ($this->asset->stop > 0 ? Date::parse(Date::getNumericDateFormat(), $this->asset->stop) : ''),
            'teaserFigure'      => $this->getImageFigures($this->asset->gallerySRC, $figureBuilder, $this->asset->orderSRC, 1),
            'galleryFigures'    => $this->getImageFigures($this->asset->gallerySRC, $figureBuilder, $this->asset->orderSRC, 0, 0),
            'floorPlansFigures' => $this->getImageFigures($this->asset->floorPlansSRC, $figureBuilder, $this->asset->floorPlansOrderSRC),
            'listUrl'           => $jumpTo !== null ? $jumpTo->getFrontendUrl() : null,
            'pdfUrl'            => $request->getBaseUrl() . $request->getPathInfo() . '?pdf',
            'qrUrl'             => $request->getUriForPath($request->getPathInfo()),
            'hasProperty'       => false
        ]);

        // Check for object
        if (($Property = $this->asset->getRelated('managedPropertyId')) !== null) {
            $arrItem['hasProperty'] = true;
            $arrItem['property'] = array_merge($Property->row(),[
                'teaserFigure'      => $this->getImageFigures($Property->gallerySRC, $figureBuilder, $Property->orderSRC, 1),
                'galleryFigures'    => $this->getImageFigures($Property->gallerySRC, $figureBuilder, $Property->orderSRC, 0, 0),
            ]);
        }


        if (isset($_GET['pdf']))
        {
            $PDF = new FrontendTemplate('exposePdfDefinition');
            $PDF->item = $arrItem;
//      echo $PDF->parse();
            $response = $PDF->getResponse();
            $template->pdfJs = $response->getContent();
            throw new ResponseException($response);
//      echo $response->getContent();
//      exit;
        }

        $template->formURL = $model->vr_re_formUrl;

        $template->item = $arrItem;

        return $template->getResponse();
    }

}
