<?php

namespace RxConnexionBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use RxConnexionBundle\Entity\Base\BaseEntity;
use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToStringTransformer;
use Doctrine\ORM\Mapping\HasLifecycleCallbacks;
use JMS\Serializer\Annotation\Groups;
use JMS\Serializer\Annotation\MaxDepth;

/**
 * @ORM\Entity(repositoryClass="RxConnexionBundle\Repository\PatientRentalRepository")
 * @ORM\HasLifecycleCallbacks
 * @ORM\Table(name="patient_rental")
 */
class PatientRentalEntity extends BaseEntity
{
    const PAYER_TYPE_SELF_PAY = 'Self Pay';
    const PAYER_TYPE_INSURANCE = 'Insurance';
    const PAYER_TYPE_FINANCING = 'Financing';



    /**
     * @ORM\Column(name="invoice_no", type="integer", nullable=true)
     * @Groups("forAudit")
     */
    protected $invoiceNo;

    /**
     * @ORM\Column(name="serial_no", type="string", nullable=true)
     * @Groups("forAudit")
     */
    protected $serialNo;

    /**
     * @ORM\Column(name="start_date", type="datetime")
     * @Groups("forAudit")
     */
    protected $startDate;

    /**
     * @ORM\Column(name="end_date", type="datetime")
     * @Groups("forAudit")
     */
    protected $endDate;

    /**
     * @ORM\Column(name="payment_day", type="integer")
     */
    protected $paymentDay;

    /**
     * @ORM\Column(name="amount_due", type="decimal", precision=12, scale=2, nullable=true)
     * @Groups("forAudit")
     */
    protected $amountDue;

    /**
     * @ORM\Column(name="down_payment", type="decimal", precision=12, scale=2, nullable=true)
     * @Groups("forAudit")
     */
    protected $downPayment;

    /**
     * @ORM\Column(name="amortization_amount", type="decimal", precision=12, scale=2, nullable=true)
     * @Groups("forAudit")
     */
    protected $amortizationAmount;

    /**
     * @ORM\Column(name="amount_balance", type="decimal", precision=12, scale=2, nullable=true)
     * @Groups("forAudit")
     */
    protected $amountBalance;

    /**
     * @ORM\Column(name="payer_type", type="string", length=20, nullable=true)
     * @Groups("forAudit")
     */
    protected $payerType;

    /**
     * @ORM\Column(name="note", type="text", nullable=true)
     * @Groups("forAudit")
     */
    protected $note;

    /**
     * @ORM\Column(name="is_deleted", type="boolean")
     */
    protected $isDeleted;

    /**
     * @ORM\Column(name="is_payment_plan", type="boolean", nullable=true)
     */
    protected $isPaymentPlan;

    /**
     * @ORM\ManyToOne(targetEntity="PatientEntity", inversedBy="patientRentals")
     * @ORM\JoinColumn(name="patient_id", referencedColumnName="id")
     * @Groups("forAudit")
     * @MaxDepth(1)
     */
    protected $patient;

    /**
     * @ORM\ManyToOne(targetEntity="PatientInsuranceEntity", inversedBy="patientRentals")
     * @ORM\JoinColumn(name="patient_insurance_id", referencedColumnName="id")
     * @Groups("forAudit")
     * @MaxDepth(1)
     */
    protected $patientInsurance;

    /**
     * @ORM\ManyToOne(targetEntity="HealthFacilityEntity", inversedBy="patientRentals")
     * @ORM\JoinColumn(name="health_facility_id", referencedColumnName="id")
     * @Groups("forAudit")
     * @MaxDepth(1)
     */
    protected $healthFacility;

    /**
     * @ORM\ManyToOne(targetEntity="HealthFacilityEntity", inversedBy="addressForPatientRentals")
     * @ORM\JoinColumn(name="health_facility_for_address_id", referencedColumnName="id")
     * @Groups("forAudit")
     * @MaxDepth(1)
     */
    protected $healthFacilityRentalForAddress;

//    /**
//     * @ORM\OneToOne(targetEntity="PatientPaymentEntity", inversedBy="patientRentalFinancing")
//     * @ORM\JoinColumn(name="patient_payment_id_financing", referencedColumnName="id")
//     * @Groups("forAudit")
//     * @MaxDepth(1)
//     */
//    protected $patientPaymentFinancing;

