<?php
namespace OfficeBrain\Bundle\CmsBundle\Manager\Extended;

use OfficeBrain\Bundle\CmsBundle\Manager\AbstractManager\ThirdPartyServiceAbstract as ThirdPartyServiceAbstract;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
use OfficeBrain\Bundle\CmsBundle\Entity\ThirdPartyServiceMeta;

/**
 *
 * @author OfficeBrain 4571 <info@officebrain.com>
 *
 * OB eCommerce Product - CMS Third Party Service
 * Extended class for Third Party Service
 *
 */
class ThirdPartyServiceExtended extends ThirdPartyServiceAbstract
{
    /**
     * @author Employee Id: 4571
     *
     * Description : This function is used to set member variables default value
     *
     * @param 1: $entityManager
     * @param 2: $request
     * @param 3: $translator
     * @param 4: $knpPaginator
     * @param 5: $formFactory
     * @param 6: $country
     * @param 7: $language
     * @param 8: $basePath
     *
     * @return: NULL
     *
     * @throws Exception: Null
     */
    public function __construct($entityManager, $request, $translator, $knpPaginator, $formFactory, $country, $language, $basePath)
    {
        parent::__construct($entityManager, $request, $translator, $knpPaginator, $formFactory, $country, $language, $basePath);
    }
    
    /**
     * @author Employee Id: 4571
     *
     * Description : This function is used to unset member variables
     *
     * @param : None
     *
     * @return NULL
     *
     * @throws Exception: Null
     */
    public function __destruct()
    {
        parent::__destruct();
    }

    /**
     * @author OfficeBrain 4571 <info@officebrain.com>
     *
     * Description: for Payment Configuration Details
     *
     * @param 1 : int $id
     *
     * @return: data
     *
     * @throws Exception : Null
    
     */
    public function generateForm($paymentMethod)
    {
        $form = $this->getForm($paymentMethod);
        //$form ->add('form_hidden_id', 'hidden', array('data' => $paymentMethod->getId(), 'mapped' => false ));
        return $form;
    }
    
    /**
     * @author OfficeBrain 4571 <info@officebrain.com>
     *
     * Description: for Payment Configuration Details
     *
     * @param 1 : int $id
     *
     * @return: data
     *
     * @throws Exception : Null
    
     */
    public function getPaymentMethodObject($id)
    {
        $thirdPartySettingMaster = $this->thirdPartySettingRepository->find($id);
         
        return $thirdPartySettingMaster;
    }
        
    /**
     * @author OfficeBrain 4571 <info@officebrain.com>
     *
     * Description: loads parent Payment methods Details
     *
     * @param 1 :  Null
     *
     * @return: data
     *
     * @throws Exception : Null
     *
     */
    public function loadParentPaymentMethods()
    {
        $this->responseArray = $this->getPaymentMethods();
        return $this->responseArray;
    }
    
    /**
     * @author OfficeBrain 4571 <info@officebrain.com>
     *
     * Description: loads parent Payment methods Details
     *
     * @param 1 :  Null
     *
     * @return: data
     *
     * @throws Exception : Null
    
     */
    public function loadParentShipmentMethods()
    {
        $this->responseArray = $this->getShipmentMethods();
        return $this->responseArray;
    }
    
    
    /**
     * @author OfficeBrain 4571 <info@officebrain.com>
     *
     * Description: Save Configuration details
     *
     * @param 1 :  Null
     *
     * @return: data
     *
     * @throws Exception : Null
     *
     */
    public function saveFields($requestForm)
    {
        $countryId = $requestForm['countryId'];
        $keyArray = array("_token", "countryId", "form_hidden_id");
        $str = array();
        foreach ($requestForm as $k=> $r) {
            if (!in_array($k, $keyArray)) {
                $tpsKey = explode("-", $k);
                $tpskValueId = ($tpsKey[1]);
                $str[]=$tpskValueId;
            }
        }
        
        //echo '<pre>'; print_r($requestForm); die;
        $makeCopyCountry = $this->request->request->get('make_copy_country');
        
        ## check if the above string already exist in database table : => tbl_third_party_setting_service_meta
        $count = $this->thirdPartyServiceMetaRepository->findCount($str, $countryId, $this->projectSettings['user_id']);
        
        foreach ($requestForm as $k=> $r) {
            if (!in_array($k, $keyArray)) {
                $tpsKey = explode("-", $k);
                $tpskValueId = ($tpsKey[1]); // tbl_third_party_setting_service_key ====> primary id
                     
                    if (is_array($r)) {
                        $r = json_encode($r);
                    }
                    
                if ($count > 0) { // update
                    $thirdPartyServiceMeta = $this->thirdPartyServiceMetaRepository->findByTpskIdAndCountryAndUserId($tpskValueId, $countryId, $this->projectSettings['user_id']);
                    
                    if (count($thirdPartyServiceMeta) > 0) {
                    	$thirdPartyServiceMeta->setValue($r);
                    	$thirdPartyServiceMeta->setUpdatedUid($this->projectSettings['user_id']);
                    	$thirdPartyServiceMeta->setUpdatedAt(new \DateTime());
                    	$this->thirdPartyServiceMetaRepository->setData($thirdPartyServiceMeta);
                    }
                    
                } else { // insert
                        $entity = new ThirdPartyServiceMeta();
                    $entity->setThirdPartyServiceKeyId($this->thirdPartyServiceKeyRepository->find($tpskValueId));
                    $entity->setInstanceId($this->projectSettings['instance_id']);
                    $entity->setCountryId($countryId);
                    $entity->setValue($r);
                    $entity->setCreatedUid($this->projectSettings['user_id']);
                    $entity->setCreatedAt(new \DateTime());
                    $this->thirdPartyServiceMetaRepository->setData($entity);
                }
            }
        }
        
        $this->thirdPartyServiceMetaRepository->flush();
          
        if ($makeCopyCountry && $makeCopyCountry!="") {
            foreach ($makeCopyCountry as $checkedCountryId=>$value) {
                $this->makeCopyGroup($requestForm, $checkedCountryId);
            }
        }
    }
    
