<?php

namespace RxConnexionBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToStringTransformer;

/**
 * @ORM\Entity(repositoryClass="RxConnexionBundle\Repository\CanvassRepository")
 * @ORM\Table(name="canvass")
 * @ORM\HasLifecycleCallbacks()
 */

class CanvassEntity
{
    const STATUS_PENDING_FIN_OFF_APP_FOR_PO = 'Pending Finance Officer Approval For PO';
    const STATUS_PENDING_ADMIN_APP_FOR_PO = 'Pending Admin Approval For PO';

    /**
     * @ORM\Column(type="bigint")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(name="canvass_no", type="string", nullable=true)
     */
    protected $canvassNo;

    /**
     * @ORM\Column(name="status", type="string", nullable=true)
     */
    protected $status;

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

    /**
     * @ORM\Column(name="created_by", type="string", length=50)
     */
    protected $createdBy;

    /**
     * @ORM\Column(name="created_at", type="datetime")
     */
    protected $createdAt;

    /**
     * @ORM\Column(name="updated_by", type="string", length=50)
     */
    protected $updatedBy;

    /**
     * @ORM\Column(name="updated_at", type="datetime")
     */
    protected $updatedAt;

    /**
     * @ORM\ManyToOne(targetEntity="MaterialRequisitionEntity", inversedBy="canvasses")
     * @ORM\JoinColumn(name="material_requisition_id", referencedColumnName="id")
     */
    protected $materialRequisition;

    /**
     * @ORM\ManyToOne(targetEntity="AccountUserEntity", inversedBy="canvassesWhoSent")
     * @ORM\JoinColumn(name="user_id_who_sent", referencedColumnName="id")
     */
    protected $userWhoSent;

    /**
     * @ORM\OneToMany(targetEntity="CanvassItemEntity", mappedBy="canvass")
     */
    protected $canvassItems;

    /**
     * @ORM\OneToMany(targetEntity="CanvassStatusEntity", mappedBy="canvass")
     */
    protected $canvassStatuses;

    /**
     * @ORM\OneToMany(targetEntity="PurchaseOrderEntity", mappedBy="canvass")
     */
    protected $purchaseOrders;

    /**
     * Set createdAt
     *
     * @ORM\PrePersist
     */
    public function setCreatedAtValue()
    {
        $this->createdBy = isSet($_COOKIE['username']) ? $_COOKIE['username'] : 'System';
        $this->createdAt = new \DateTime();
        $this->updatedBy = isSet($_COOKIE['username']) ? $_COOKIE['username'] : 'System';
        $this->updatedAt = new \DateTime();
//        $this->status = 'Supplier Canvassing';
        //Forced Approve
        $this->status = 'Approved';
        $this->approvalBatchNo = 0;
    }

    /**
     * Set updatedAt
     *
     * @ORM\PreUpdate
     */
    public function setUpdatedAtValue()
    {
        $this->updatedBy = $_COOKIE['username'];
        $this->updatedAt = new \DateTime();
    }

    public function doVoid() {

        $isAllQuantityVoidedSelf = true;
        $isAllQuantityVoided = true;

        foreach($this->canvassItems as $canvassItem) {
            $canvassItem->getMaterialRequisitionItem()->updateQuantityVoided();
            if(!$canvassItem->getIsAllQuantityVoided()) $isAllQuantityVoidedSelf = false;
            if(!$canvassItem->getMaterialRequisitionItem()->getIsAllQuantityVoided()) $isAllQuantityVoided = false;

        }

        if($isAllQuantityVoidedSelf) $this->status = 'Voided';
        if($isAllQuantityVoided) $this->materialRequisition->doVoid();

        return $this;
    }

    public function doAddQuantity() {

        foreach($this->canvassItems as $canvassItem) {
            $canvassItem->getMaterialRequisitionItem()->updateQuantityAdded();
        }

        return $this;
    }

    public function __construct($data=null)
    {
        if(!is_null($data)) {
            $this->id = $data->getId();
            $this->status = $data->getStatus();
            $this->approvalBatchNo = $data->getApprovalBatchNo();
            $this->materialRequisition = $data->getMaterialRequisition();
        }

        $this->canvassItems = new ArrayCollection();
        $this->canvassStatuses = new ArrayCollection();
        $this->purchaseOrders = new ArrayCollection();
    }

    /*--------------------------------------------------------------------------------------------------------*/
    /*					User Defined Setters and Getters													  */
    /*--------------------------------------------------------------------------------------------------------*/