    /**
     * @ORM\OneToMany(targetEntity="PatientBillingBreakdownEntity", mappedBy="patientRental", orphanRemoval=true, cascade={"persist", "remove"})
     * @Groups("forAudit")
     */
    protected $patientBillingBreakdowns;

    /**
     * @ORM\OneToMany(targetEntity="PatientPaymentEntity", mappedBy="patientRental")
     */
    protected $patientPayments;

//    /**
//     * @ORM\OneToOne(targetEntity="PatientBillingFinancingPaymentDetailEntity", mappedBy="patientBilling", cascade={"remove"})
//     */
//    protected $patientBillingFinancingPaymentDetail;

//    /**
//     * @ORM\OneToMany(targetEntity="PatientBillingRefundEntity", mappedBy="patientBilling")
//     */
//    protected $patientBillingRefunds;

    /**
     * Set createdAt
     *
     * @ORM\PrePersist
     */
    public function setCreatedAtValue()
    {
        parent::setCreatedAtValue();
        $this->isDeleted = 0;
        $this->updateBillingStatus();
    }

    /**
     * @ORM\PreFlush
     */
    public function preFlush() {
//        if(($this->billingStatus != self::BILLING_STATUS_VOID) && ($this->billingStatus != self::BILLING_STATUS_REFUND) && ($this->billingStatus != self::BILLING_STATUS_RETURNED)){
//            $this->updateBillingStatus();
//        }
    }

    public function __construct()
    {
        $this->patientBillingBreakdowns = new ArrayCollection();
        $this->patientPayments = new ArrayCollection();
    }

    /**
     * Update billingStatus
     */
    public function updateBillingStatus() {
//        $currentBillingStatus = $this->billingStatus;
//        $this->billingStatus = null;
//        $status = null;
//        if(count($this->getPatientBillingBreakdowns())){
//            if($this->amountBalance == 0){
//                $this->billingStatus = self::BILLING_STATUS_PAID;
//            }else{
//                if($currentBillingStatus === self::BILLING_STATUS_VOID){
//                    $this->billingStatus = self::BILLING_STATUS_VOID;
//                }elseif ($currentBillingStatus === self::BILLING_STATUS_RETURNED){
//                    $this->billingStatus = self::BILLING_STATUS_RETURNED;
//                }elseif ($currentBillingStatus === self::BILLING_STATUS_REFUND){
//                    $this->billingStatus = self::BILLING_STATUS_REFUND;
//                } else {
//                    $this->billingStatus = self::BILLING_STATUS_PENDING_PAYMENT;
//                }
//            }
//        }else{
//            if($this->getPatientPaymentFinancing()){
//                if($this->getPatientPaymentFinancing()->getPayType() === PatientPaymentEntity::PAY_TYPE_FINANCING){
//                    $this->billingStatus = self::BILLING_STATUS_PENDING_PAYMENT;
//                }else{
//                    $this->billingStatus = self::BILLING_STATUS_PENDING_BILLING;
//                }
//            }
//        }
    }

    /**
     * Update billingIfReturned
     */
    public function updateBillingIfReturned($id = null) {

        if($this->patientBillingBreakdowns->count()) {
            foreach ($this->patientBillingBreakdowns as $patientBillingBreakdown) {
                if($patientBillingBreakdown->getId() == $id) {
                    $this->amountDue = $this->getAmountDue() - $patientBillingBreakdown->getAmount();
                }
            }

//            $ctr = 0;
//            foreach ($this->patientBillingBreakdowns as $patientBillingBreakdown) {
//                if($patientBillingBreakdown->getId() == $id) {
//                  if($patientBillingBreakdown->getStatus() == 'Return') {
//                        if (1 == $ctr) {
//                            $this->billingStatus = self::BILLING_STATUS_RETURNED;
//                        }
//                    }
//                }
//                $ctr++;
//
//                var_dump($ctr);
//                die();
//            }
        }
    }


