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

use Symfony\Component\DependencyInjection\ContainerInterface as Container;
use Symfony\Component\HttpFoundation\Request;
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 Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use OfficeBrain\Bundle\CoreBundle\File\ApiUploadedFile;
/**
 *
 * @author Employee Id: 4273
 * OB eCommerce Product - Core
 * CoreAbstract Class Add to define the common function and logic for sign up process
 */

abstract class CoreAbstract
{
    private $entityManager;
    protected $session;
    protected $request;
    private $locationPath;
	private $subShopMediaUploadLocation;
	private $countryConfiguration;
	private $serviceContainer;
    /**
     * @author Employee Id: 4273
     * Initialize the required variable on class load
     *
     */
    public function __construct($entityManager, $request, $session, $subShopMediaUploadLocation, $country,$serviceContainer)
    {
        $this->entityManager = $entityManager;
        $this->session = $session;
        $this->request = $request;
        $this->countryLanguageConfiguration = $country;
        $this->serviceContainer = $serviceContainer;
        $this->countryConfiguration = array();
        $this->subShopMediaUploadLocation = $subShopMediaUploadLocation;
        foreach ($country as $key=>$value) {
        	$this->countryConfiguration[]=$value['short_name'];
        }
    }
    
    public function getUserType(){
    	$user = $this->request->get('project_setting');
    	if($user['user_id']>0){
    		$userData=$this->request->get('project_user_setting')['user_data'];
    		return $userData->getUserType();
    	}
    	return 'end_user';
    }

    /**
     * @author Employee Id: 410175
     * OB eCommerce Product - Core
     * Function created to get country data
     */
    public function getCountryDataAPI($countryConfiguration=null)
    {
    	if( null == $countryConfiguration ){
    		$countryConfiguration = $this->countryConfiguration;
    	}
    	$countryData=array();
    	$countryResult=$this->entityManager->getRepository("OfficeBrainCoreBundle:Country")->getCountry( $countryConfiguration );
    	foreach ($countryResult as $key=>$value) {

    		$countryData[$key]['key']=$value['id'];
    		$countryData[$key]['value']=$value['countryName'];
    	}

    	return $countryData;
    }

    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - Core
     * Function created to get country data
     */
    public function getCountryData($countryConfiguration=array())
    {
        $countryData=array();
        $countryResult=$this->entityManager->getRepository("OfficeBrainCoreBundle:Country")->getCountry($this->countryConfiguration);
        foreach ($countryResult as $key=>$value) {
            $countryData[$value['id']]=$value['countryName'];
        }
        return $countryData;
    }
    
    
    /**
     * @author Employee Id: 4471
     * OB eCommerce Product - Core
     * Function created to get country data with country code
     * comment : made chages in product/src on 29/12/2015 because we need both country code and country name in shipping estimator
     */
 	public function getCountryDataWithCode($countryConfiguration=array())
    {
    	if(count($countryConfiguration)>0)
    	{
    		$countryReq=$countryConfiguration;
    	}
    	else
    	{
    		$countryReq=$this->countryConfiguration;
    	}
    	$countryData=array();
    	$countryResult=$this->entityManager->getRepository("OfficeBrainCoreBundle:Country")->getCountry($countryReq);
    	foreach ($countryResult as $key=>$value) {
    		$countryData[$value['countryCode']]=$value['countryName'];
    	}
    
    	return $countryData;
    }

    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - Core
     * Function created to get state data
     */
    public function getStateDataAPI($countryCode = '')
    {
    	$stateData=array();
    	$stateResult=$this->entityManager->getRepository("OfficeBrainCoreBundle:State")->getState($countryCode);
    	foreach ($stateResult as $key=>$value) {
    		$stateData[$key]['key']=$value['id'];
    		$stateData[$key]['value']=$value['stateName'];
    	}
    	return $stateData;
    }

