<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Controller;

use Chill\MainBundle\Pagination\PaginatorFactory;
use Chill\MainBundle\Timeline\TimelineBuilder;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;

class TimelineCenterController extends AbstractController
{
    public function __construct(protected TimelineBuilder $timelineBuilder, protected PaginatorFactory $paginatorFactory, private readonly Security $security) {}

    #[Route(path: '/{_locale}/center/timeline', name: 'chill_center_timeline', methods: ['GET'])]
    public function centerAction(Request $request)
    {
        // collect reachable center for each group
        $user = $this->security->getUser();
        $centers = [];

        foreach ($user->getGroupCenters() as $group) {
            $centers[] = $group->getCenter();
        }

        if (0 === \count($centers)) {
            throw $this->createNotFoundException();
        }

        $nbItems = $this->timelineBuilder->countItems(
            'center',
            ['centers' => $centers]
        );

        $paginator = $this->paginatorFactory->create($nbItems);

        return $this->render(
            '@ChillMain/Timeline/index.html.twig',
            [
                'timeline' => $this->timelineBuilder->getTimelineHTML(
                    'center',
                    ['centers' => $centers],
                    $paginator->getCurrentPage()->getFirstItemNumber(),
                    $paginator->getItemsPerPage()
                ),
                'nb_items' => $nbItems,
                'paginator' => $paginator,
            ]
        );
    }
}