    /*--------------------------------------------------------------------------------------------------------*/
    /*					Use Defined Methods         														  */
    /*--------------------------------------------------------------------------------------------------------*/

    /**
     * @ORM\PrePersist
     * @ORM\PreUpdate
     */
    public function setAmountsValue() {

        /*if($this->payerType != PatientBillingEntity::PAYER_TYPE_FINANCING){*/
//            $this->amountPaid = 0;
//            $this->amountRefunded = 0;
//            if($this->patientPayments->count()) {
//                foreach($this->patientPayments as $patientPayment) {
//                    if($patientPayment->getPaymentStatus() != PatientPaymentEntity::PAYMENT_STATUS_VOID && $patientPayment->getIsDeleted() != 1 && $patientPayment->getPaymentStatus() != PatientPaymentEntity::PAYMENT_STATUS_PENDING){
//                        $this->amountPaid += $patientPayment->getAmount();
//                    }
//                }
//
//            }
//
//            if($this->patientBillingRefunds->count()) {
//                foreach($this->patientBillingRefunds as $patientBillingRefund) {
//                        $this->amountRefunded += $patientBillingRefund->getAmount();
//                }
//            }

        /*}*/
//        $this->amountBalance = ($this->amountDue - $this->amountPaid);
    }

    /*--------------------------------------------------------------------------------------------------------*/
    /*					Use Defined Setters and Getters														  */
    /*--------------------------------------------------------------------------------------------------------*/

    /**
     * get startDateAsString
     *
     * @return string
     */
    public function getStartDateAsString() {

        $dttst = new DateTimeToStringTransformer();

        return !empty($this->startDate) ? date('m/d/Y', strtotime($dttst->transform($this->startDate))) : '';
    }

    /**
     * get endDateAsString
     *
     * @return string
     */
    public function getEndDateAsString() {

        $dttst = new DateTimeToStringTransformer();

        return !empty($this->endDate) ? date('m/d/Y', strtotime($dttst->transform($this->endDate))) : '';
    }

    /**
     * Get invoiceNoAndBillingDateAndBalance
     *
     * @return string
     */
    public function getInvoiceNoAndBillingDateAndBalance() {

        return ($this->invoiceNo ? $this->invoiceNo : $this->prevSysInvoiceNo . '[ imported ]') . ' - ' . $this->getBillingDateAsString() . ' - ' . number_format($this->amountBalance, 2);
    }

    /**
     * get patientPaymentsNotVoid
     *
     * @return array
     */
    public function getPatientPaymentsNotVoid() {

        $arr = array();
        foreach($this->getPatientPayments() as $patientPayment){
            if($patientPayment->getPaymentStatus() !== PatientPaymentEntity::PAYMENT_STATUS_VOID){
                $arr[] = $patientPayment;
            }
        }

        return $arr;

    }


    /*--------------------------------------------------------------------------------------------------------*/
    /*					Setters and Getters																	  */
    /*--------------------------------------------------------------------------------------------------------*/


    /**
     * Set invoiceNo
     *
     * @param integer $invoiceNo
     *
     * @return PatientRentalEntity
     */
    public function setInvoiceNo($invoiceNo)
    {
        $this->invoiceNo = $invoiceNo;

        return $this;
    }

    /**
     * Get invoiceNo
     *
     * @return integer
     */
    public function getInvoiceNo()
    {
        return $this->invoiceNo;
    }

    /**
     * Set serialNo
     *
     * @param string $serialNo
     *
     * @return PatientRentalEntity
     */
    public function setSerialNo($serialNo)
    {
        $this->serialNo = $serialNo;

        return $this;
    }

    /**
     * Get serialNo
     *
     * @return string
     */
    public function getSerialNo()
    {
        return $this->serialNo;
    }

    /**
     * Set startDate
     *
     * @param \DateTime $startDate
     *
     * @return PatientRentalEntity
     */
    public function setStartDate($startDate)
    {
        $this->startDate = empty($startDate) ? NULL : new \DateTime($startDate);

        return $this;
    }

