<?php

declare(strict_types=1);

/*
 * This file is part of modal bundle for Contao.
 *
 * (c) Benjamin Roth
 *
 * @license LGPL-3.0-or-later
 */

namespace vonRotenberg\ModalBundle\Controller\ContentElement;

use Contao\ContentModel;
use Contao\Controller;
use Contao\CoreBundle\Controller\ContentElement\AbstractContentElementController;
use Contao\CoreBundle\ServiceAnnotation\ContentElement;
use Contao\Template;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use vonRotenberg\ModalBundle\Model\ModalModel;

/**
 * @ContentElement(ModalElementController::TYPE, category="miscellaneous")
 */
class ModalElementController extends AbstractContentElementController
{
    public const TYPE = 'modal_element';

    protected function getResponse(Template $template, ContentModel $model, Request $request): ?Response
    {
        if (!$model->modal_configurations || ($modal = ModalModel::findPublishedById($model->modal_configurations)) === null)
        {
            return new Response();
        }

        $id = $modal->id;

        $template->details = function () use ($id)
        {
            $strDetails = '';
            $objElement = ContentModel::findPublishedByPidAndTable($id, 'tl_vr_modal');

            if ($objElement !== null)
            {
                while ($objElement->next())
                {
                    $strDetails .= Controller::getContentElement($objElement->current());
                }
            }

            return $strDetails;
        };

        $template->hasDetails = static function () use ($id)
        {
            return ContentModel::countPublishedByPidAndTable($id, 'tl_vr_modal') > 0;
        };

        $template->modal_configuration = $modal->row();

        $GLOBALS['TL_BODY'][] = $template->parse();

        return new Response();
    }

}