<?php

namespace OfficeBrain\Bundle\SubShopBundle\Manager\Extended;

use OfficeBrain\Bundle\SubShopBundle\Manager\AbstractManager\SubShopThemeAbstract as SubShopThemeAbstract;
use Symfony\Component\HttpFoundation\File\File;
use OfficeBrain\Bundle\UserBundle\Entity\SignUpForm;

/**
 * @author OfficeBrain 4494 <info@officebrain.com>
 *
 * Description : Sub shop theme extended class
 **/
class SubShopThemeExtended extends SubShopThemeAbstract
{
    public function __construct($entityManager, $request, $cmsMenuManager, $paginatorManager, $subShopMediaUploadLocation,$brandsManager,$language,$bannerMastermanager,$bannerManager,$cmsPageManager,$subSiteAccessManager)
    {
        parent::__construct($entityManager, $request, $cmsMenuManager, $paginatorManager, $subShopMediaUploadLocation,$brandsManager,$language,$bannerMastermanager,$bannerManager,$cmsPageManager,$subSiteAccessManager);
    }

    public function __destruct()
    {
        parent::__destruct();
    }

    /**
     * @author Employee Id: 4494
     * Description : Set Subshop Theme.
     *
     * @param 1 : Subshop Theme object
     *
     * @return type : SubShop Theme Id.
     *
     * @throws Exception: Null
     **/
    public function setSubShopTheme($subShopTheme)
    {
        $subShopTheme->setCreatedUid($this->projectSetting['user_id']);
        $subShopTheme->setInstanceId($this->request->get('project_setting')['instance_id']);
        $subShopTheme->setInstanceType($this->request->get('project_setting')['instance_type']);
        $subShopTheme->setUpdatedAt(new \DateTime());
        $subShopTheme->setUpdatedUid($this->projectSetting['user_id']);

        return $this->repository->set($subShopTheme);
    }

    /**
     * @author Employee Id: 4494
     * Description : Get Subshop Theme.
     *
     * @param 1 :  SubShop Theme Id
     *
     * @return type :  Subshop Theme object.
     *
     * @throws Exception: Null
     **/
    public function getSubShopTheme($id)
    {
        $subShopTheme = $this->repository->find($id);

        if (!$subShopTheme) {
        }

        unset($id);

        return $subShopTheme;
    }

    /**
     * @author Employee Id: 4494
     * Description : Get Subshop Theme List.
     *
     * @param 1 :  No parameter
     *
     * @return type :  Subshop Theme List.
     *
     * @throws Exception: Null
     **/
    public function getSubShopThemeList()
    {
        return $this->repository->findAll();
    }

    /**
     * @author Employee Id: 4494
     * Description : Delete Subshop Theme.
     *
     * @param 1 :  SubShop Theme Id
     *
     * @return type :  Subshop Theme Id.
     *
     * @throws Exception: Null
     **/
    public function deleteSubShopTheme($id)
    {
        $currentDateTime = new \DateTime();
        $subShopTheme = $this->getSubShopTheme($id);
        $subShopTheme->setDeletedAt($currentDateTime = new \DateTime());

        $subShopTheme->setFolderName($subShopTheme->getFolderName().'_'.$currentDateTime->format('Y-m-d H:i:s'));

        $this->entityManager->getRepository('OfficeBrainThemeBundle:ThemeMaster')->delete($subShopTheme->getParentId());

        unset($id);
        unset($currentDateTime);

        return $this->setSubShopTheme($subShopTheme);
    }

    /**
     * @author Employee Id: 4494
     * Description : Revert Subshop Theme to active.
     *
     * @param 1 :  SubShop Theme Id
     *
     * @return type :  Subshop Theme Id.
     *
     * @throws Exception: Null
     **/
    public function revertSubShopTheme($id)
    {
        $subShopTheme = $this->getSubShopTheme($id);
        $subShopTheme->setDeletedAt(null);
        $subShopTheme->setStatus('1');

        unset($id);

        return $this->setSubShopTheme($subShopTheme);
    }

    /**
     * @author Employee Id: 4494
     * Description : Approve Subshop Theme to active.
     *
     * @param 1 :  SubShop Theme Id
     *
     * @return type :  Subshop Theme Id.
     *
     * @throws Exception: Null
     **/
    public function approveSubShopTheme($id)
    {
        $subShopTheme = $this->getSubShopTheme($id);
        $subShopTheme->setStatus('1');

        unset($id);

        return $this->setSubShopTheme($subShopTheme);
    }