    /**
     * Get startDate
     *
     * @return \DateTime
     */
    public function getStartDate()
    {
        return $this->startDate;
    }

    /**
     * Set endDate
     *
     * @param \DateTime $endDate
     *
     * @return PatientRentalEntity
     */
    public function setEndDate($endDate)
    {
        $this->endDate = empty($endDate) ? NULL : new \DateTime($endDate);

        return $this;
    }

    /**
     * Get endDate
     *
     * @return \DateTime
     */
    public function getEndDate()
    {
        return $this->endDate;
    }

    /**
     * Set paymentDay
     *
     * @param integer $paymentDay
     *
     * @return PatientRentalEntity
     */
    public function setPaymentDay($paymentDay)
    {
        $this->paymentDay = $paymentDay;

        return $this;
    }

    /**
     * Get paymentDay
     *
     * @return integer
     */
    public function getPaymentDay()
    {
        return $this->paymentDay;
    }

    /**
     * Set amountDue
     *
     * @param string $amountDue
     *
     * @return PatientRentalEntity
     */
    public function setAmountDue($amountDue)
    {
        $this->amountDue = $amountDue;

        return $this;
    }

    /**
     * Get amountDue
     *
     * @return string
     */
    public function getAmountDue()
    {
        return $this->amountDue;
    }

    /**
     * Set downPayment
     *
     * @param string $downPayment
     *
     * @return PatientRentalEntity
     */
    public function setDownPayment($downPayment)
    {
        $this->downPayment = $downPayment;

        return $this;
    }

    /**
     * Get downPayment
     *
     * @return string
     */
    public function getDownPayment()
    {
        return $this->downPayment;
    }

    /**
     * Set amortizationAmount
     *
     * @param string $amortizationAmount
     *
     * @return PatientRentalEntity
     */
    public function setAmortizationAmount($amortizationAmount)
    {
        $this->amortizationAmount = $amortizationAmount;

        return $this;
    }

    /**
     * Get amortizationAmount
     *
     * @return string
     */
    public function getAmortizationAmount()
    {
        return $this->amortizationAmount;
    }

    /**
     * Set amountBalance
     *
     * @param string $amountBalance
     *
     * @return PatientRentalEntity
     */
    public function setAmountBalance($amountBalance)
    {
        $this->amountBalance = $amountBalance;

        return $this;
    }

    /**
     * Get amountBalance
     *
     * @return string
     */
    public function getAmountBalance()
    {
        return $this->amountBalance;
    }

    /**
     * Set payerType
     *
     * @param string $payerType
     *
     * @return PatientRentalEntity
     */
    public function setPayerType($payerType)
    {
        $this->payerType = $payerType;

        return $this;
    }

    /**
     * Get payerType
     *
     * @return string
     */
    public function getPayerType()
    {
        return $this->payerType;
    }

    /**
     * Set note
     *
     * @param string $note
     *
     * @return PatientRentalEntity
     */
    public function setNote($note)
    {
        $this->note = $note;

        return $this;
    }

    /**
     * Get note
     *
     * @return string
     */
    public function getNote()
    {
        return $this->note;
    }

    /**
     * Set isDeleted
     *
     * @param boolean $isDeleted
     *
     * @return PatientRentalEntity
     */
    public function setIsDeleted($isDeleted)
    {
        $this->isDeleted = $isDeleted;

        return $this;
    }

    /**
     * Get isDeleted
     *
     * @return boolean
     */
    public function getIsDeleted()
    {
        return $this->isDeleted;
    }

    /**
     * Set isPaymentPlan
     *
     * @param boolean $isPaymentPlan
     *
     * @return PatientRentalEntity
     */
    public function setIsPaymentPlan($isPaymentPlan)
    {
        $this->isPaymentPlan = $isPaymentPlan;

        return $this;
    }

    /**
     * Get isPaymentPlan
     *
     * @return boolean
     */
    public function getIsPaymentPlan()
    {
        return $this->isPaymentPlan;
    }

    /**
     * Set patient
     *
     * @param \RxConnexionBundle\Entity\PatientEntity $patient
     *
     * @return PatientRentalEntity
     */
    public function setPatient(\RxConnexionBundle\Entity\PatientEntity $patient = null)
    {
        $this->patient = $patient;

        return $this;
    }

