<?php

namespace RxConnexionBundle\Form;

use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\ORM\EntityRepository;
use RxConnexionBundle\Entity\ChartTypeEntity;
use RxConnexionBundle\Entity\MarketingStaffScheduleStatusEntity;
use RxConnexionBundle\Entity\PatientNoteEntity;
use RxConnexionBundle\Entity\ProviderEntity;
use RxConnexionBundle\Entity\ScheduleEntity;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
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;

class MarketingStaffScheduleForCalendarForm extends AbstractType
{
    private $manager;

    public function __construct(ObjectManager $manager) {
        $this->manager = $manager;
    }
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('action', HiddenType::class, array(
                'mapped' => false,
                'attr' => array(
                    'class' => 'form-action'
                )
            ))
            ->add('marketingStaff', HiddenType::class, array(
                'attr' => array(
                    'value' => $options['marketingStaff_id']
                )
            ))
            ->add('health_facility', HiddenType::class, array(
                'attr' => array(
                    'value' => $options['healthFacility_id']
                )
            ))
            ->add('patient_city_id', HiddenType::class, array(
                'mapped' => false
            ))
            ->add('start_time', HiddenType::class, array(
                'attr' => array(
                    'value' => $options['startTime']
                )

            ))
            /*->add('start_time_period', HiddenType::class, array(

            ))*/
            ->add('start_time_minute', HiddenType::class, array(
                'attr' => array(
                    'value' => $options['startTimeMin']
                )
            ))
            ->add('start_time_hour', HiddenType::class, array(
                'attr' => array(
                    'value' => $options['startTimeHour']
                )
            ))
            ->add('id', HiddenType::class)
            ->add('note', TextareaType::class, array(
                'label' => 'Notes',
                'label_attr' => array(
                    'class' => 'required middle'
                ),
                'required' => true,
                'attr' => array(
                    'rows' => 5
                ),
                'data' => null
            ))
            ->add('end_time_period', ChoiceType::class, array(
                'required' => true,
                'choices' => array(
                    ScheduleEntity::END_TIME_PERIOD_AM => 'AM',
                    ScheduleEntity::END_TIME_PERIOD_PM => 'PM'
                ),
                'data' => $options['startTimeHour'] == 11 && ($options['startTimeMin'] >= 30) ? 'PM' : $options['startTimePeriod']
            ))
            /*->add('chart_type', EntityType::class, array(
                'class' => ChartTypeEntity::class,
                'choice_label' => 'description',
                'query_builder' => function(EntityRepository $er) {

                    return $er->createQueryBuilder('ct')
                        ->where('ct.isActive = 1')
                        ->orderBy('ct.description', 'ASC');
                },
                'label' => 'Chart Type',
                'label_attr' => array(
                    'class' => 'required'
                ),
                'required' => false
            ))*/
            ->add('start_time_hour', ChoiceType::class, array(
                'required' => true,
                'choices' => $this->generateHoursArray(),
                'data' => $options['startTimeHour']
            ))
            ->add('start_time_minute', ChoiceType::class, array(
                'required' => true,
                'choices' => $this->generateMinutesArray(),
                'data' => $options['startTimeMin']
            ))
            ->add('start_time_period', ChoiceType::class, array(
                'required' => true,
                'choices' => array(
                    ScheduleEntity::START_TIME_PERIOD_AM => 'AM',
                    ScheduleEntity::START_TIME_PERIOD_PM => 'PM'
                ),
                'data' => $options['startTimePeriod']
            ))
            ->add('marketingStaffScheduleStatus', EntityType::class, array(
                'class' => MarketingStaffScheduleStatusEntity::class,
                'choice_label' => 'description',
                'query_builder' => function(EntityRepository $er) use ($options) {

                    return $er->createQueryBuilder('ss')
                        ->where('ss.isActive = 1')
                        ->orderBy('ss.description', 'ASC');
                },
                'label' => 'Appointment Status',
                'label_attr' => array(
                    'class' => 'required'
                ),
                'required' => true
            ))
            ->add('note_type', ChoiceType::class, array(
                'label' => 'Note Type',
                'required' => false,
                'choices' => array(
                    PatientNoteEntity::TYPE_CLINICAL => 'Clinical',
                    PatientNoteEntity::TYPE_BILLING => 'Billing',
                    PatientNoteEntity::TYPE_APPOINTMENT => 'Appointment',
                    PatientNoteEntity::TYPE_TEMPLATE => 'Template',
                ),
                'mapped' => false
            ))
            ->add('contactPerson', TextType::class, array(
                'label' => 'Contact Person',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false
            ))
            ->add('referringProvider', HiddenType::class)
            ->add('referringHealthFacility', HiddenType::class)
            ->add('chartType', HiddenType::class)
            ->add('noteTemplate', HiddenType::class)
            ->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) use ($options) {

                $form = $event->getForm();
                $data = $event->getData();
                $referringProvider = $data->getReferringProvider();
                $referringHealthFacility = $data->getReferringHealthFacility();
                $marketingStaff = $data->getMarketingStaff();
                $healthFacility = $data->getHealthFacility();
                $chartType = $data->getChartType();
                $noteTemplate = $data->getNoteTemplate();
                $form
                    ->add('referringProvider_fullName', TextType::class, array(
                        'label' => 'Referring Physician',
                        'label_attr' => array(
                            'class' => 'middle'
                        ),
                        'required' => false,
                        'mapped' => false,
                        'data' => $referringProvider ? $referringProvider->getFullName() : ''
                    ))
                    ->add('referringHealthFacility_desc', TextType::class, array(
                        'label' => 'Referring Affiliate',
                        'label_attr' => array(
                            'class' => 'middle'
                        ),
                        'required' => false,
                        'mapped' => false,
                        'data' => $referringHealthFacility ? $referringHealthFacility->getDescription() : ''
                    ))
                    ->add('marketingStaff_fullName', TextType::class, array(
                        'label' => 'Marketing Staff',
                        'label_attr' => array(
                            'class' => 'required middle'
                        ),
                        'required' => true,
                        'mapped' => false,
                        'data' => $marketingStaff ? $marketingStaff->getFullName() : $options['marketingStaffFullName']
                    ))
                    ->add('chartType_desc', TextType::class, array(
                        'label' => 'Type',
                        'label_attr' => array(
                            'class' => 'required middle'
                        ),
                        'required' => true,
                        'mapped' => false,
                        'data' => $chartType ? $chartType->getDescription() : ''
                    ))
                    ->add('health_facility_desc', TextType::class, array(
                        'label' => 'Branch',
                        'label_attr' => array(
                            'class' => 'required middle'
                        ),
                        'required' => true,
                        'mapped' => false,
                        'data' => $healthFacility ? $healthFacility->getDescription() :  $options['healthFacilityName']
                    ))
                    ->add('schedule_date', TextType::class, array(
                        'label' => 'Appt. Date',
                        'label_attr' => array(
                            'class' => 'required middle'
                        ),
                        'required' => true,
                        'attr' => array(
                            'class' => 'date'
                        ),
                        'data' =>  $data->getScheduleDateAsString() ? $data->getScheduleDateAsString() : $options['schedDate']
                    ))
                    ->add('note_template_description', TextType::class, array(
                        'mapped' => false,
                        'label' => 'Note Template',
                        'label_attr' => array(
                            'class' => 'middle'
                        ),
                        'required' => false,
                        'attr' => array(
                            'class' => 'hide'
                        ),
                        'data' => $noteTemplate ? $noteTemplate->getDescription() : ''
                    ))
                    ->add('referringHealthFacility_geoLat', HiddenType::class, array(
                        'attr' => array(
                            'value' => $referringHealthFacility ? $referringHealthFacility->getGeoLat() : ''
                        ),
                        'mapped' => false
                    ))
                    ->add('referringHealthFacility_geoLong', HiddenType::class, array(
                        'attr' => array(
                            'value' => $referringHealthFacility ? $referringHealthFacility->getGeoLong() : ''
                        ),
                        'mapped' => false
                    ))
                    ->add('referringProvider_geoLat', HiddenType::class, array(
                        'attr' => array(
                            'value' => $referringProvider ? $referringProvider->getGeoLat() : ''
                        ),
                        'mapped' => false
                    ))
                    ->add('referringProvider_geoLong', HiddenType::class, array(
                        'attr' => array(
                            'value' => $referringProvider ? $referringProvider->getGeoLong() : ''
                        ),
                        'mapped' => false
                    ))
                    ->add('health_facility_city_id', HiddenType::class, array(
                        'attr' => array(
                            'value' => $healthFacility ? $healthFacility->getId() : $options['healthFacility_city_id']
                        ),
                        'mapped' => false
                    ))
                    ->add('health_facility_geoLat', HiddenType::class, array(
                        'attr' => array(
                            'value' => $healthFacility ? $healthFacility->getGeoLatitude() : $options['healthFacility_geoLat']
                        ),
                        'mapped' => false
                    ))
                    ->add('health_facility_geoLong', HiddenType::class, array(
                        'attr' => array(
                            'value' => $healthFacility ? $healthFacility->getGeoLongitude() : $options['healthFacility_geoLong']
                        ),
                        'mapped' => false
                    ));
            });
            if($options['action'] == 'n'){
                if($options['startTimeMin'] === '30'){
                    $builder
                        ->add('end_time_hour', ChoiceType::class, array(
                            'required' => true,
                            'choices' => $this->generateHoursArray(),
                            'data' => $options['startTimeHour'] + 1
                        ))
                        ->add('end_time_minute', ChoiceType::class, array(
                            'required' => true,
                            'choices' => $this->generateMinutesArray(),
                            'data' => '00'
                        ));
                }elseif($options['startTimeMin'] === '45'){
                    $builder
                        ->add('end_time_hour', ChoiceType::class, array(
                            'required' => true,
                            'choices' => $this->generateHoursArray(),
                            'data' => $options['startTimeHour'] + 1
                        ))
                        ->add('end_time_minute', ChoiceType::class, array(
                            'required' => true,
                            'choices' => $this->generateMinutesArray(),
                            'data' => '15'
                        ));
                }else{
                    $builder
                        ->add('end_time_hour', ChoiceType::class, array(
                            'required' => true,
                            'choices' => $this->generateHoursArray(),
                            'data' => $options['startTimeHour']
                        ))
                        ->add('end_time_minute', ChoiceType::class, array(
                            'required' => true,
                            'choices' => $this->generateMinutesArray(),
                            'data' => $options['startTimeMin'] + 30
                        ));
                }
            }else{
                $builder
                    ->add('end_time_hour', ChoiceType::class, array(
                        'required' => true,
                        'choices' => $this->generateHoursArray()
                    ))
                    ->add('end_time_minute', ChoiceType::class, array(
                        'required' => true,
                        'choices' => $this->generateMinutesArray()
                    ));
            }

        $builder->get('health_facility')->addModelTransformer(new DataTransformer($this->manager, 'RxConnexionBundle:HealthFacilityEntity', false));
        $builder->get('referringHealthFacility')->addModelTransformer(new DataTransformer($this->manager, 'RxConnexionBundle:ReferringHealthFacilityEntity', false));
        $builder->get('referringProvider')->addModelTransformer(new DataTransformer($this->manager, 'RxConnexionBundle:ReferringProviderEntity', false));
        $builder->get('marketingStaff')->addModelTransformer(new DataTransformer($this->manager, 'RxConnexionBundle:MarketingStaffEntity', false));
        $builder->get('chartType')->addModelTransformer(new DataTransformer($this->manager, 'RxConnexionBundle:ChartTypeEntity', false));
    }

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

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' 	  => 'RxConnexionBundle\Entity\MarketingStaffScheduleEntity',
            'csrf_protection' => true,
            'csrf_field_name' => '_token',
            // a unique key to help generate the secret token
            'intention'       => 'scheduleEntity_intention',
            'action'          => 'n',
            'healthFacility_id' => null,
            'marketingStaff_id'     => null,
            'schedDate'       => null,
            'startTime'       => null,
            'startTimeHour'       => null,
            'startTimeMin'       => null,
            'startTimePeriod'       => null,
            'marketingStaffFullName'    => null,
            'healthFacilityName'  => null,
            'healthFacility_city_id' => null,
            'healthFacility_geoLat' => null,
            'healthFacility_geoLong' => null

        ));
    }

    private function generateHoursArray() {

        $hoursArray = array();

        for($i=1; $i<=12; $i++) {
            $hoursArray[sprintf('%002d', $i)] = $i;
        }
        return $hoursArray;

    }

    private function generateMinutesArray() {

        $minutesArray = array();

        for($i=0; $i<=55; $i+=5) {
            $minutesArray[sprintf('%002d', $i)] = $i;
        }

        return $minutesArray;
    }

}