    /**
     * @author Employee Id: 4494
     * Description : Reject Subshop Theme to active.
     *
     * @param 1 :  SubShop Theme Id
     *
     * @return type :  Subshop Theme Id.
     *
     * @throws Exception: Null
     **/
    public function rejectSubShopTheme($id)
    {
        $subShopTheme = $this->getSubShopTheme($id);
        $subShopTheme->setStatus('2');

        unset($id);

        return $this->setSubShopTheme($subShopTheme);
    }

    /**
     * @author Employee Id: 4494
     * Description : Onlold Subshop Theme to active.
     *
     * @param 1 :  SubShop Theme Id
     *
     * @return type :  Subshop Theme Id.
     *
     * @throws Exception: Null
     **/
    public function onHoldSubShopTheme($id)
    {
        $subShopTheme = $this->getSubShopTheme($id);
        $subShopTheme->setStatus('0');

        unset($id);

        return $this->setSubShopTheme($subShopTheme);
    }

    /**
     * @author Employee Id: 4494
     * Description : Search subshop theme list by status.
     *
     * @param 1 :  SubShop theme status
     *
     * @return type :  Subshop theme list.
     *
     * @throws Exception: Null
     **/
    public function searchByStatusSubShopTheme()
    {
        $statusId = $this->request->get('status_id');

        switch ($this->request->get('tab')) {
            case 'inactive_theme_list' :
                $statusId = '0';
                break;

            case 'active_theme_list' :
                $statusId = '1';
                break;

            case 'drafted_theme_list' :
                $statusId = '2';
                break;
        }

        $subShopThemeList = $this->repository->findByStatus($statusId);

        unset($statusId);

        return $this->paginatorManager->paginate($subShopThemeList, $this->request->get('page'), $this->recordsPerPage, array(), count($subShopThemeList));
    }

    /**
     * @author Employee Id: 4494
     * Description : Search subshop theme list by type.
     *
     * @param 1 :  SubShop theme status
     *
     * @return type :  Subshop theme list.
     *
     * @throws Exception: Null
     **/
    public function searchByTypeSubShopTheme($subshopThemeId = 0)
    {
        $type = $this->request->get('type');

        if ($type == 'all') {
            $subShopThemeList = $this->repository->findByStatus(1);
        } elseif ($type == 'active') {
            $subShopThemeList = array($this->repository->find($subshopThemeId));
        } else {
            $subShopThemeList = $this->repository->findByType($type);
        }
        //echo"<pre>";print_r($subShopThemeList);die;
        return $this->paginatorManager->paginate($subShopThemeList, $this->request->get('page'), $this->recordsPerPage, array(), count($subShopThemeList));
    }

    /**
     * @author Employee Id: 4494
     * Description : Search subshop theme list by delete.
     *
     * @param 1 :  No parameter
     *
     * @return type :  Subshop theme List.
     *
     * @throws Exception: Null
     **/
    public function searchByDeleteSubShopTheme()
    {
        $subShopThemeList = $this->repository->findByDelete();

        return $this->paginatorManager->paginate($subShopThemeList, $this->request->get('page'), $this->recordsPerPage, array(), count($subShopThemeList));
    }

    /**
     * @author Employee Id: 4494.
     * Description : Search Subshop Theme.
     *
     * @param 1 : No paramater
     *
     * @return type :Subshop Theme List.
     *
     * @throws Exception: Null.
     **/
    public function searchSubShopTheme()
    {
        $statusId = null;
        $tabStatus = array('inactive_theme_list' => 0, 'active_theme_list' => 1, 'drafted_theme_list' => 2);

        if (isset($tabStatus[$this->request->get('tab')])) {
            $statusId = $tabStatus[$this->request->get('tab')];
        }

        $subShopThemeList = $this->repository->findByOption($this->request->get('option'), $this->request->get('keyword'), $statusId);

        unset($statusId);
        unset($tabStatus);

        return $this->paginatorManager->paginate($subShopThemeList, $this->request->get('page'), $this->recordsPerPage, array(), count($subShopThemeList));
    }

    /**
     * @author Employee Id: 4494
     * Description : Set subshop theme design.
     *
     * @param 1 :  SubShop theme design
     *
     * @return type :  Subshop theme list.
     *
     * @throws Exception: Null
     **/
    public function setSubShopThemeDesign($subShopThemeDesign)
    {
        $this->subshopThemeDesignRepository->set($subShopThemeDesign);
    }