    /**
     * @author Employee Id: 4571
     * Description : Make a Copy of Configuration Form from Object
     *
     * @param 1: obj form
     * @param 2: int $countryId
     *
     * @return object
     *
     * @throws null
     *
     **/
    public function makeCopyGroup($requestForm, $countryId)
    {
        $keyArray = array("_token", "countryId", "form_hidden_id");
        $str = array();
        foreach ($requestForm as $k=> $r) {
            if (!in_array($k, $keyArray)) {
                $tpsKey = explode("-", $k);
                $tpskValueId = ($tpsKey[1]);
                $str[]=$tpskValueId;
            }
        }
         
        ## check if the above string already exist in database table : => tbl_third_party_setting_service_meta
        $count = $this->thirdPartyServiceMetaRepository->findCount($str, $countryId, $this->projectSettings['user_id']);
        
        foreach ($requestForm as $k=> $r) {
            if (!in_array($k, $keyArray)) {
                $tpsKey = explode("-", $k);
                $tpskValueId = ($tpsKey [1]); // tbl_third_party_setting_service_key ====> primary id
                    
                    if (is_array($r)) {
                        $r = json_encode($r);
                    }
                                                 // echo "\n\r";
                    if ($count > 0) { // update
                        $thirdPartyServiceMeta = $this->thirdPartyServiceMetaRepository->findByTpskIdAndCountry($tpskValueId, $countryId);
                        $thirdPartyServiceMeta->setValue($r);
                        $thirdPartyServiceMeta->setUpdatedUid($this->projectSettings ['user_id']);
                        $thirdPartyServiceMeta->setUpdatedAt(new \DateTime());
                        $this->thirdPartyServiceMetaRepository->setData($thirdPartyServiceMeta);
                    } else { // insert
                        $entity = new ThirdPartyServiceMeta();
                        $entity->setThirdPartyServiceKeyId($this->thirdPartyServiceKeyRepository->find($tpskValueId));
                        $entity->setInstanceId($this->projectSettings ['instance_id']);
                        $entity->setCountryId($countryId);
                        $entity->setValue($r);
                        $entity->setCreatedUid($this->projectSettings ['user_id']);
                        $entity->setCreatedAt(new \DateTime());
                        $this->thirdPartyServiceMetaRepository->setData($entity);
                    }
            }
        }
            
        $this->thirdPartyServiceMetaRepository->flush();
    }
    