    /**
     * Get idEncoded
     *
     * @return string
     */
    public function getIdEncoded() {

        return base64_encode($this->id);
    }

    /**
     * Get canvassNoParsed
     *
     * @return string
     */
    public function getCanvassNoParsed() {

        return sprintf('%012d', $this->id);
    }

    /**
     * @param array $userData
     *
     * @return boolean
     */
    public function canApproveByUser($userData) {

        $canApproveByUser = false;
        $isAlreadyApproved = false;

        switch($this->status) {
            case 'Pending Purchasing Manager Approval':

                switch($userData['type']) {
                    case 'Super Admin':
                    case 'Admin':
                        $canApproveByUser = true;
                        break;
                    case 'Purchasing Manager':

                        foreach($this->canvassStatuses as $canvassStatus) {
                            if($this->approvalBatchNo === $canvassStatus->getBatchNo() && $canvassStatus->getStatus() === 'Pending Purchasing Manager Approval' && $canvassStatus->getUser() && $canvassStatus->getUser()->getId() === $userData['id'])
                                $isAlreadyApproved = true;
                        }

                        if(!$isAlreadyApproved) $canApproveByUser = true;

                        break;
                }

                break;
            case 'Pending Admin Approval For Purchase Order':

                if(in_array($userData['type'], array('Super Admin', 'Admin'))) {

                    foreach($this->canvassStatuses as $canvassStatus) {
                        if($this->approvalBatchNo === $canvassStatus->getBatchNo() && $canvassStatus->getStatus() === 'Pending Admin Approval For Purchase Order' && $canvassStatus->getUser() && $canvassStatus->getUser()->getId() === $userData['id'])
                            $isAlreadyApproved = true;
                    }

                    if(!$isAlreadyApproved) $canApproveByUser = true;
                }

                break;
        }

        return $canApproveByUser;
    }