    /**
     * @author Employee Id: 4494
     * Description : Get subshop theme design.
     *
     * @param 1 :  SubShop id
     * @param 2 :  mode
     *
     * @return type :  Subshop theme design.
     *
     * @throws Exception: Null
     **/
    public function getSubShopThemeDesign($subShopId, $mode = null)
    {
        if ($mode == null) {
            $mode = $this->projectSetting['instance_theme_mode'];
        }

        return $this->subshopThemeDesignRepository->findByMode($subShopId, $mode);
    }

    /**
     * @author Employee Id: 4494
     * Description : Update subshop theme custom design.
     *
     * @param 1 :  mode
     *
     * @return type :  Subshop theme design.
     *
     * @throws Exception: Null
     **/
    public function updateSubShopThemeCustomDesing($mode = 'draft')
    {
        $data = array();
        $subShopthemeDesign = $this->getSubShopThemeDesign($this->request->get('subshop_id'), $mode);

        $data['customDesign'] = json_decode($subShopthemeDesign->getCustomDesign(), 'Array');

        if ($this->request->get('key') == 'no-key') {
            $data['customDesign']['autoSave'] = $this->request->get('save') == 'false' ? 0 : 1;
        } else {
            if ($this->request->get('key') == 'themeColor') {
                $data['customDesign'][$this->request->get('key')] = $this->request->get('value');
            } else {
                $data['customDesign']['themeColorSetting'][$this->request->get('CurrentThemeColor')][$this->request->get('key')] = $this->request->get('value');
            }
        }

        $data['customDesign'] = json_encode($data['customDesign']);

        $subShopthemeDesign->setCustomDesign($data['customDesign']);

        $this->setSubShopThemeDesign($subShopthemeDesign);

        unset($subShopthemeDesign);

        return json_decode($data['customDesign']);
    }

    /**
     * @author Employee Id: 4494
     * Description : Prepate subshop theme custom design.
     *
     * @param 1 :  Subshop theme id
     *
     * @return type :  Subshop theme design.
     *
     * @throws Exception: Null
     **/
    public function prepareSubShopThemeDesign($subShopThemeId = 0, $subshopId = 0, $subShopTheme = array())
    {
    	
        $customDesign = array();

        if ($subshopId == 0) {
            $subshopId = $this->request->get('subshop_id');
        }

        if ($subShopThemeId > 0) {
            $subShopTheme = $this->getSubShopTheme($subShopThemeId);
        }

        $subShopThemeDesign = $this->getSubShopThemeDesign($subshopId, 'draft');

        $customDesign = json_decode($subShopThemeDesign->getCustomDesign(), 'Array');

        if (!isset($customDesign['themeName'])) {
            $customDesign = $this->resetSubShopThemeDesign($subShopTheme, 1);

            $subShopThemeDesign->setCustomDesign(json_encode($customDesign));
            $this->setSubShopThemeDesign($subShopThemeDesign);
        }

        if ($customDesign['autoSave'] == 0 && $this->request->get('theme_id') <= 0) {
            $subShopPublishThemeDesign = $this->getSubShopThemeDesign($subshopId, 'publish');

            $customPublishDesign = json_decode($subShopPublishThemeDesign->getCustomDesign(), 'Array');

            if ($customPublishDesign) {
                $customDesign = $customPublishDesign;
                $customDesign['autoSave'] = 0;
            } else {
                $customDesign = $this->resetSubShopThemeDesign($subShopTheme, 0);
            }

            $subShopThemeDesign->setCustomDesign(json_encode($customDesign));
            $this->setSubShopThemeDesign($subShopThemeDesign);

            unset($subShopPublishThemeDesign);
        }

        unset($subShopTheme);
        unset($subShopThemeDesign);

        return $customDesign;
    }

    /**
     * @author Employee Id: 4494
     * Description : Update subshop theme custom image design.
     *
     * @param 1 :  image path
     * @param 2 :  mode
     *
     * @return type :  Subshop theme design.
     *
     * @throws Exception: Null
     **/
    public function updateSubShopThemeCustomImageDesing($mode = 'draft')
    {
        $file = $this->request->files->get('file');

        if (in_array($file->getMimeType(), array('image/jpeg', 'image/jpg', 'image/png', 'image/gif'))) {
            $originalFileName = time().'_'.$file->getClientOriginalName();

            if (!file_exists($this->subShopMediaUploadLocation['path'])) {
                mkdir($this->subShopMediaUploadLocation['path'], 0777, true);
            }

            $file->move($this->subShopMediaUploadLocation['path'], $originalFileName);

            $file = $this->request->getScheme().'://'.$this->request->getHttpHost().$this->request->getBasePath().$this->subShopMediaUploadLocation['url'].$originalFileName;

            return array('file' => $file, 'name' => $originalFileName);
        }
    }

