<?php

declare(strict_types=1);

namespace vonRotenberg\CoretoolsBundle\Controller\ContentElement;

use Contao\ContentModel;
use Contao\Controller;
use Contao\CoreBundle\Controller\ContentElement\AbstractContentElementController;
use Contao\CoreBundle\DependencyInjection\Attribute\AsContentElement;
use Contao\CoreBundle\Twig\FragmentTemplate;
use Contao\FilesModel;
use Contao\System;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

#[AsContentElement(category: 'miscellaneous', nestedFragments: true)]
class GridPlacementWrapperController extends AbstractContentElementController
{
    protected function getResponse(FragmentTemplate $template, ContentModel $model, Request $request): Response
    {
        Controller::loadDataContainer($model->getTable());
        $intDesktopColCount = $GLOBALS['TL_DCA'][$model->getTable()]['fields']['vr_gpw_grid']['eval']['cols'] ?? 12;
        $intTabletColCount = $GLOBALS['TL_DCA'][$model->getTable()]['fields']['vr_gpw_tablet_grid']['eval']['cols'] ?? 12;
        $intMobileColCount = $GLOBALS['TL_DCA'][$model->getTable()]['fields']['vr_gpw_mobile_grid']['eval']['cols'] ?? 12;

        if (System::getContainer()->get('contao.routing.scope_matcher')->isFrontendRequest($request))
        {
            $GLOBALS['TL_CSS'][] = 'bundles/vonrotenbergcoretools/css/grid-placement-wrapper.min.css|static';
        }

        // Sicherstellen, dass alle notwendigen Felder vorhanden sind
        // Desktop Grid
        $arrGridCells = $model->vr_gpw_grid ? json_decode($model->vr_gpw_grid) : [];
        $intCellStart = !empty($arrGridCells) ? min($arrGridCells) : $intDesktopColCount;
        $intCellEnd = !empty($arrGridCells) ? max($arrGridCells) : $intDesktopColCount;

        // Tablet Grid
        $arrTabletGridCells = $model->vr_gpw_tablet_grid ? json_decode($model->vr_gpw_tablet_grid) : [];
        $intTabletCellStart = !empty($arrTabletGridCells) ? min($arrTabletGridCells) : $intTabletColCount;
        $intTabletCellEnd = !empty($arrTabletGridCells) ? max($arrTabletGridCells) : $intTabletColCount;

        // Mobile Grid
        $arrMobileGridCells = $model->vr_gpw_mobile_grid ? json_decode($model->vr_gpw_mobile_grid) : [];
        $intMobileCellStart = !empty($arrMobileGridCells) ? min($arrMobileGridCells) : $intMobileColCount;
        $intMobileCellEnd = !empty($arrMobileGridCells) ? max($arrMobileGridCells) : $intMobileColCount;


        // Vorbereiten der Daten, inklusive der neuen Tablet- und Mobile-Klassen
        $arrData = array_merge($template->getData(), [
            'colStart' => $this->getColumnNumber(12, $intCellStart),
            'colEnd' => $this->getColumnNumber(12, $intCellEnd),
            'rowStart' => $this->getRowNumber(12, $intCellStart),
            'rowEnd' => $this->getRowNumber(12, $intCellEnd),
            'grid_classes' => $this->getGridClasses(12, $intCellStart, $intCellEnd), // Desktop-Klassen

            // Spezifische Grid-Klassen für Tablet und Mobile
            'grid_tablet_classes' => count($arrTabletGridCells) ? $this->getGridClasses(12, $intTabletCellStart, $intTabletCellEnd, 'tablet') : '',
            'grid_mobile_classes' => count($arrMobileGridCells) ? $this->getGridClasses(12, $intMobileCellStart, $intMobileCellEnd, 'mobil') : '',
        ]);

        $template->setData($arrData);
        return $template->getResponse();
    }


    private function getColumnNumber(int $columns, int $cellIndex): int
    {
        if ($columns <= 0)
        {
            throw new \InvalidArgumentException('The number of columns must be greater than zero.');
        }

        return ($cellIndex % $columns) + 1;
    }


    private function getRowNumber(int $columns, int $cellIndex): int
    {
        if ($columns <= 0)
        {
            throw new \InvalidArgumentException('The number of columns must be greater than zero.');
        }

        return intdiv($cellIndex, $columns) + 1;
    }

    private function getGridClasses(int $columns, int $intCellStart, int $intCellEnd, string $strViewportName = ''): string
    {
        // Berechnung der Start-/Endspalten
        $colStart = $this->getColumnNumber($columns, $intCellStart);
        $colEnd = $this->getColumnNumber($columns, $intCellEnd);

        // Berechnung der Start-/Endreihen
        $rowStart = $this->getRowNumber($columns, $intCellStart);
        $rowEnd = $this->getRowNumber($columns, $intCellEnd);

        // Generierung der CSS-Klassennamen
        if (!empty($strViewportName))
        {
            $strViewportName = '-' . $strViewportName;
        }
        $cssClasses = [
            "gp--col$strViewportName-start-$colStart",
            "gp--col$strViewportName-end-" . ($colEnd + 1),    // col-end benötigt +1 gemäß Ihrer CSS-Definition
            "gp--row$strViewportName-start-$rowStart",
            "gp--row$strViewportName-end-" . ($rowEnd + 1),   // row-end benötigt ebenfalls +1
        ];

        // Klassennamen als String trennen
        return implode(' ', $cssClasses);
    }
}