<?php

namespace RxConnexionBundle\Form;

use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use RxConnexionBundle\Form\DataTransformer\DataTransformer;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;

use RxConnexionBundle\Entity\PatientRentalEntity;
use RxConnexionBundle\Form\Type\PatientBillingBreakdownForm;

class PatientRentalForm 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'
                ),
                'data' => $options['action']
            ))
            ->add('patient', HiddenType::class, array(
                'attr' => array(
                    'value' => $options['patient_id']
                )
            ))
            ->add('id', HiddenType::class)
            ->add('amount_due', HiddenType::class)
            ->add('patientInsurance', HiddenType::class)
            ->add('invoice_no', TextType::class, array(
                'label' => 'Invoice No.',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'attr' => array(
                    'class' => 'disabled',
                    'disabled' => 'true',
                ),
                'required' => false,
            ))
            ->add('serial_no', TextType::class, array(
                'label' => 'Serial No.',
                'label_attr' => array(
                    'class' => 'middle'
                ),
                'required' => false,
            ))
            ->add('note', TextareaType::class, array(
                'label' => 'Notes',
                'required' => false,
                'attr' => array(
                    'rows' => 3,
                ),
                'data' => null
            ))
            ->add('patientBillingBreakdowns', CollectionType::class, array(
                'entry_type' => PatientBillingBreakdownForm::class,
                'allow_add' => true,
                'allow_delete' => true,
                'prototype' => false,
                'by_reference' => false
            ))
            ->add('payer_type', ChoiceType::class, array(
                'label' => 'Payer Type',
                'label_attr' => array(
                    'class' => 'required middle'
                ),
                'choices' => array(
                    PatientRentalEntity::PAYER_TYPE_SELF_PAY => 'Self Pay',
                    PatientRentalEntity::PAYER_TYPE_INSURANCE => 'Insurance',
                    PatientRentalEntity::PAYER_TYPE_FINANCING => 'Financing',
                ),
                'choice_attr' => function($val, $key, $index) {
                    return [
                        'class' => 'payer_type_choice_'.strtolower($key),
                    ];
                },
            ))
            ->add('payment_day', ChoiceType::class, array(
                'label' => 'Payment Day',
                'label_attr' => array(
                    'class' => 'required middle'
                ),
                'choices' => $this->generateDaysArray(),
                'required' => false,
                'attr' => array(
                    'class' => ''
                )
            ))
            ->add('amortization_amount', TextType::class, array(
                'label' => 'Amortization Amount',
                'label_attr' => array(
                    'class' => 'required middle'
                ),
                'required' => false,
                'attr' => array(
                    'class' => ''
                ),
            ))
            ->add('healthFacility', HiddenType::class, array(
                'attr' => array(
                    'value' => $options['defaultHealthFacility_id']
                )
            ))
            ->add('healthFacilityRentalForAddress', HiddenType::class)
            ->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) use($options) {

                $form = $event->getForm();
                $data = $event->getData();
                $patientInsurance = $data ? $data->getPatientInsurance() : null;
                $patient = $data ? $data->getPatient() : null;
                $healthFacility = $data ? $data->getHealthFacility() : null;
                $healthFacilityRentalForAddress = $data ? $data->getHealthFacilityRentalForAddress() : null;


                $form
                    ->add('start_date', TextType::class, array(
                        'label' => 'Start Date',
                        'label_attr' => array(
                            'class' => 'required middle'
                        ),
                        'required' => true,
                        'attr' => array(
                            'class' => 'date',
                            //'readonly' => $options['action'] == 'u' ? true : false
                        ),
                        'data' => $data && $data->getStartDateAsString() != '' ? $data->getStartDateAsString() : date('m/d/Y')
                    ))
                    ->add('end_date', TextType::class, array(
                        'label' => 'End Date',
                        'label_attr' => array(
                            'class' => 'middle'
                        ),
                        'required' => false,
                        'attr' => array(
                            'class' => 'date',
                            //'readonly' => $options['action'] == 'u' ? true : false
                        ),
                        'data' => $data && $data->getEndDateAsString() != '' ? $data->getEndDateAsString() : date('m/d/Y')
                    ))
                    ->add('patientInsurance_insurance_description', TextType::class, array(
                        'mapped' => false,
                        'label' => 'Insurance',
                        'label_attr' => array(
                            'class' => 'middle'
                        ),
                        'attr' => array(
                            //'readonly' => $options['action'] == 'u' ? true : false
                        ),
                        'data' => $patientInsurance ? $patientInsurance->getInsurance()->getDescription() : ''
                    ))
                    ->add('patient_fullName', TextType::class, array(
                        'mapped' => false,
                        'label' => 'Patient',
                        'label_attr' => array(
                            'class' => 'middle'
                        ),
                        'attr' => array(
                            'class' => ($patient && $patient->getFullName() == 'Mismatched Invoice')  ? '' : 'hide'
                        ),
                        'data' => $patient ? $patient->getFullName() : ''
                    ))
                    ->add('healthFacility_desc', TextType::class, array(
                        'mapped' => false,
                        'label' => 'Billing Branch',
                        'label_attr' => array(
                            'class' => 'middle'
                        ),
                        /*'attr' => array(
                            'readonly' => $options['action'] == 'u' ? true : false
                        ),*/
                        'data' => $healthFacility ? $healthFacility->getDescription() : $options['defaultHealthFacility']
                    ))
                    ->add('healthFacilityRentalForAddress_desc', TextType::class, array(
                        'mapped' => false,
                        'label' => 'Billing Address',
                        'label_attr' => array(
                            'class' => 'middle'
                        ),
                        /*'attr' => array(
                            'readonly' => $options['action'] == 'u' ? true : false
                        ),*/
                        'data' => $healthFacilityRentalForAddress ? $healthFacilityRentalForAddress->getDescription() : ''
                    ));
            });

        $builder->get('patient')->addModelTransformer(new DataTransformer($this->manager, 'RxConnexionBundle:PatientEntity', true));
        $builder->get('patientInsurance')->addModelTransformer(new DataTransformer($this->manager, 'RxConnexionBundle:PatientInsuranceEntity', false));
        $builder->get('healthFacility')->addModelTransformer(new DataTransformer($this->manager, 'RxConnexionBundle:HealthFacilityEntity', false));
        $builder->get('healthFacilityRentalForAddress')->addModelTransformer(new DataTransformer($this->manager, 'RxConnexionBundle:HealthFacilityEntity', false));
    }

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

    private function generateDaysArray() {

        $arr = array();

        for($i=1; $i<=31; $i++) {
            $arr[$this->ordinal($i)] = $i;
        }

        return $arr;
    }

    private function ordinal($number) {
        $ends = array('th','st','nd','rd','th','th','th','th','th','th');
        if ((($number % 100) >= 11) && (($number%100) <= 13))
            return $number. 'th';
        else
            return $number. $ends[$number % 10];
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' 	  => 'RxConnexionBundle\Entity\PatientRentalEntity',
            'csrf_protection' => true,
            'csrf_field_name' => '_token',
            // a unique key to help generate the secret token
            'intention'       => 'patientRentalEntity_intention',
            'action'          => 'n',
            'patient_id'      => null,
            'defaultHealthFacility_id' => null,
            'defaultHealthFacility' => null,
        ));
    }
}