    /**
     * @author Employee Id: 410175
     * OB eCommerce Product - Core
     * Function created to get All state data for Distributor
     */
    public function getLocateDistributorStateDataAPI($countryCode = '')
    {
    	$stateData=array();
    	$stateResult=$this->entityManager->getRepository("OfficeBrainCoreBundle:State")->getLocateDistributorState($countryCode,$this->countryConfiguration);
    	foreach ($stateResult as $key=>$value) {
    		$stateData[$key]['key']=$value['id'];
    		$stateData[$key]['value']=$value['stateName'];
    	}
    	return $stateData;
    }

    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - Core
     * Function created to get state data
     */
    public function getStateData($countryIds = '')
    {
        $stateData=array();
        $stateResult=$this->entityManager->getRepository("OfficeBrainCoreBundle:State")->getState($countryIds);
        foreach ($stateResult as $key=>$value) {
            $stateData[$value['id']]=$value['stateName'];
        }
        return $stateData;
    }
    
    
    /**
     * @author Employee Id: 4471
     * OB eCommerce Product - Core
     * Function created to get state data from country Code (use in shipping esti)
     */
    public function getStateDataFromCountryCode($countryCode = '')
    {
    	$stateData=array();
    	$stateResult=$this->entityManager->getRepository("OfficeBrainCoreBundle:State")->getStateFromCountryCode($countryCode);
    	foreach ($stateResult as $key=>$value) {
    		$stateData[$value['id']]=$value['stateName'];
    	}
    	return $stateData;
    }

    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - Core
     * Function created to get All state data
     */
    public function getLocateDistributorStateData($countryCode = '')
    {
    	$stateData=array();
    	$stateResult=$this->entityManager->getRepository("OfficeBrainCoreBundle:State")->getLocateDistributorState($countryCode,$this->countryConfiguration);
    	foreach ($stateResult as $key=>$value) {
    		$stateData[$value['id']]=$value['stateName'];
    	}
    	return $stateData;
    }


    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - Core
     * Function created to get city data
     */
    public function getCityDataAPI($stateCode = '', $countryCode = '')
    {
    	$cityData=array();
    	$stateResult=$this->entityManager->getRepository("OfficeBrainCoreBundle:City")->getCity($stateCode, $countryCode);
    	foreach ($stateResult as $key=>$value) {
    		$cityData[$key]['key']=$value['id'];
    		$cityData[$key]['value']=$value['cityName'];
    	}

    	return $cityData;
    }
    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - Core
     * Function created to get city data
     */
    public function getCityData($stateCode = '', $countryCode = '')
    {
        $cityData=array();
        $stateResult=$this->entityManager->getRepository("OfficeBrainCoreBundle:City")->getCity($stateCode, $countryCode);
        foreach ($stateResult as $key=>$value) {
            $cityData[$value['id']]=$value['cityName'];
        }

        return $cityData;
    }

    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - Core
     * Function created to get country name by countryId
     */

    public function getCountryName($countryId)
    {
        $countryName = $this->entityManager->getRepository("OfficeBrainCoreBundle:Country")->getCountryNameById($countryId);
        return $countryName[0]['countryName'];
    }

    /**
     * @author Employee Id: 4471
     * OB eCommerce Product - Core
     * Function created to get country code by countryId
     */

    public function getCountryCode($countryId)
    {
    	$countryName = $this->entityManager->getRepository("OfficeBrainCoreBundle:Country")->getCountryCodeById($countryId);
    	return $countryName[0]['countryCode'];
    }

    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - Core
     * Function created to get state name by stateId
     */
    public function getStateName($stateId)
    {
        $stateName = $this->entityManager->getRepository("OfficeBrainCoreBundle:State")->getStateNameById($stateId);
        return $stateName[0]['stateName'];
    }
    
    /**
     * @author Employee Id: 4846
     * OB eCommerce Product - Core
     * Function created to get state code by stateId
     */
    public function getStateCode($stateId)
    {
    	$stateName = $this->entityManager->getRepository("OfficeBrainCoreBundle:State")->getStateCodeById($stateId);
    	return $stateName[0]['stateCode'];
    }

    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - Core
     * Function created to get city name by cityId
     */

    public function getCityName($cityId)
    {
        $cityName = $this->entityManager->getRepository("OfficeBrainCoreBundle:City")->getCityNameById($cityId);
        return $cityName[0]['cityName'];
    }


    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - Core
     * Function created to get Service Group Name by serviceGroupId
     */

    public function getServiceGroupName($serviceGroupId)
    {
    	$serviceGroupName = $this->entityManager->getRepository("OfficeBrainServiceGroupBundle:ServiceGroup")->getServiceGroupName($serviceGroupId);
    	return $serviceGroupName[0]['groupName'];
    }