    /**
     * @author Employee Id: 4494
     * Description : Set subshop theme custom design.
     *
     * @param 1 :  No paramater
     *
     * @return type :  Subshop theme id.
     *
     * @throws Exception: Null
     **/
    public function setSubShopThemeDesingStatus()
    {
        $subShopthemeDesign = $this->getSubShopThemeDesign($this->request->get('subshop_id'), 'draft');

        if ($this->request->get('action') == 'default') {
            $subShopthemeDesign->setCustomDesign(null);
        } elseif ($this->request->get('action') == 'publish') {
            $customDesign = $subShopthemeDesign->getCustomDesign();

            $subShopthemeDesign = $this->getSubShopThemeDesign($this->request->get('subshop_id'), 'publish');
            $subShopthemeDesign->setCustomDesign($customDesign);

            unset($customDesign);
        }

        return $this->setSubShopThemeDesign($subShopthemeDesign);
    }

    /**
     * @author Employee Id: 4494
     * Description : Set subshop theme color design.
     *
     * @param 1 :  Theme color list
     * @param 2 :  Subshop theme
     *
     * @return type :  Subshop theme id.
     *
     * @throws Exception: Null
     **/
    public function setSubShopThemeColor($themeColorList, $subShoptheme,$setImageName = '')
    {
        if (!in_array('default', $themeColorList)) {
            $themeColorList[] = 'default';
        }

        $themeColorList = array_unique($themeColorList);

        $themeColor = array('customize_elements' => array('logo_image','header_image','background_image','theme_colors','body_text_color','body_text_font_family','body_background_color','header_background_color','menu_background_color','menu_text_rollover_color','menu_text_color','button_background_color','button_background_rollover_color','button_text_background_color'));
        $themeColorAttributes = $this->entityManager->getRepository('OfficeBrainSubShopBundle:SubShopThemeColor')->findBySlugs($themeColorList);

        $themeColor['theme_colors'] = array();

        foreach ($themeColorAttributes as $item) {
            $colorAttributes = json_decode($item->getAttributes(), 'Array');

            if (isset($colorAttributes[$subShoptheme->getFolderName()])) {
                $colorAttributes = $colorAttributes[$subShoptheme->getFolderName()];
            }

            $themeColor['theme_colors'][$item->getSlug()] = $colorAttributes;
        }
        $subShoptheme->setThemeColor(json_encode($themeColor));

        if ($subShoptheme->getParentId() <= 0) {
            $subShoptheme->setParentId($this->entityManager->getRepository('OfficeBrainThemeBundle:ThemeMaster')->add(array('themeName' => $subShoptheme->getFolderName(), 'themeType' => 'sub_shop')));
        }
		if($subShoptheme->getThemeImageName() != '')
		{
       		 $subShoptheme = $this->setSubShopThemeImage($subShoptheme);
		}
		else{
			$subShoptheme->setThemeImageName($setImageName);
		}

        unset($themeColorList);
        unset($themeColor);

        return $this->setSubShopTheme($subShoptheme);
    }

    /**
     * @author Employee Id: 5058
     * Description : Set subshop theme Image.
     *
     * @param 1 :  Subshop theme
     *
     * @return type :  subShopTheme.
     *
     * @throws Exception: Null
     **/
    public function setSubShopThemeImage($subShopTheme)
    {
        $file = $subShopTheme->getThemeImageName();

        if ($file != '') {
            $originalFileName = time().'_'.$file->getClientOriginalName();
            $file->move($this->subShopMediaUploadLocation['path'], $originalFileName);
            $subShopTheme->setThemeImageName($originalFileName);

            unset($file);
            unset($originalFileName);
        }
        return $subShopTheme;
    }

