<?php
namespace OfficeBrain\Bundle\UserBundle\Manager\AbstractManager;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
use Symfony\Component\Translation\Translator;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\JsonResponse;
use OfficeBrain\Bundle\UserBundle\Entity\ContactBook;

abstract class ContactBookAbstract
{
    protected $entityManager;
    protected $sessionManager;
    protected $paginatorManager;
    protected $request;

    /**
     * @author Employee Id: 4493
     * Initialize the required variable on class load
     *
     */
    public function __construct($entityManager, $request, $sessionManager, $paginatorManager)
    {
        $this->entityManager = $entityManager;
        $this->sessionManager = $sessionManager;
        $this->request = $request;
        $this->paginatorManager = $paginatorManager;
        $this->projectSetting = $this->request->get('project_setting');
        $this->projectUserSetting = $this->request->get('project_user_setting');
        $this->projectSetting = $this->request->get('project_setting');
        $this->instanceId = $this->projectSetting['instance_id'];
        $this->instanceType = $this->projectSetting['instance_type'];
        $this->userId = $this->projectSetting['user_id'];
        $this->user = $this->projectUserSetting['user_data'];
        $this->cultureId = $this->projectSetting['culture_id'];
        $this->cultureCode = $this->projectSetting['culture_code'];
        $this->totalRecord = 0;
        
        $this->userRepositoryManager = $this->entityManager->getRepository('OfficeBrainUserBundle:User');
        $this->contactBookRepositoryManager = $this->entityManager->getRepository('OfficeBrainUserBundle:ContactBook');
        $this->addressTypeRepositoryManager = $this->entityManager->getRepository('OfficeBrainCoreBundle:AddressType');
        $this->userRepositoryManager->setProjectSetting($this->projectSetting);
        $this->userRepositoryManager->setProjectUserSetting($this->projectUserSetting);
        $this->contactBookRepositoryManager->setProjectSetting($this->projectSetting);
        $this->contactBookRepositoryManager->setPaginatorService($this->paginatorManager);
        $this->contactBookRepositoryManager->setProjectUserSetting($this->projectUserSetting);
    }

    public function __destruct()
    {
    	unset($this->entityManager);
        unset($this->sessionManager);
        unset($this->request);
        unset($this->paginatorManager);
        unset($this->projectSetting);
        unset($this->projectUserSetting);
        unset($this->userRepositoryManager);
        unset($this->contactBookRepositoryManager);
        unset($this->addressTypeRepositoryManager);
    }
    
    public function getTotal()
    {
    	return $this->totalRecord;
    }

    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - Contact Book
     * Function created for add contactBook
     */

    public function addContactBook($contactBookObject, $side='', $isAddress)
    {
        $this->contactBookObj = $this->contactBookRepositoryManager->addContactBook($contactBookObject, $side, $isAddress);
        if ($this->contactBookObj) {
        	return array('status'=>'SUCCESS','data'=>$this->contactBookObj);
        }
        return array('status'=>'FAIL');
    }

    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - Contact Book From Quote
     * Function created for add Billing From Quote
     */
    
    public function addBillingAddresssFromQuote($billingAddressData)
    {
    	$addressType = 1;
    	$contactBook = new ContactBook();
    	$addressTypeObj = $this->entityManager->getRepository('OfficeBrainCoreBundle:AddressType')->findOneBy(array('id'=>$addressType));
    	$contactBook->setUser($this->user);
    	$contactBook->setName($billingAddressData['firstName'].' '.$billingAddressData['lastName']);
    	$contactBook->setAdressType($addressTypeObj);
    	$contactBook->setCompanyName($billingAddressData['companyName']);
    	$contactBook->setCompanyNumber($billingAddressData['companyNumber']);
    	$contactBook->setEmail($billingAddressData['email']);
    	$contactBook->setStreet1($billingAddressData['street1']);
    	$contactBook->setStreet2($billingAddressData['street2']);
    	$contactBook->setCountryId($billingAddressData['countryId']);
    	$contactBook->setCountryName($billingAddressData['countryName']);
    	$contactBook->setStateId($billingAddressData['stateId']);
    	$contactBook->setStateName($billingAddressData['stateName']);
    	$contactBook->setCityId($billingAddressData['cityId']);
    	$contactBook->setCityName($billingAddressData['cityName']);
    	$contactBook->setZipcode($billingAddressData['zipcode']);
    	$contactBook->setIsOffice('1');
    	$contactBook->setPhone($billingAddressData['phone']);
    	$contactBook->setFax($billingAddressData['fax']);
    	$contactBook->setWebsite($billingAddressData['website']);
    	
    	$this->contactBookObj = $this->entityManager->getRepository('OfficeBrainUserBundle:ContactBook')->addContactBook($contactBook,'adminSide',0);
    	
    	if ($this->contactBookObj) {
    		return array('status'=>'SUCCESS','data'=>$this->contactBookObj);
    	}
    	return array('status'=>'FAIL');
    }

    
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - Contact Book From Quote
     * Function created for add Billing From Quote
     */
    
