<?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\PatientBillingEntity;

class PatientBillingRefundForm 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('id', HiddenType::class)
            ->add('amount', TextType::class, array(
                'label' => 'Amount',
                'label_attr' => array(
                    'class' => 'middle required'
                ),
                'attr' => array(
                  'class' => 'amount amt-text-align',
                ),
                'required' => true
            ))
            ->add('note', TextareaType::class, array(
                'label' => 'Notes',
                'required' => false,
                'attr' => array(
                    'rows' => 3
                )
            ))
            ->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')
                            ->leftJoin('pb.patientPayments', 'pp')
                            ->where('pb.patient = :patient')
                            ->andWhere('pb.isDeleted = 0')
                            ->andWhere('pb.billingStatus != :void')
                            ->andWhere('pb.billingStatus != :returned')
                            ->andWhere('pb.billingStatus != :refunded')
//                            ->andWhere('pb.amountBalance <= 0')
                            ->andWhere('pp.id IS NOT NULL')
                            ->orderBy('pb.billingDate', 'DESC')
                            ->setParameter('patient', base64_decode($options['patient_id']))
                            ->setParameter('void', PatientBillingEntity::BILLING_STATUS_VOID)
                            ->setParameter('returned', PatientBillingEntity::BILLING_STATUS_RETURNED)
                            ->setParameter('refunded', PatientBillingEntity::BILLING_STATUS_REFUND);
                    } 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('refund_date', TextType::class, array(
                        'label' => 'Refund Date',
                        'label_attr' => array(
                            'class' => 'required middle'
                        ),
                        'required' => true,
                        'attr' => array(
                            'class' => 'date',
                            'placeholder' => 'MM/DD/YYYY'
                        ),
                        'data' => $data && $data->getRefundDateAsString() != '' ? $data->getRefundDateAsString() : date('m/d/Y')
                    ));
            });

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

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

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' 	  => 'RxConnexionBundle\Entity\PatientBillingRefundEntity',
            'csrf_protection' => true,
            'csrf_field_name' => '_token',
            // a unique key to help generate the secret token
            'intention'       => 'patientBillingRefundEntity_intention',
            'action'          => 'n',
            'patient_id'      => 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];
    }
}