    /**
     * @author Employee Id: 4494
     * Description : Set subshop theme color design.
     *
     * @param 1 :  Subshop theme
     * @param 2 :  auto save
     *
     * @return type :  Subshop theme design.
     *
     * @throws Exception: Null
     **/
    public function resetSubShopThemeDesign($subShopTheme, $autoSave)
    {
        $themeColor = json_decode($subShopTheme->getThemeColor(), 'Array');

        $customDesign['themeName'] = $subShopTheme->getFolderName();
        $customDesign['themeColor'] = 'default';
        $customDesign['autoSave'] = $autoSave;

        foreach ($themeColor['theme_colors'] as $key => $value) {
            $customDesign['themeColorSetting'][$key] = array(
                    'bodyTextColor' => $value['body_text_color'],
                    'bodyBackgroundColor' => $value['body_background_color'],
                    'bodyTextFontFamily' => $value['body_text_font_family'],
                    'headerBackgroundColor' => $value['header_background_color'],
                    'menuBackgroundColor' => $value['menu_background_color'],
                    'menuTextColor' => $value['menu_text_color'],
                    'menuTextRolloverColor' => $value['menu_text_rollover_color'],
                    'buttonBackgroundColor' => $value['button_background_color'],
                    'buttonBackgroundRolloverColor' => $value['button_background_rollover_color'],
                    'buttonTextBackgroundColor' => $value['button_text_background_color'],
            );

            if ($key == 'default') {
                $customDesign['themeColorSetting'][$key]['themeIconColor'] = $value['theme_icon_color'];
            }
        }

        unset($themeColor);

        return $customDesign;
    }

    public function initSubShopThemeDesign($subShopId)
    {
        $this->subshopThemeDesignRepository->add($subShopId, 'publish');
        $this->subshopThemeDesignRepository->add($subShopId, 'draft');
    }

    public function changeSubShopTheme($subshopId)
    {
        return $this->subshopThemeDesignRepository->resetBySubShopId($subshopId);
    }

    public function mediaLocation()
    {
        return $this->subShopMediaUploadLocation;
    }

