<?php

namespace App\Form\Type;

use App\Entity\GlobalParameter;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Constraints\GreaterThanOrEqual;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

/**
 * Represent a flux form type with check on number of tickets
 * Amount must be modulo the smallest existing ticket
 * Examples :
 * - You cannot transfer 3 value of MLC if minimum ticket is 2.
 */
class TicketFormType extends FluxFormType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('montant', NumberType::class, [
                'label' => 'Montant :',
                'required' => true,
                'constraints' => [
                    new GreaterThanOrEqual([
                        'message' => 'Montant inférieur à zéro !',
                        'value' => 0,
                    ]),
                    new Callback([$this, 'validateTicket']),
                ],
            ])
        ;
    }

    public function validateTicket($value, ExecutionContextInterface $context)
    {
        $allTickets = explode(',', $this->em->getRepository(GlobalParameter::class)->val(GlobalParameter::ALL_TICKETS));
        $minTicket = min($allTickets);

        if (!(0 == fmod($value, $minTicket))) {
            $context
                ->buildViolation('Montant impossible, inférieur au billet le plus bas ou non divible par celui-ci !')
                ->addViolation()
            ;
        }
    }

    public function getParent()
    {
        return FluxFormType::class;
    }

    public function getBlockPrefix()
    {
        return 'formTicket';
    }
}