    /**
     * @author Employee Id: 4571
     *
     * Description : Get Form details Country Wise
     *
     * @param $id
     *
     * @return object
     *
     * @throws null
     *
     **/
    public function getFormDetailsCountryWise()
    {
        $countryId = $this->request->get("countryId");
        $formHiddenId = $this->request->get("formHiddenId");
        $fieldIds = $this->thirdPartyServiceKeyRepository->findId($formHiddenId, $countryId);
        $this->responseArray = array();
        foreach ($fieldIds as $fieldId) {
            $name = '';
            foreach ($fieldId->getThirdPartyServiceMeta() as $fieldValue) {
            	if($this->projectSettings['user_id'] == $fieldValue->getCreatedUid() && $this->instanceId ==$fieldValue->getInstanceId()){
            		$name = str_replace(".", "_", $fieldId->getKeyName());
                	$this->responseArray[] = array('id' => $fieldValue->getId(), 'countryId'=>$fieldValue->getCountryId(),'key'=>$name,'value'=>$fieldValue->getValue());
            		break;
            	}
                
            }
        }
         
        return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4571
     *
     * Description : Get All active shipping method used in configuration Country Wise
     *
     * @param $countryCode
     *
     * @return object
     *
     * @throws null
     *
     **/
    public function getShippingCountryWise($countryCode)
    {
        $countryId= $this->getCountryIdByCode(strtolower($countryCode)); // pass country shortcode and get country id
        if ($countryId > 0) {
            $formHiddenId = $this->thirdPartySettingRepository->findFormId('shipment');    // fetch join  //$type= 'shipment';
            $name = '';
            $shippingArray = array();
            foreach ($formHiddenId as $elements) {
                $tpSettingKeyId = '';
                $tpSettingId = $elements->getId();
                $name = $this->translator->trans($elements->getName());
                     
                foreach ($elements->getThirdPartyServiceKey() as $fieldValue) {
                    $tpSettingKeyId.= $fieldValue->getId().",";
                }
                $tpSettingKeyId = rtrim($tpSettingKeyId, ",");
                $shippingCount = $this->thirdPartyServiceMetaRepository->findCount($tpSettingKeyId, $countryId, $this->projectSettings['user_id']);
                    //echo $shippingCount; echo "<br>";
                if ($shippingCount > 0) {
                   $shippingArray[strtolower($name)] = $name ;
                }
            }
            return $this->responseArray = $shippingArray;
        }
    }
    
    /**
     * @author Employee Id: 4571
     *
     * Description : Get All active shipping method used in configuration Country Wise
     *
     * @param $countryCode
     *
     * @return object
     *
     * @throws null
     *
     **/
    public function getPaymentCountryWise($countryCode, $userId='')
    {
    	$countryId= $this->getCountryIdByCode(strtolower($countryCode)); // pass country shortcode and get country id
    	if ($countryId > 0) {
    		$formHiddenId = $this->thirdPartySettingRepository->findFormId('payment');    // fetch join  //$type= 'shipment';
    		$name = '';
    		$paymentArray = array();
    		foreach ($formHiddenId as $elements) {
    			$tpSettingKeyId = '';
    			$tpSettingId = $elements->getId();
    			$name = $elements->getName();
    			 
    			foreach ($elements->getThirdPartyServiceKey() as $fieldValue) {
    				$tpSettingKeyId.= $fieldValue->getId().",";
    			}
    			$tpSettingKeyId = rtrim($tpSettingKeyId, ",");
    			$paymentCount = $this->thirdPartyServiceMetaRepository->findCount($tpSettingKeyId, $countryId, $userId);
    			//$paymentCount = $this->thirdPartyServiceMetaRepository->findCount($tpSettingKeyId, $countryId);
    			//echo $paymentCount; echo "<br>";
    			if ($paymentCount > 0) {
    				$paymentArray[$elements->getTpsKey()] = $name ;
    			}
    		}
    		return $this->responseArray = $paymentArray;
    	}
    }
    
    /**
     * @author Employee Id: 4571
     *
     * Description : Get configuration Form details
     *
     * @param $id
     *
     * @return object
     *
     * @throws null
     *
     **/
    public function getConfigDetails($tps_key, $countryId, $userId, $instId, $mode)
    {
    	//$tps_key = 'paypal_express';
    	$formHiddenId =  $this->thirdPartySettingRepository->findFormIdByTpsKey(strtolower($tps_key));  	
    	
    	if($formHiddenId=='' || $formHiddenId < 1){
    		return $this->responseArray;
    	}
    	//$countryId = '233'; //$this->request->get("countryId");
    	//$userId = '1';     	
    	//$instId = '1';     	
    	//$mode = 'production';
    	
    	$fieldIds = $this->thirdPartyServiceKeyRepository->findId($formHiddenId, $countryId, $userId, $instId, $mode);
    	$this->responseArray = array();
    	foreach ($fieldIds as $fieldId) {
    		$name = '';
    		foreach ($fieldId->getThirdPartyServiceMeta() as $fieldValue) {
    			$name = str_replace(".", "_", $fieldId->getKeyName());
    			$this->responseArray[] = array('id' => $fieldValue->getId(), 'countryId'=>$fieldValue->getCountryId(),'key'=>$name,'value'=>$fieldValue->getValue());
    		}
    	} 
    	 
    	return $this->responseArray;
    }
    
    
    
}