    public function prepareSubShopThemeData($subShopThemeId = 0, $subShopInstanceId = 0, $subShopTheme = array())
    {
        $instanceThemeData = array('theme_area' => array());

        if ($subShopThemeId > 0) {
            $subShopTheme = $this->getSubShopTheme($subShopThemeId);
        }

        $subShopThemeData = json_decode($subShopTheme->getThemeData(), 'Array');

        if (isset($subShopThemeData['theme_area'])) {
            foreach ($subShopThemeData['theme_area'] as $key => $themeArea) {
                foreach ($themeArea as $value) {
                    $instanceThemeData['theme_area'][$key.'_'.$value.'_area'] = 1;
                }
            }

            $this->setSubShopInstanceKey('theme_area', json_encode($instanceThemeData['theme_area']), $subShopInstanceId);
        }

        if (isset($subShopThemeData['theme_data'])) {
            foreach ($subShopThemeData['theme_data'] as $key => $themeArea) {
            	if (is_array($themeArea) && count($themeArea) > 0) {
	                foreach ($themeArea as $id => $value) {
	                	$instanceThemeData['theme_data'][$key][$id] = $value;
	                }
            	}
            }
            
            $subShopDesignTheme = json_decode($subShopTheme->getThemeColor(), 'Array');

            if ($subShopDesignTheme) {
                $instanceThemeData['theme_data']['design'] = $subShopDesignTheme;
                $instanceThemeData['theme_data']['design']['current_theme_color'] = 'default';

                $customizeElements = array_flip($instanceThemeData['theme_data']['design']['customize_elements']);

                $currentThemeColor = $instanceThemeData['theme_data']['design']['theme_colors'][$instanceThemeData['theme_data']['design']['current_theme_color']];
                if (isset($currentThemeColor)) {
                    foreach ($currentThemeColor as $key => $val) {
                        if (isset($customizeElements[$key])) {
                            $customizeElements[$key] = $val;
                        }
                    }
                }

                $instanceThemeData['theme_data']['design']['customize_elements'] = $customizeElements;

                unset($currentThemeColor);
                unset($customizeElements);
            }
            
            $this->subSiteAccessManager->setSubSiteAccessRules($subShopInstanceId);
            
            if (isset($instanceThemeData['theme_data']['cms'])) {
                foreach ($instanceThemeData['theme_data']['cms'] as $key => $themeElements) {
                    foreach ($themeElements as $item) {
                        if (isset($instanceThemeData['theme_data'][$item])) {
                            if ($key == 'menu') {
                                $this->cmsMenuManager->create($item, $instanceThemeData['theme_data'][$item], $subShopInstanceId);
                            }
                        }
                    }
                    if($key == "our_brands"){
                    	$instanceThemeData['theme_data']['home_our_brands_area'] = $this->getBrandsForSubShop();
                    	//$this->getProductsForSubShop();
                    }
                    if($key == "banner"){
                    	$bannerTypeId = $this->bannerMastermanager->cmsSetBannerType($subShopInstanceId,$instanceThemeData['theme_data']['home_banner_area']);
                    	if($bannerTypeId != ""){
                    		$this->bannerManager->cmsSetBanner($subShopInstanceId,$bannerTypeId,$instanceThemeData['theme_data']['home_banner_area']);
                    	}
                    }
                    if($key == "static_page"){
                    	foreach ($themeElements as $item) {
                    		if (isset($instanceThemeData['theme_data'][$item])) {
                    			if ($key == 'static_page') {
                    				$instanceThemeData['theme_data'][$item]['content'] = preg_replace('/images/', $this->request->getScheme().'://'.$this->request->getHttpHost().$this->request->getBasePath().$this->subShopMediaUploadLocation['url'], $instanceThemeData['theme_data'][$item]['content']);
                    				$cmsPageId = $this->cmsPageManager->cmsSetStaticPage($subShopInstanceId,$instanceThemeData['theme_data'][$item],$this->request->get('project_setting')['instance_type']);
                    				$instanceThemeData['theme_data'][$item]['content'] = '';
                    			}
                    		}
                    	}
                    }
                }
            }
            
            $this->setSubShopInstanceKey('theme_data', json_encode($instanceThemeData['theme_data']), $subShopInstanceId);

            if (isset($subShopThemeData['theme_data']['user_register_form']) || (isset($subShopThemeData['theme_data']['website_admin_dashboard']) && $subShopThemeData['theme_data']['website_admin_dashboard'] == '1')) {
            	$instanceMaster = $this->entityManager->getRepository('OfficeBrainAccessManagementBundle:InstanceMaster')->find($subShopInstanceId);
            }

            if (isset($subShopThemeData['theme_data']['user_register_form'])) {
            	$signUpFormRepository = $this->entityManager->getRepository('OfficeBrainUserBundle:SignUpForm');
            	$userSignUpForm = $signUpFormRepository->getSignUpForm($subShopThemeData['theme_data']['user_register_form']); 

            	if (count($userSignUpForm)) {
            		$signUpForm = new SignUpForm();
            		$signUpForm->setUserType($subShopThemeData['theme_data']['user_register_form']);
            		$signUpForm->setFields(json_encode($userSignUpForm['fields']));
            		$signUpForm->setUniqueKeys(implode(',', $userSignUpForm['unique_keys']));
            		$signUpForm->setValidations(implode(',', $userSignUpForm['validations']));
            		$signUpForm->setApprovalConfiguration(json_encode($userSignUpForm['approval_configuration']));
            		$signUpForm->setInstanceType($instanceMaster->getInstanceType());
            		$signUpForm->setInstanceTypeId($subShopInstanceId);
            		$signUpForm->setCreatedAt(new \DateTime());
            		$signUpForm->setUpdatedAt(new \DateTime());

            		$signUpFormRepository->set($signUpForm);
            	}
            }
            
            if (isset($subShopThemeData['theme_data']['website_admin_dashboard'])) {
            	$userRepository = $this->entityManager->getRepository('OfficeBrainUserBundle:User');

            	$checkUserexist = $userRepository->getInstanceUserById($instanceMaster->getOwnerId(), $subShopInstanceId);

            	if (count($checkUserexist) == 0) {
            		$user = $userRepository->getUserById($instanceMaster->getOwnerId());

            		if (count($user) > 0) {
            			$newUser = $userRepository->cloneUser($user);

            			$instanceMaster->setOwnerId($newUser->getId());
            			$this->entityManager->getRepository('OfficeBrainAccessManagementBundle:InstanceMaster')->set($instanceMaster);

            			$newUser->setParent($user);
            			$newUser->setInstanceId($subShopInstanceId);
            			$newUser->setInstanceType($instanceMaster->getInstanceType());
            			$newUser->setUserType($subShopThemeData['theme_data']['website_admin_dashboard']['user_type']);
            			$newUser->setCreatedAt(new \DateTime());
            			$userRepository->set($newUser);
            		}	
            	}
            }
        }

        unset($instanceThemeData);
    }