     /**
     * @author Employee Id: 4493
     * OB eCommerce Product - Core
     * Function created to get address type by id
     */
    public function getAddressTypeObj($addressTypeId)
    {
        $addressType = $this->entityManager->getRepository("OfficeBrainCoreBundle:AddressType")->getAddressTypeObjById($addressTypeId);
        return $addressType;
    }


    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - Core
     * Function created to get address type by id
     */
    public function getAddressType($addressTypeId)
    {
        $addressType = $this->entityManager->getRepository("OfficeBrainCoreBundle:AddressType")->getAddressTypeById($addressTypeId);
        return $addressType[0]['name'];
    }

    public function getApiUploadedFile($base64File,$originalName){
    	return new ApiUploadedFile($base64File,$originalName);
    }

    public function getUploadedFile($file){
    	return new UploadedFile(
    			$file['tmp_name'],
    			$file['name'], $file['type'],
    			$file['size'], $file['error'],
    			$test = false);
    }

    public function uploadImage($parameter,$file,$location) {
    	$error=array();
    	if(is_object($file))
    	{
    		$parameter_location=$this->getLocationPath().$location;
    		$target_dir=$parameter_location.'/'.$file->getClientOriginalName();
    		if (!is_dir($parameter_location)) {
    			if (false === @mkdir($parameter_location, 0777, true))
    			{
    				$error[]='Unable to create the "%s" directory';
    				return $error;
    			}
    		}
    		list($width,$height)=@getimagesize($file);

    		if(!in_array($file->getClientMimeType(),$parameter['type']))
    			return "TYPE";
    		else if($file->getClientSize()>$parameter['size'] * 1024 * 1024)
    			return "SIZE";
    		else if($width>$parameter['width']+10 || $width < $parameter['width']-10)
    			return "WIDTH";
    		else if($height>$parameter['height']+10 || $height < $parameter['height']-10)
    			return "HEIGHT";
    		if($file->move($parameter_location,$file->getClientOriginalName()))
    			return "SUCCESS";
    		else
    			return "FAIL";
    	}

    }
    public function uploadFile($parameter,$file,$location) {
    	$error=array();
    	if(is_object($file))
    	{
    		$parameter_location=$this->getLocationPath().$location;
    		$target_dir=$parameter_location.'/'.$file->getClientOriginalName();
    		if (!is_dir($parameter_location)) {
    			if (false === @mkdir($parameter_location, 0777, true))
    			{
    				$error[]='Unable to create the "%s" directory';
    				return $error;
    			}
    		}
    		if(!in_array($file->getClientMimeType(),$parameter['type']))
    			return "TYPE";
    		else if($file->getClientSize()>$parameter['size'] * 1024 * 1024)
    			return "SIZE";
    		if($file->move($parameter_location,$file->getClientOriginalName()))
    			return "SUCCESS";
    		else
    			return "FAIL";
    	}

    }

    public function getLocationPath() {
    	return $this->locationPath;
    }
    public function setLocationPath($locationPath) {
    	$this->locationPath = $locationPath;
    	return $this;
    }
    public function getDomain()
    {
    	$domain=$this->entityManager->getRepository("OfficeBrainAccessManagementBundle:InstanceMaster")->getAllInstanceMasterArray();
    	return $domain;
    }

    public function getLogo()
    {
    	$logo = '';
    	$instanceDesign = $this->entityManager->getRepository("OfficeBrainSubShopBundle:SubShop")->findByInstanceDesign($this->request->get('_route') == 'office_brain_subshopbundle_subshopthemeadmin_subshopthemepreview' ? 'draft' : 'publish');

    	if (isset($instanceDesign[0]['customDesign']))
    	{
    		$customDesign = json_decode($instanceDesign[0]['customDesign'], 'Array');

    		if (isset($customDesign['logoImage']))
    		{
    			$logo = $this->subShopMediaUploadLocation['url'] .$customDesign['logoImage'];
    		}
    	}

    	return $logo;
    }


    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - Core
     *
     * Convert under_score type array's keys to camelCase type array's keys
     * @param array $array array to convert
     * @param array $arrayHolder parent array holder for recursive array
     * @return array camelCase array
     */
    public function camelCaseKeys($array, $arrayHolder = array())
    {
        $camelCaseArray = !empty($arrayHolder) ? $arrayHolder : array();
        //print_r($array);
        foreach ($array as $key => $val) {
            $newKey = @explode('_', $key);
            array_walk($newKey, create_function('&$v', '$v = ucwords($v);'));
            $newKey = @implode('', $newKey);
            $newKey{0}
            = strtolower($newKey{0});
            //if (!is_array($val)) {
            $camelCaseArray[$newKey] = $val;
            //} else {
            //	$camelCaseArray[$newKey] = $this->camelCaseKeys($val, $camelCaseArray[$newKey]);
            //}
        }

        return $camelCaseArray;
    }


    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - Core
     *
     */
    public function get_array_column($array, $columnKey, $indexKey='')
    {
        $newAry = array();
        if ($indexKey=='key') {
            foreach ($array as $k=>$a) {
                $newAry[$k] = $a[$columnKey];
            }
        } else {
            foreach ($array as $a) {
                if (isset($a[$indexKey])) {
                    $newAry[$a[$indexKey]] = $a[$columnKey];
                } else {
                    $newAry[] = $a[$columnKey];
                }
            }
        }
        return $newAry;
    }

    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - Core
     * Function created to get user photo by id
     */
    public function getUserPhoto($userId)
    {
    	$userPhoto = $this->entityManager->getRepository("OfficeBrainUserBundle:User")->getUserById($userId);
    	return  $userPhoto->getPhoto();

    }

