<?php

namespace App\Form;

use App\Entity\Rank;
use App\Entity\SubGroup;
use App\Entity\User;
use App\Form\Type\PhoneType;
use App\Repository\RankRepository;
use App\Repository\SubGroupRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

class EmployeeType extends AbstractType
{
    private TranslatorInterface $translator;

    public function __construct(TranslatorInterface $translator)
    {
        $this->translator = $translator;
    }

    public function buildForm(FormBuilderInterface $builder, array $options): void
    {

        /**
         * @var User $User
         */
        $User = $builder->getData();
        $UserGroup = $User->getMainGroup();

        $builder
            ->add('phone', PhoneType::class)
            ->add('mainRank', EntityType::class, [
                'class' => Rank::class,
                'query_builder' => function (RankRepository $RankRepository) use ($UserGroup) {
                    return $RankRepository->createQueryBuilder('r')
                        ->where('r.mainGroup =' . $UserGroup->getId())
                        ->orderBy('r.power', 'DESC');
                },
                'choice_label' => 'name',
                'label' => 'form_label_rank',
                'placeholder' => $this->translator->trans('form_placeholder_group_and_rank'),
                'required' => false,
                'expanded' => true
            ])

            ->add('subGroups', EntityType::class, [
                'class' => SubGroup::class,
                'query_builder' => function (SubGroupRepository $SubGroupRepository) use ($UserGroup) {
                    return $SubGroupRepository->createQueryBuilder('sg')
                        ->where('sg.mainGroup =' . $UserGroup->getId())
                        ;
                },
                'choice_label' => 'name',
                'label' => 'form_label_subgroups',
                'required' => false,
                'multiple' => true,
                'expanded' => true
            ])

            ->add('submit', SubmitType::class, [
                'label' => 'form_button_submit',
                'attr' => ['class' => 'btn-primary'],
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => User::class,
        ]);
    }
}
