<?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\AsideActivityBundle\Controller;

use Chill\AsideActivityBundle\Entity\AsideActivity;
use Chill\AsideActivityBundle\Repository\AsideActivityCategoryRepository;
use Chill\MainBundle\CRUD\Controller\CRUDController;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Pagination\PaginatorInterface;
use Chill\MainBundle\Templating\Listing\FilterOrderHelper;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Security\Core\Security;

final class AsideActivityController extends CRUDController
{
    public function __construct(
        private readonly AsideActivityCategoryRepository $categoryRepository,
        private readonly Security $security,
    ) {}

    public function createEntity(string $action, Request $request): object
    {
        $user = $this->security->getUser();

        if (!$this->security->isGranted('ROLE_USER') || !$user instanceof User) {
            throw new AccessDeniedHttpException();
        }

        $asideActivity = new AsideActivity();

        $asideActivity->setAgent($user);
        $asideActivity->setLocation($user->getCurrentLocation());

        $duration = $request->query->get('duration', '300');
        $duration = \DateTime::createFromFormat('U', $duration);
        $asideActivity->setDuration($duration);

        $categoryId = $request->query->get('type', 7);

        if (null === $categoryId) {
            return $this->createNotFoundException('You must give a valid category id');
        }
        $category = $this->categoryRepository->find($categoryId);
        $asideActivity->setType($category);

        $note = $request->query->get('note', null);
        $asideActivity->setNote($note);

        return $asideActivity;
    }

    protected function buildQueryEntities(string $action, Request $request, ?FilterOrderHelper $filterOrder = null)
    {
        $qb = parent::buildQueryEntities($action, $request);

        if ('index' === $action) {
            $qb->where($qb->expr()->eq('e.agent', ':user'));
            $qb->orWhere($qb->expr()->eq('e.createdBy', ':user'));
            $qb->setParameter('user', $this->getUser());
        }

        return $qb;
    }

    protected function orderQuery(
        string $action,
        $query,
        Request $request,
        PaginatorInterface $paginator,
    ) {
        if ('index' === $action) {
            return $query->orderBy('e.date', 'DESC');
        }

        return parent::orderQuery($action, $query, $request, $paginator);
    }
}
