<?php

declare(strict_types=1);

namespace App\Controller\FrontendModule;

use Contao\CoreBundle\Controller\FrontendModule\AbstractFrontendModuleController;
use Contao\CoreBundle\DependencyInjection\Attribute\AsFrontendModule;
use Contao\CoreBundle\Image\Studio\Studio;
use Contao\ModuleModel;
use Contao\StringUtil;
use Contao\System;
use Contao\Template;
use Doctrine\DBAL\Connection;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

#[AsFrontendModule(category: "miscellaneous")]
class TeamListController extends AbstractFrontendModuleController
{
    /**
     * @var Connection
     */
    protected $db;

    public function __invoke(Request $request, ModuleModel $model, string $section, array $classes = null): Response
    {
        $this->db = System::getContainer()->get('database_connection');
        return parent::__invoke($request, $model, $section, $classes); // TODO: Change the autogenerated stub
    }

    protected function getResponse(Template $template, ModuleModel $model, Request $request): Response
    {
        $Team = $this->db->executeQuery(
            "SELECT * FROM tl_esm_team WHERE division IN (:division) AND pid = :group AND published = '1' ORDER BY division, lastname",
            [
                'division' => StringUtil::deserialize($model->eSM_team_divisions),
                'group' => $model->eSM_team_group
            ],
            ['division' => Connection::PARAM_STR_ARRAY]
        );

        if ($Team->rowCount())
        {
            $arrTeam = [];
            $figureBuilder = System::getContainer()
                ->get(Studio::class)
                ->createFigureBuilder();
//                ->enableLightbox();

            foreach ($Team->fetchAllAssociative() as $member)
            {
                $arrTeam[] = array_merge($member,[
                    'imageFigure' => $figureBuilder->fromUuid($member['singleSRC'])->setSize($model->imgSize)->build()
                ]);
            }

            shuffle($arrTeam);

            $template->teammembers = $arrTeam;

            $GLOBALS['TL_CSS']['swiper'] = 'bundles/esalesmediacontaoswiper/css/swiper-custom.css';
            $GLOBALS['TL_JAVASCRIPT']['swiper'] = 'bundles/esalesmediacontaoswiper/js/lib/swiper/6.5.0/swiper-bundle.min.js'; // load swiper
        }

        return $template->getResponse();
    }
}
