<?php

namespace RxConnexionBundle\Form;

use Doctrine\Common\Persistence\ObjectManager;
use RxConnexionBundle\Entity\FinancingCompanyEntity;
use RxConnexionBundle\Entity\PatientBillingFinancingPaymentDetailEntity;
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\ChoiceType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Doctrine\ORM\EntityRepository;

use RxConnexionBundle\Entity\PatientPaymentEntity;
use RxConnexionBundle\Entity\PatientBillingEntity;

class PatientPaymentForm extends AbstractType
{
    private $manager;
    private $date;

    public function __construct(ObjectManager $manager) {
        $this->manager = $manager;
        $this->date = new \DateTime();
    }

    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('payment_status', HiddenType::class, array(
                'attr' => array(
                    'value' => $options['payment_status']
                )
            ))
            ->add('id', HiddenType::class)
            ->add('amount', TextType::class, array(
                'label' => 'Total Amount',
                'label_attr' => array(
                    'class' => 'text-right middle required'
                ),
                'attr' => array(
                    'class' => 'amount'
                ),
                'required' => true
            ))
            ->add('pay_type', ChoiceType::class, array(
                'label' => 'Payment Type',
                'label_attr' => array(
                    'class' => 'middle required'
                ),
                'required' => true,
                'choices' => array(
                    PatientPaymentEntity::PAY_TYPE_AMEX             => 'Amex',
                    PatientPaymentEntity::PAY_TYPE_CASH             => 'Cash',
                    PatientPaymentEntity::PAY_TYPE_CHEQUE           => 'Cheque',
                    PatientPaymentEntity::PAY_TYPE_CREDIT           => 'Credit',
                    PatientPaymentEntity::PAY_TYPE_DEBIT_CARD       => 'Debit Card',
                    PatientPaymentEntity::PAY_TYPE_DIRECT_DEPOSIT   => 'Direct Deposit',
                    PatientPaymentEntity::PAY_TYPE_MASTER_CARD      => 'Master Card',
                    PatientPaymentEntity::PAY_TYPE_OTHER            => 'Other',
                    PatientPaymentEntity::PAY_TYPE_VISA             => 'Visa',
                    PatientPaymentEntity::PAY_TYPE_FINANCING        => 'Financing',
                    PatientPaymentEntity::PAY_TYPE_WAIVER           => 'Waiver',
                )
            ))
            ->add('pay_type_for_print', ChoiceType::class, array(
                'label' => 'Payment Type (Print)',
                'label_attr' => array(
                    'class' => ' required'
                ),
                'required' => true,
                'choices' => array(
                    PatientPaymentEntity::PAY_TYPE_AMEX             => 'Amex',
                    PatientPaymentEntity::PAY_TYPE_CASH             => 'Cash',
                    PatientPaymentEntity::PAY_TYPE_CHEQUE           => 'Cheque',
                    PatientPaymentEntity::PAY_TYPE_CREDIT           => 'Credit',
                    PatientPaymentEntity::PAY_TYPE_DEBIT_CARD       => 'Debit Card',
                    PatientPaymentEntity::PAY_TYPE_DIRECT_DEPOSIT   => 'Direct Deposit',
                    PatientPaymentEntity::PAY_TYPE_MASTER_CARD      => 'Master Card',
                    PatientPaymentEntity::PAY_TYPE_OTHER            => 'Other',
                    PatientPaymentEntity::PAY_TYPE_VISA             => 'Visa',
                    PatientPaymentEntity::PAY_TYPE_FINANCING        => 'Financing',
                    PatientPaymentEntity::PAY_TYPE_WAIVER           => 'Waiver',
                )
            ))
            ->add('financingCompany', EntityType::class, array(
                'class'         => FinancingCompanyEntity::class,
                'choice_label'  => 'description',
                'query_builder' => function(EntityRepository $er) use ($options) {
                    return $er->createQueryBuilder('pb')
                        ->where('pb.isDeleted = 0');
                },
                'label'         => 'Financing Company',
                'label_attr'    => array(
                    'class' => 'required hide type-financing'
                ),
                'required'      => false,
                'attr' => array(
                    'class' => 'hide type-financing'
                )
            ))
            ->add('note', TextareaType::class, array(
                'label' => 'Notes',
                'required' => false,
                'attr' => array(
                    'rows' => 3
                )
            ))
            ->add('new_invoice_no_for_financing', TextType::class, array(
                'label' => 'Invoice No.',
                'label_attr' => array(
                    'class' => 'middle hide type-financing'
                ),
                'attr' => array(
                    'class' => ' hide type-financing disabled',
                    'disabled' => 'true'
                ),
                'required' => false,
            ))
            ->add('payment_plan_type', ChoiceType::class, array(
                'mapped' => false,
                'label' => 'Payment Type',
                'label_attr' => array(
                    'class' => 'middle required hide type-financing-payment-plan'
                ),
                'required' => true,
                'choices' => array(
                    ''                                                                                    => '',
                    PatientBillingFinancingPaymentDetailEntity::PAYMENT_PLAN_TYPE_RENT_TO_OWN             => 'Rent to Own',
                    PatientBillingFinancingPaymentDetailEntity::PAYMENT_PLAN_TYPE_LONG_TERM_RENTAL        => 'Long Term Rental',
                    PatientBillingFinancingPaymentDetailEntity::PAYMENT_PLAN_TYPE_WARRANTY                => 'Warranty',
                ),
                'attr' => array(
                    'class' => 'hide type-financing-payment-plan'
                )
            ))
            ->add('payment_day', ChoiceType::class, array(
                'mapped' => false,
                'label' => 'Payment Day',
                'label_attr' => array(
                    'class' => 'required middle hide type-financing-payment-plan'
                ),
                'choices' => $this->generateDaysArray(),
                'required' => false,
                'attr' => array(
                    'class' => 'hide type-financing-payment-plan'
                )
            ))
            ->add('start_date', TextType::class, array(
                'mapped' => false,
                'label' => 'Start Date',
                'label_attr' => array(
                    'class' => 'required middle hide type-financing-payment-plan'
                ),
                'required' => false,
                'attr' => array(
                    'class' => 'date hide type-financing-payment-plan'
                ),
            ))
            ->add('end_date', TextType::class, array(
                'mapped' => false,
                'label' => 'End Date',
                'label_attr' => array(
                    'class' => 'required middle hide type-financing-payment-plan'
                ),
                'required' => false,
                'attr' => array(
                    'class' => 'date hide type-financing-payment-plan'
                ),
            ))
            ->add('is_payment_plan', CheckboxType::class, array(
                'mapped' => false,
                'label' => 'Payment Plan',
                'label_attr' => array(
                    'class' => 'required hide type-financing'
                ),
                'required' => false,
                'attr' => array(
                    'class' => 'hide type-financing'
                ),
            ))
            ->add('amortization_amount', TextType::class, array(
                'mapped' => false,
                'label' => 'Amortization Amount',
                'label_attr' => array(
                    'class' => 'required hide type-financing-payment-plan'
                ),
                'required' => false,
                'attr' => array(
                    'class' => 'hide type-financing-payment-plan amount'
                ),
            ))
            ->add('patientBilling', EntityType::class, array(
                'class'         => PatientBillingEntity::class,
                'choice_label'  => 'invoiceNoAndBillingDateAndBalance',
                'query_builder' => function(EntityRepository $er) use ($options) {
                    if($options['action'] == 'n'){
                        return $er->createQueryBuilder('pb')
                            ->where('pb.patient = :patient')
                            ->andWhere('pb.isDeleted = 0')
                            ->andWhere('pb.billingStatus != :void')
                            ->andWhere('pb.billingStatus != :returned')
                            ->andWhere('pb.billingStatus != :refunded')
                            ->andWhere('pb.amountBalance != 0')
                            ->orderBy('pb.billingDate', 'DESC')
                            ->setParameter('patient', base64_decode($options['patient_id']))
                            ->setParameter('void', 'Void')
                            ->setParameter('returned', 'Returned')
                            ->setParameter('refunded', 'Refunded');
                    } else {
                        return $er->createQueryBuilder('pb')
                            ->where('pb.patient = :patient')
                            ->andWhere('pb.isDeleted = 0')
                            ->orderBy('pb.billingDate', 'DESC')
                            ->setParameter('patient', base64_decode($options['patient_id']));
                    }
                },
                'label'         => 'Invoice No.',
                'label_attr'    => array(
                    'class' => 'required middle'
                ),
                'required'      => false
            ))
            ->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) {

                $form = $event->getForm();
                $data = $event->getData();

                $form
                    ->add('pay_date', TextType::class, array(
                        'label' => 'Payment Date',
                        'label_attr' => array(
                            'class' => 'required middle'
                        ),
                        'required' => true,
                        'attr' => array(
                            'class' => 'date',
                            'placeholder' => 'MM/DD/YYYY'
                        ),
                        'data' => $data && $data->getPayDateAsString() != '' ? $data->getPayDateAsString() : date('m/d/Y')
                    ));
            });

        $builder->get('patient')->addModelTransformer(new DataTransformer($this->manager, 'RxConnexionBundle:PatientEntity', true));
    }

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

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


    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];
    }
}