    public function addBillingShippingAddresssForQuote($billingAddressData,$addressType,$isAddress,$userObj)
    {
    	//$addressType = 1 for billing address +++++++++++ $addressType = 2 for shipping address ++++++++++ 
    	//$isAddress = 1 for address book +++++++++++ $isAddress = 0 for contact book ++++++++++ 
    	$contactBook = new ContactBook();
    	$addressTypeObj = $this->entityManager->getRepository('OfficeBrainCoreBundle:AddressType')->findOneBy(array('id'=>$addressType));
    	$contactBook->setUser($userObj);
    	$contactBook->setName($billingAddressData['name']);
    	$contactBook->setAdressType($addressTypeObj);
    	$contactBook->setCompanyName($billingAddressData['company_name']);
    	$contactBook->setCompanyNumber($billingAddressData['company_number']);
    	$contactBook->setEmail($billingAddressData['email']);
    	$contactBook->setStreet1($billingAddressData['street1']);
    	$contactBook->setStreet2($billingAddressData['street2']);
    	$contactBook->setCountryId($billingAddressData['country_id']);
    	$contactBook->setStateId($billingAddressData['state_id']);
    	$contactBook->setCityId($billingAddressData['city_id']);
    	$contactBook->setZipcode($billingAddressData['zip_code']);
    	$contactBook->setExtension($billingAddressData['extension']);
    	if($addressType == 2){
    		$contactBook->setIsOffice('1');
    	}	
    	$contactBook->setMobile($billingAddressData['mobile']);
    	$contactBook->setPhone($billingAddressData['phone']);
    	$contactBook->setFax($billingAddressData['fax']);
    	$contactBook->setWebsite($billingAddressData['website']);
    	 
    	$this->contactBookObj = $this->entityManager->getRepository('OfficeBrainUserBundle:ContactBook')->addContactBook($contactBook,'adminSide',$isAddress);
    	 
    	if ($this->contactBookObj) {
    		return array('status'=>'SUCCESS','data'=>$this->contactBookObj);
    	}
    	return array('status'=>'FAIL');
    }
    
    
    
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - Contact Book
     * Function created for check default address is exist or not
     */    
    public function isDefaultAddress($userId, $addressType, $isAddress)
    {
        return $this->contactBookRepositoryManager->isDefaultAddress($userId, $addressType, $isAddress);
    }
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - Contact Book
     * Function created for edit ContactBook
     */
    public function editContactBook($contactBookObject,$changeAddressTypeFlag=0)
    {
        $contactBookObject->setUpdatedUid($this->projectSetting['user_id']);
        if (!$contactBookObject->getIsAddress())
            $contactBookObject->setIsAddress(0);
        $this->contactBook = $this->contactBookRepositoryManager->editContactBook($contactBookObject,$changeAddressTypeFlag);
        if ($this->contactBook) {
            return array('status'=>'SUCCESS', 'data'=>$this->contactBook);
        }
        return array('status'=>'FAIL');
    }
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - Contact Book
     * Function created for get contactId wise single record
     */
    public function getSingleContactBook($contactBookId)
    {
        return $this->contactBookRepositoryManager->getContactBookById($contactBookId);
    }

    public function getUserBillingAddresByUserId($userId){
        return $this->contactBookRepositoryManager->getContactBookByUserIdSingle($userId);
    }

    public function getContactBookByEmailSingle($email,$userId)
    {
        return $this->contactBookRepositoryManager->getContactBookByEmailSingle($email,$userId);
    }
    
    
	/**
     * @author Employee Id: 4493
     * OB eCommerce Product - Contact Book
     * Function created for get contactId wise single record
     */
    public function getSingleContactBookMobileApi($contactBookId)
    {
        return $this->contactBookRepositoryManager->getContactBookByIdMobileApi($contactBookId);
    }

    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - Contact Book
     * Function created for get all record of contactbook
     */    
    public function getContactBook($userId, $isAddress, $page, $recordsPerPage, $searchParameterArray='')
    {
        $this->paginatorRecordSet = $this->contactBookRepositoryManager->getContactBook($userId, $searchParameterArray, $isAddress, $page, $recordsPerPage);
        $this->totalRecord = $this->paginatorRecordSet->getTotalItemCount();
        return $this->paginatorRecordSet;
    }
    