    public function addSubShopInstanceKey($key, $value = null, $instanceId = 0)
    {
    	return $this->subShopInstanceMetaRepository->add($key, $value, $instanceId);
    }

    public function newThenAddElseSetSubShopInstanceKey($key, $value = null, $instanceId = 0)
    {
        $subShopInstanceMeta = $this->getSubShopInstanceKey($key, $instanceId);

        if (!empty($subShopInstanceMeta)) {
            $subShopInstanceMeta->setMetaValue($value);

            return $this->subShopInstanceMetaRepository->set($subShopInstanceMeta);
        }
        else
        {
        	return $this->addSubShopInstanceKey($key, $value, $instanceId);
        }

        return false;
    }

    public function setSubShopInstanceKey($key, $value = null, $instanceId = 0)
    {
        $subShopInstanceMeta = $this->getSubShopInstanceKey($key, $instanceId);

        if (count($subShopInstanceMeta) > 0) {
            $subShopInstanceMeta->setMetaValue($value);

            return $this->subShopInstanceMetaRepository->set($subShopInstanceMeta);
        }

        return false;
    }

    public function getSubShopInstanceKey($key, $instanceId = 0)
    {
        return $this->subShopInstanceMetaRepository->findByMetaKey($key, $instanceId);
    }

    public function updateSubShopInstanceKey($subShopInstanceMeta)
    {
        return $this->subShopInstanceMetaRepository->set($subShopInstanceMeta);
    }

    public function getSubShopThemeMeta($instanceId)
    {
        $data = array('theme_area' => array(), 'theme_data' => array(), 'token' => $this->request->get('stoken'));

        $subShopInstanceMeta = $this->getSubShopInstanceKey('theme_area', $instanceId);

        if ($subShopInstanceMeta) {
            $data['theme_area'] = json_decode($subShopInstanceMeta->getMetaValue(), 'array');
        }

        $subShopInstanceMeta = $this->getSubShopInstanceKey('theme_data', $instanceId);

        if ($subShopInstanceMeta) {
            $data['theme_data'] = json_decode($subShopInstanceMeta->getMetaValue(), 'array');
        }

        return $data;
    }

    public function updateSubShopThemeMeta($instanceId)
    {
        $design = $this->request->get('design');

        $subShopInstanceMeta = $this->getSubShopInstanceKey('theme_area', $instanceId);

        if ($subShopInstanceMeta) {
            $themeArea = json_decode($subShopInstanceMeta->getMetaValue(), 'array');

            foreach ($themeArea as $area => $val) {
                if (isset($design['theme_area'][$area])) {
                    $themeArea[$area] = $design['theme_area'][$area];
                }
            }

            $subShopInstanceMeta->setMetaValue(json_encode($themeArea));
            $this->updateSubShopInstanceKey($subShopInstanceMeta);
        }

        if (isset($design['theme_data']) && count($design['theme_data'])) {
            $subShopInstanceMeta = $this->getSubShopInstanceKey('theme_data', $instanceId);

            if ($subShopInstanceMeta) {
                $themeData = json_decode($subShopInstanceMeta->getMetaValue(), 'array');

                foreach ($themeData as $area => $data) {
                    foreach ($data as $key => $value) {
                        if (isset($design['theme_data'][$area][$key])) {
                            $themeData[$area][$key] = $design['theme_data'][$area][$key];
                        }
                    }

                    if (isset($design['theme_data'][$area]['style'])) {
                        $themeData[$area]['style'] = $design['theme_data'][$area]['style'];
                    }
                }
                if(isset($design['theme_data']['css']['custom_css'])){
                	$themeData['css']['custom_css'] = $design['theme_data']['css']['custom_css'];
                }
                
                $subShopInstanceMeta->setMetaValue(json_encode($themeData));
                $this->updateSubShopInstanceKey($subShopInstanceMeta);
            }
        }

        return true;
    }
    
    public function getBrandsForSubShop()
    {
    	$culture = array();
    	$data = array();
    	foreach($this->language as $key=>$value){
    		$culture[] = $key;
    	}
    	
    	$brandData = $this->brandService->getList($culture,array());
    	foreach($brandData as $key=>$value){
    		foreach($value as $k=>$v){
    			$data[$key][] = $k;
    		}
    	}
    	return $data;
    	
    }
    public function getProductsForSubShop()
    {
    	
    }
}