    /**
     * Get isApprovedByStatusAndUserFullName
     *
     * @param $status
     * @param $userFullName
     * @return boolean
     */
    public function isApprovedByStatusAndUserFullName($status, $userFullName) {

        $userFullName = strtoupper($userFullName);

        if($this->canvassStatuses->count()) {
            foreach($this->canvassStatuses as $canvassesStatus) {
                if($status === $canvassesStatus->getStatus() && 'Approved' === $canvassesStatus->getApprovalDescription() &&
                    $userFullName === $canvassesStatus->getUser()->getFullNameToUpper()) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * Get selectedSuppliers
     *
     * @return array
     */
    public function getSelectedSuppliers() {

        $suppliers = array();

        foreach($this->canvassItems as $canvassItem) {
            if($canvassItem->getCanvassItemSuppliers()) {
                foreach($canvassItem->getCanvassItemSuppliers() as $canvassItemSupplier) {
                    if($canvassItemSupplier->getIsSelected()) {
                        $supplierData = array(
                            'supplier' => $canvassItemSupplier->getSupplier(),
//                            'currency' => $canvassItemSupplier->getCurrency(),
//                            'withholdingTaxRate' => $canvassItemSupplier->getWithholdingTaxRate(),
                            'paymentMode' => $canvassItemSupplier->getPaymentMode(),
                            'term' => $canvassItemSupplier->getTerm()
                        );
                        if(!in_array($supplierData, $suppliers)) {
                            $suppliers[] = $supplierData;
                        }
                    }
                }
            }
        }

        return $suppliers;
    }

    /**
     * Get isVoidable
     *
     * @return boolean
     */
    public function getIsVoidable() {

        return $this->status === 'Approved' || $this->status === 'Voided' || $this->status === 'Cancelled' ? false : true;
    }

    /**
     * Get hasQuantityForCanvassing
     *
     * @return boolean
     */
    public function getHasQuantityForCanvassing() {

        $has = false;

        foreach($this->canvassItems as $canvassItem) {
            if($canvassItem->getQuantityForCanvassing() != $canvassItem->getQuantityCanvassed()) {
                $has = true;
                break;
            }
        }

        return $has;
    }

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

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

    /**
     * Set status
     *
     * @param string $status
     * @return CanvassEntity
     */
    public function setStatus($status)
    {
        $this->status = $status;

        return $this;
    }

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

    /**
     * Set approvalBatchNo
     *
     * @param integer $approvalBatchNo
     * @return CanvassEntity
     */
    public function setApprovalBatchNo($approvalBatchNo)
    {
        $this->approvalBatchNo = $approvalBatchNo;

        return $this;
    }

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

    /**
     * Set createdBy
     *
     * @param string $createdBy
     * @return CanvassEntity
     */
    public function setCreatedBy($createdBy)
    {
        $this->createdBy = $createdBy;

        return $this;
    }

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

    /**
     * Set createdAt
     *
     * @param \DateTime $createdAt
     * @return CanvassEntity
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;

        return $this;
    }

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

    /**
     * Set updatedBy
     *
     * @param string $updatedBy
     * @return CanvassEntity
     */
    public function setUpdatedBy($updatedBy)
    {
        $this->updatedBy = $updatedBy;

        return $this;
    }

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

    /**
     * Set updatedAt
     *
     * @param \DateTime $updatedAt
     * @return CanvassEntity
     */
    public function setUpdatedAt($updatedAt)
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

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

    /**
     * Set materialRequisition
     *
     * @param \RxConnexionBundle\Entity\MaterialRequisitionEntity $materialRequisition
     * @return CanvassEntity
     */
    public function setMaterialRequisition(\RxConnexionBundle\Entity\MaterialRequisitionEntity $materialRequisition = null)
    {
        $this->materialRequisition = $materialRequisition;

        return $this;
    }

    /**
     * Get materialRequisition
     *
     * @return \RxConnexionBundle\Entity\MaterialRequisitionEntity
     */
    public function getMaterialRequisition()
    {
        return $this->materialRequisition;
    }

    /**
     * Add canvassItems
     *
     * @param \RxConnexionBundle\Entity\CanvassItemEntity $canvassItems
     * @return CanvassEntity
     */
    public function addCanvassItem(\RxConnexionBundle\Entity\CanvassItemEntity $canvassItems)
    {
        $this->canvassItems[] = $canvassItems;

        return $this;
    }

    /**
     * Remove canvassItems
     *
     * @param \RxConnexionBundle\Entity\CanvassItemEntity $canvassItems
     */
    public function removeCanvassItem(\RxConnexionBundle\Entity\CanvassItemEntity $canvassItems)
    {
        $this->canvassItems->removeElement($canvassItems);
    }

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

    /**
     * Add canvassStatuses
     *
     * @param \RxConnexionBundle\Entity\CanvassStatusEntity $canvassStatuses
     * @return CanvassEntity
     */
    public function addCanvassStatus(\RxConnexionBundle\Entity\CanvassStatusEntity $canvassStatuses)
    {
        $this->canvassStatuses[] = $canvassStatuses;

        return $this;
    }

    /**
     * Remove canvassStatuses
     *
     * @param \RxConnexionBundle\Entity\CanvassStatusEntity $canvassStatuses
     */
    public function removeCanvassStatus(\RxConnexionBundle\Entity\CanvassStatusEntity $canvassStatuses)
    {
        $this->canvassStatuses->removeElement($canvassStatuses);
    }

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

    /**
     * Add purchaseOrders
     *
     * @param \RxConnexionBundle\Entity\PurchaseOrderEntity $purchaseOrders
     * @return CanvassEntity
     */
    public function addPurchaseOrder(\RxConnexionBundle\Entity\PurchaseOrderEntity $purchaseOrders)
    {
        $this->purchaseOrders[] = $purchaseOrders;

        return $this;
    }

    /**
     * Remove purchaseOrders
     *
     * @param \RxConnexionBundle\Entity\PurchaseOrderEntity $purchaseOrders
     */
    public function removePurchaseOrder(\RxConnexionBundle\Entity\PurchaseOrderEntity $purchaseOrders)
    {
        $this->purchaseOrders->removeElement($purchaseOrders);
    }

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

    /**
     * Set canvassNo
     *
     * @param string $canvassNo
     * @return CanvassEntity
     */
    public function setCanvassNo($canvassNo)
    {
        $this->canvassNo = $canvassNo;

        return $this;
    }

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

    /**
     * Set userWhoSent
     *
     * @param \RxConnexionBundle\Entity\AccountUserEntity $userWhoSent
     *
     * @return CanvassEntity
     */
    public function setUserWhoSent(\RxConnexionBundle\Entity\AccountUserEntity $userWhoSent = null)
    {
        $this->userWhoSent = $userWhoSent;

        return $this;
    }

    /**
     * Get userWhoSent
     *
     * @return \RxConnexionBundle\Entity\AccountUserEntity
     */
    public function getUserWhoSent()
    {
        return $this->userWhoSent;
    }
}
