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

use Chill\BudgetBundle\Calculator\CalculatorManager;
use Chill\BudgetBundle\Repository\ChargeRepository;
use Chill\BudgetBundle\Repository\ResourceRepository;
use Chill\BudgetBundle\Security\Authorization\BudgetElementVoter;
use Chill\PersonBundle\Entity\Household\Household;
use Chill\PersonBundle\Entity\Person;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class ElementController extends AbstractController
{
    public function __construct(private readonly CalculatorManager $calculator, private readonly ResourceRepository $resourceRepository, private readonly ChargeRepository $chargeRepository) {}

    #[\Symfony\Component\Routing\Annotation\Route(path: '{_locale}/budget/elements/by-person/{id}', name: 'chill_budget_elements_index')]
    public function indexAction(Person $person)
    {
        $this->denyAccessUnlessGranted(BudgetElementVoter::SEE, $person);

        $charges = $this->chargeRepository->findAllByEntity($person);
        $resources = $this->resourceRepository->findAllByEntity($person);

        $elements = \array_merge($charges, $resources);

        if (\count($elements) > 0) {
            $results = $this->calculator->calculateDefault($elements);
        }

        return $this->render('@ChillBudget/Person/index.html.twig', [
            'person' => $person,
            'charges' => $charges,
            'resources' => $resources,
            'results' => $results ?? [],
        ]);
    }

    #[\Symfony\Component\Routing\Annotation\Route(path: '{_locale}/budget/elements/by-household/{id}', name: 'chill_budget_elements_household_index')]
    public function indexHouseholdAction(Household $household)
    {
        $this->denyAccessUnlessGranted(BudgetElementVoter::SEE, $household);

        $charges = $this->chargeRepository->findAllByEntity($household);
        $resources = $this->resourceRepository->findAllByEntity($household);

        $elements = \array_merge($charges, $resources);

        if (\count($elements) > 0) {
            $results = $this->calculator->calculateDefault($elements);
        }

        return $this->render('@ChillBudget/Household/index.html.twig', [
            'household' => $household,
            'charges' => $charges,
            'resources' => $resources,
            'results' => $results ?? [],
        ]);
    }
}