    /**
     * Get patient
     *
     * @return \RxConnexionBundle\Entity\PatientEntity
     */
    public function getPatient()
    {
        return $this->patient;
    }

    /**
     * Set patientInsurance
     *
     * @param \RxConnexionBundle\Entity\PatientInsuranceEntity $patientInsurance
     *
     * @return PatientRentalEntity
     */
    public function setPatientInsurance(\RxConnexionBundle\Entity\PatientInsuranceEntity $patientInsurance = null)
    {
        $this->patientInsurance = $patientInsurance;

        return $this;
    }

    /**
     * Get patientInsurance
     *
     * @return \RxConnexionBundle\Entity\PatientInsuranceEntity
     */
    public function getPatientInsurance()
    {
        return $this->patientInsurance;
    }

    /**
     * Set healthFacility
     *
     * @param \RxConnexionBundle\Entity\HealthFacilityEntity $healthFacility
     *
     * @return PatientRentalEntity
     */
    public function setHealthFacility(\RxConnexionBundle\Entity\HealthFacilityEntity $healthFacility = null)
    {
        $this->healthFacility = $healthFacility;

        return $this;
    }

    /**
     * Get healthFacility
     *
     * @return \RxConnexionBundle\Entity\HealthFacilityEntity
     */
    public function getHealthFacility()
    {
        return $this->healthFacility;
    }

    /**
     * Set healthFacilityRentalForAddress
     *
     * @param \RxConnexionBundle\Entity\HealthFacilityEntity $healthFacilityRentalForAddress
     *
     * @return PatientRentalEntity
     */
    public function setHealthFacilityRentalForAddress(\RxConnexionBundle\Entity\HealthFacilityEntity $healthFacilityRentalForAddress = null)
    {
        $this->healthFacilityRentalForAddress = $healthFacilityRentalForAddress;

        return $this;
    }

    /**
     * Get healthFacilityRentalForAddress
     *
     * @return \RxConnexionBundle\Entity\HealthFacilityEntity
     */
    public function getHealthFacilityRentalForAddress()
    {
        return $this->healthFacilityRentalForAddress;
    }

    /**
     * Add patientBillingBreakdown
     *
     * @param \RxConnexionBundle\Entity\PatientBillingBreakdownEntity $patientBillingBreakdown
     *
     * @return PatientRentalEntity
     */
    public function addPatientBillingBreakdown(\RxConnexionBundle\Entity\PatientBillingBreakdownEntity $patientBillingBreakdown)
    {
        $this->patientBillingBreakdowns[] = $patientBillingBreakdown;

        return $this;
    }

    /**
     * Remove patientBillingBreakdown
     *
     * @param \RxConnexionBundle\Entity\PatientBillingBreakdownEntity $patientBillingBreakdown
     */
    public function removePatientBillingBreakdown(\RxConnexionBundle\Entity\PatientBillingBreakdownEntity $patientBillingBreakdown)
    {
        $this->patientBillingBreakdowns->removeElement($patientBillingBreakdown);
    }

    /**
     * Get patientBillingBreakdowns
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getPatientBillingBreakdowns()
    {
        return $this->patientBillingBreakdowns;
    }

    /**
     * Add patientPayment
     *
     * @param \RxConnexionBundle\Entity\PatientPaymentEntity $patientPayment
     *
     * @return PatientRentalEntity
     */
    public function addPatientPayment(\RxConnexionBundle\Entity\PatientPaymentEntity $patientPayment)
    {
        $this->patientPayments[] = $patientPayment;

        return $this;
    }

    /**
     * Remove patientPayment
     *
     * @param \RxConnexionBundle\Entity\PatientPaymentEntity $patientPayment
     */
    public function removePatientPayment(\RxConnexionBundle\Entity\PatientPaymentEntity $patientPayment)
    {
        $this->patientPayments->removeElement($patientPayment);
    }

    /**
     * Get patientPayments
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getPatientPayments()
    {
        return $this->patientPayments;
    }
}