	/**
     * @author Employee Id: 4493
     * OB eCommerce Product - Contact Book
     * Function created for get all record of contactbook
     */    
    public function getContactBookMobileApi($userId, $isAddress, $page, $recordsPerPage, $searchParameterArray='')
    {
    	$addressType = $this->request->get('address_type',null);
        $this->paginatorRecordSet = $this->contactBookRepositoryManager->getContactBookMobileApi($userId, $searchParameterArray, $isAddress, $page, $recordsPerPage, $addressType);
        $this->totalRecord = $this->paginatorRecordSet->getTotalItemCount();
        return $this->paginatorRecordSet;
    }
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - Contact Book
     * Function created for get all Address Book
     */
    public function getAllAddressBook($userId, $addressType='', $searchIn=array(), $isAllField=true)
    {
    	$this->RecordSet = $this->contactBookRepositoryManager->getAllAddressBook($userId, $addressType, $searchIn, $isAllField);
    	return $this->RecordSet;
    }

    
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - Contact Book
     * Function created for get all Contact Book
     */
    public function getAllContactBook($userId, $addressType='', $searchIn=array(), $isAllField=true)
    {
    	$this->RecordSet = $this->contactBookRepositoryManager->getAllContactBook($userId, $addressType, $searchIn, $isAllField);
    	return $this->RecordSet;
    }


	/**
     * @author Employee Id: 4493
     * OB eCommerce Product - Contact Book
     * Function created for delete contact book
     */    
    public function deleteContactBook($contactBookId)
    {
        $this->contactBookDeleted = $this->contactBookRepositoryManager->deleteContactBook($contactBookId);
        if ($this->contactBookDeleted) {
            return array('status'=>'SUCCESS','data'=>$this->contactBookDeleted);
        }
        return array('status'=>'FAIL');
    }    

    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - getUserById of login user
     * Function created to get User By Id Of login user
     */
    public function getValidUserById($id)
    {
        $loginId = $this->projectSetting['user_id'];
        $userObj = $this->projectUserSetting['user_data'];
        if ($userObj->getUserType() == 'employee' || $userObj->getUserType() == 'branchEmployee') {
            $loginId = $userObj->getParent()->getId();
        }

        return $this->userRepositoryManager->getValidUserById($id, $loginId);
    }

    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - Contact Book
     * Function created for get addresstype dropdown
     */
    public function getAddressType()
    {
        $addressType = array();
        $addresstypeResult = $this->addressTypeRepositoryManager->getAllAddressType();
        foreach ($addresstypeResult as $key=>$value) {
            $addressType[$value['id']] = $value['name'];
        }

        return $addressType;
    }
    
	/**
     * @author Employee Id: 410175
     * OB eCommerce Product - Contact Book
     * Function created for get addresstype dropdown for mobile api
     */
    public function getAddressTypeMobileApi()
    {
        $addressType = array();
        $addresstypeResult = $this->addressTypeRepositoryManager->getAllAddressType();
        foreach ($addresstypeResult as $key=>$value) {
            $addressType[$key]['key'] = $value['id'];
            $addressType[$key]['value'] = $value['name'];
        }

        return $addressType;
    }
    
    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - update Is default
     * Delete user by id
     */
    public function updateIsDefault($contactBookId)
    {
       return  $this->contactBookObj = $this->contactBookRepositoryManager->updateIsDefault($contactBookId);
       
    }
    /**
     * @author Employee Id: 410175
     * OB eCommerce Product - Get Default billing/shipping contact address 
     */
    public function getDefaultContactBookIdMobileApi($userId,$addressTypeAry=array(1,2))
    {	
    	$returnAry = null;
    	foreach ($addressTypeAry as $type){
    		if(is_numeric($type) && $type>0){
    			$data = $this->contactBookRepositoryManager->getDefaultContactBookIdMobileApi($userId, ((int)$type));
    			if($data && count($data)>0){
    				$returnAry[$data[0]['addressTypeLabel']] = $data[0];
    			}
    		}
    	}
    	
    	return $returnAry;    	 
    }

    /** 
    * @author Employee Id:5083
    * OB eCommerce product - Get search address from user contact book
    */
    public function getPopAddressList($userId,$option,$keywords,$page, $recordsPerPage,$addressType){
        $returnAry= $this->contactBookRepositoryManager->getSearchPopAddressList($userId,$option,$keywords,$page, $recordsPerPage,$addressType);
         return $returnAry;

    }

    /** 
    * @author Employee Id:5083
    * OB eCommerce product - Get search company from user contact book
    */
    public function getPopCompanyAddressList($userId,$keywords,$page, $recordsPerPage,$addressType){
        $returnAry= $this->contactBookRepositoryManager->getCompanySearchPopupAddressList($userId,$keywords,$page, $recordsPerPage,$addressType);
         return $returnAry;

    }

    /**
     * @author Employee Id: 5497
     * OB eCommerce Product - Contact Book
     * Function created for get Contact Book By Email
     */
    public function getContactBookByEmail($email, $addressType = null)
    {
    	return $this->contactBookRepositoryManager->getContactBookByEmail($email, $addressType);
    }
}
