<?php

namespace RxConnexionBundle\Form;

use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\ORM\EntityRepository;
use RxConnexionBundle\Entity\FaxTranEntity;
use RxConnexionBundle\Entity\SourceEntity;
use RxConnexionBundle\Entity\ReferralEntity;
use RxConnexionBundle\Entity\ReferringHealthFacilityEntity;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use RxConnexionBundle\Form\DataTransformer\DataTransformer;
use RxConnexionBundle\Entity\ReferringProviderEntity;
use RxConnexionBundle\Entity\ServiceEntity;
use RxConnexionBundle\Form\Type\ReferralServicesForm;

class ReferralForm extends AbstractType
{
    private $faxTranId;
    private $manager;

    public function __construct(ObjectManager $manager) {
        $this->manager = $manager;
    }

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

        $this->faxTranId = $options['faxTranId'];

        $builder
            ->add('action', HiddenType::class, array(
                'mapped' => false,
                'attr' => array(
                    'class' => 'form-action'
                )
            ))
            ->add('id', HiddenType::class)
            ->add('first_name', TextType::class, array(
                'label' => 'First Name',
                'label_attr' => array(
                    'class' => 'required middle'
                ),
                'required' => true
            ))
            ->add('middle_name', TextType::class, array(
                'label' => 'Middle Name',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false
            ))
            ->add('last_name', TextType::class, array(
                'label' => 'Last Name',
                'label_attr' => array(
                    'class' => 'required middle'
                ),
                'required' => true
            ))
            ->add('street', TextType::class, array(
                'label' => 'Street',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false
            ))
            ->add('mobile_no', TextType::class, array(
                'label' => 'Mobile No(s).',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false
            ))
            ->add('mobile_no_two', TextType::class, array(
                'label' => 'Mobile No.',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false
            ))
            ->add('mobile_no_three', TextType::class, array(
                'label' => 'Mobile No.',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false
            ))
            ->add('phone_no', TextType::class, array(
                'label' => 'Phone No(s).',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false
            ))
            ->add('phone_no_two', TextType::class, array(
                'label' => 'Phone No.',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false
            ))
            ->add('phone_no_three', TextType::class, array(
                'label' => 'Phone No.',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false
            ))
            ->add('email', TextType::class, array(
                'label' => 'Email(s)',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false
            ))
            ->add('email_two', TextType::class, array(
                'label' => 'Email',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false
            ))
            ->add('email_three', TextType::class, array(
                'label' => 'Email',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false
            ))
            ->add('gender', ChoiceType::class, array(
                'label' => 'Gender',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false,
                'choices' => array(
                    '' => '',
                    ReferralEntity::GENDER_MALE => 'Male',
                    ReferralEntity::GENDER_FEMALE => 'Female',
                )
            ))
            ->add('note', TextareaType::class, array(
                'label' => 'Notes',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false,
                'attr' => array(
                    'rows' => 5
                )
            ))
            ->add('source', EntityType::class, array(
                'class' => SourceEntity::class,
                'choice_label' => 'description',
                'query_builder' => function(EntityRepository $er) use ($options) {

                    return $er->createQueryBuilder('cs')
                        ->orderBy('cs.description', 'ASC');
                },
                'label' => 'Source',
                'label_attr' => array(
                    'class' => 'required'
                ),
                'required' => true
            ))
            ->add('referredBy', HiddenType::class, array(
                'label' => 'Referred By',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'mapped' => false,
                'required' => false
            ))
            ->add('personal_health_no', TextType::class, array(
                'label' => 'PHN/AHN/ULI',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false
            ))
            ->add('city', HiddenType::class)
            ->add('referringHealthFacility', ReferringHealthFacilityForReferralForm::class, array(
                'data_class' => ReferringHealthFacilityEntity::class
            ))
            ->add('referringProvider', ReferringProviderForReferralForm::class, array(
                'data_class' => ReferringProviderEntity::class
            ))
            ->add('faxTran', FaxTranForReferralForm::class, array(
                'data_class' => FaxTranEntity::class
            ))
            ->add('faxTran_id', TextType::class, array(
                'label' => 'ID',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'mapped' => false,
                'required' => false,
                'data' => $options['faxTranId'],
                'attr' => array(
                    'readonly' => true
                )
            ))
            ->add('referralServices', CollectionType::class, array(
                'entry_type' => ReferralServicesForm::class,
                'allow_add' => true,
                'allow_delete' => true,
                'prototype' => false,
                'by_reference' => false,
                'required' => false,
                'delete_empty' => function($referralService = null){
                    return !$referralService->getService();
                }

            ))
            ->add('postalCode', HiddenType::class)
            ->add('healthFacility', HiddenType::class)
            ->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) {

                $form = $event->getForm();
                $data = $event->getData();
                $city = $data->getCity();
                $referringProvider = $data->getReferringProvider();
                $referringHealthFacility = $data->getReferringHealthFacility();
                $postalCode = $data->getPostalCode();
                $faxTran = $data->getFaxTran();
                $healthFacility = $data->getHealthFacility();


                $form
                    ->add('referringProvider_id', TextType::class, array(
                        'label' => 'ID',
                        'label_attr' => array(
                            'class' => 'middle'
                        ),
                        'mapped' => false,
                        'required' => false,
                        'data' => $referringProvider ? $referringProvider->getId() : '',
                        'attr' => array(
                            'readonly' => true
                        )
                    ))
                    ->add('referringHealthFacility_id', TextType::class, array(
                        'label' => 'ID',
                        'label_attr' => array(
                            'class' => 'middle'
                        ),
                        'mapped' => false,
                        'required' => false,
                        'data' => $referringHealthFacility ? $referringHealthFacility->getId() : '',
                        'attr' => array(
                            'readonly' => true
                        )
                    ))
                    ->add('healthFacility_desc', TextType::class, array(
                        'label' => 'Branch',
                        'label_attr' => array(
                            'class' => 'required middle'
                        ),
                        'mapped' => false,
                        'required' => true,
                        'data' => $healthFacility ? $healthFacility->getDescription() : ''
                    ))
                    ->add('fax_tran_id', TextType::class, array(
                        'label' => 'ID',
                        'label_attr' => array(
                            'class' => 'middle',
                        ),
                        'attr' => array(
                            'readonly' => true
                        ),
                        'mapped' => false,
                        'data' => $faxTran ? $faxTran->getId() : $this->faxTranId,
                        'required' => false
                    ))
                    ->add('fax_tran', HiddenType::class, array(
                        'mapped' => false,
                        'data' => $faxTran ? $faxTran->getId() : $this->faxTranId,
                    ))
                    /*->add('faxTran_id', TextType::class, array(
                        'label' => 'ID',
                        'label_attr' => array(
                            'class' => 'middle'
                        ),
                        'mapped' => false,
                        'required' => false,
                        'data' => $faxTran ? $faxTran->getId() : '',
                        'attr' => array(
                            'readonly' => true
                        )
                    ))*/
                    ->add('city_desc', TextType::class, array(
                        'label' => 'City',
                        'label_attr' => array(
                            'class' => 'required middle'
                        ),
                        'required' => true,
                        'mapped' => false,
                        'data' => $city ? $city->getDescription() : ''
                    ))
                    ->add('birth_date', TextType::class, array(
                        'label' => 'Birth Date',
                        'label_attr' => array(
                            'class' => 'required middle'
                        ),
                        'required' => true,
                        'attr' => array(
                            'class' => 'date'
                        ),
                        'data' => $data ? $data->getBirthDateAsString() : ''
                    ))
                    ->add('referral_date', TextType::class, array(
                        'label' => 'Referral Date',
                        'label_attr' => array(
                            'class' => 'required middle'
                        ),
                        'required' => true,
                        'attr' => array(
                            'class' => 'date',
                            'value' => $data->getReferralDateAsString() ? $data->getReferralDateAsString() : date("m/d/Y")
                        ),
                        'data' => $data ? $data->getReferralDateAsString() : ''
                    ))
                    ->add('receiveDate', TextType::class, array(
                        'label' => 'Received Date',
                        'label_attr' => array(
                            'class' => 'required middle'
                        ),
                        'required' => true,
                        'attr' => array(
                            'class' => 'date',
                            'value' => $data->getReceiveDateAsString() ? $data->getReceiveDateAsString() : date("m/d/Y")
                        ),
                        'data' => $data ? $data->getReceiveDateAsString() : ''
                    ))
                    ->add('postalCode_desc', TextType::class, array(
                        'label' => 'Postal Code',
                        'label_attr' => array(
                            'class' => 'required middle'
                        ),
                        'required' => true,
                        'mapped' => false,
                        'data' => $postalCode ? $postalCode->getDescription() : ''
                    ))
                    ->add('referredBy', HiddenType::class, array(
                        'mapped' => false,
                    ))
                    ->add('referredByPatient_fullName', TextType::class, array(
                        'label' => 'Referred By',
                        'label_attr' => array(
                            'class' => 'middle'
                        ),
                        'mapped' => false,
                        'required' => false,
                        'data' => '',
                    ));;
            })
            ->addEventListener(FormEvents::PRE_SUBMIT, function(FormEvent $event) {
                $form = $event->getForm();
                $data = $event->getData();
                if($data['referringProvider_id'] > 0){
                    $data['referringProvider'] = $data['referringProvider_id'];
                    $event->setData($data);
                    $form->remove('referringProvider');
                    $form->add('referringProvider', EntityType::class, array(
                        'class' => ReferringProviderEntity::class
                    ));
                }
                if($data['referringHealthFacility_id'] > 0){
                    $data['referringHealthFacility'] = $data['referringHealthFacility_id'];
                    $event->setData($data);
                    $form->remove('referringHealthFacility');
                    $form->add('referringHealthFacility', EntityType::class, array(
                        'class' => ReferringHealthFacilityEntity::class
                    ));
                }
//                if(isset($data['fax_tran'])){
                if($data['fax_tran'] > 0){
                    $data['faxTran'] = $data['fax_tran'];
                    $event->setData($data);
                    $form->remove('faxTran');
                    $form->add('faxTran', EntityType::class, array(
                        'class' => FaxTranEntity::class
                    ));
                }
//                }
            });

        $builder->get('city')->addModelTransformer(new DataTransformer($this->manager, 'RxConnexionBundle:CityEntity', false));
        $builder->get('postalCode')->addModelTransformer(new DataTransformer($this->manager, 'RxConnexionBundle:PostalCodeEntity', false));
        $builder->get('healthFacility')->addModelTransformer(new DataTransformer($this->manager, 'RxConnexionBundle:HealthFacilityEntity', false));
    }

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

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' 	  => 'RxConnexionBundle\Entity\ReferralEntity',
            'csrf_protection' => true,
            'csrf_field_name' => '_token',
            // a unique key to help generate the secret token
            'intention'       => 'referralEntity_intention',
            'action'          => 'n',
            'faxTranId'          => null,
            /*'faxTran'          => null,
            'remote_id' => null*/
        ));
    }
}