    /**
     * @author Employee Id: 4493
     * OB eCommerce Product - Core
     * Function created to get country culture
     */
    public function getCountryCulture()
    {
    	$countryArray = $this->countryLanguageConfiguration;
    	$cultureCountry = null;
    	foreach ($countryArray as $key=>$value) {
    		foreach($value['language'] as $k => $v) {
    			$cultureCountry .= $k.'_'.$value['short_name'].',';
    		}
    	}
    	$cultureCountry = trim($cultureCountry,',');
    	return $cultureCountry;
    }

    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - Core
     * Function created to get decimal points for price
     */
    public function getDecimalPointForPrice()
    {
        return $this->request->get('project_setting')['price_in_decimal'];
    }
    
    /**
     * @author Employee Id: 4273
     * OB eCommerce Product - Core
     * Function created to get decimal points for price
     */
    public function getPriceFormater()
    {
    	$priceFormatter = $this->serviceContainer->getParameter('price_formater');
    	$user = $this->request->get('project_setting');
    	$priceFormatter['user_id'] = $user['user_id'];
    	
    	return $priceFormatter;
    }
	public function formatinr($input){  
        //CUSTOM FUNCTION TO GENERATE ##,##,###.##  
        $dec = "";  
        $pos = strpos($input, ".");  
        if ($pos === false){  
            //no decimals     
        } else {  
            //decimals  
            $dec = substr(round(substr($input,$pos),2),1);  
            $input = substr($input,0,$pos);  
        }  
        $num = substr($input,-3); //get the last 3 digits  
        $input = substr($input,0, -3); //omit the last 3 digits already stored in $num  
        while(strlen($input) > 0) //loop the process - further get digits 2 by 2  
        {  
            $num = substr($input,-2).",".$num;  
            $input = substr($input,0,-2);  
        }  
        return $num . $dec;  
    }
    
    /**
     * @author Employee Id: 4471
     * OB eCommerce Product - Core
     * Function to get distributor CompanyName from user id
     */
    public function getDistributorCompanyName($userId)
    {
    	$userObj = $this->entityManager->getRepository("OfficeBrainUserBundle:User")->getUserById($userId);
    	if($userObj && $userObj->getUserCompany()){
    		return $userObj->getUserCompany()->getCompanyName();
    	}else{
    		return null;
    	}
    }
    
    /**
     * @author Employee Id: 4203
     * OB eCommerce Product - Core
     * Function to get site owner id from access listener variable
     */
    public function getSiteOwnerId()
    {
    	return $this->request->get('project_setting')['site_owner_id'];
    }

    public function updateLocatedDistId($siteOwnerId){
    	$user = $this->request->get('project_setting');
    	if($user['user_id']>0){
    		$userData=$this->request->get('project_user_setting')['user_data'];
    		$userData->setLocatedDistributorId($siteOwnerId);
    		$this->entityManager->persist($userData);
    		$this->entityManager->flush();
    	}
    }
    
    public function getDateJsFormat($data=null){
    	if ($data=="dateJsFormat") {
    		return 'MM/dd/yyyy';
    	} else {
    		$this->projectSetting = $this->request->get('project_setting');
    		return $this->projectSetting['date_format'];
    		//return 'm/d/Y';
    		//return 'd/m/Y';
    	}
    }    
    
    function getServiceContainer()
    {
    	return $this->serviceContainer;
    }
}

