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

use OfficeBrain\Bundle\HomeSectionBundle\Manager\AbstractManager\HomeSectionAbstract as HomeSectionAbstract;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
use OfficeBrain\Bundle\HomeSectionBundle\Entity\HomeSection;

/**
 *
 * @author OfficeBrain 4571 <info@officebrain.com>
 *
 * Description : Extended class
 *
 */
class HomeSectionExtended extends HomeSectionAbstract
{
    /**
     *
     * @author Employee Id: 4571
     * Description : Set variables
     *
     * @param 1:  $entityManager
     * @param 2:  $request
     * @param 3:  $translator
     * @param 4:  $knpPaginator
     * @param 6:  $bannerImgPath
     *
     * @return null
     *
     * @throws null
     *
     **/
    public function __construct($entityManager, $request, $translator, $knpPaginator, $bannerImagePath, $subShopImagePath)
    {
        parent::__construct($entityManager, $request, $translator, $knpPaginator, $bannerImagePath, $subShopImagePath);
    }
    
    /**
     *
     * @author Employee Id: 4571
     * Description : Unset variables
     *
     * @param : null
     *
     * @return null
     *
     * @throws null
     *
     **/
    public function __destruct()
    {
        parent::__destruct();
    }

        
    
    /**
     * @author Employee Id: 4571
     * Description : Fetching id wise repository details
     *
     * @param $id
     *
     * @return result
     *
     * @throws null
     *
     **/
    public function getHomeSection($id)
    {
        return $this->homeSectionRepository->find($id);
        
    }
        
    /**
     * @author Employee Id: 4571
     * Description : Get homeSection List
     *
     * @param null
     *
     * @return Data Array
     *
     * @throws null
     *
     **/
    public function getHomeSectionList($keywords, $page,$recordsPerPage)
    {
    	return $this->homeSectionRepository->getHomeSectionList($keywords, $page,$recordsPerPage)
    ;
    }

    /**
     * @author Employee Id: 4571
     * Description : Get homeSection List
     *
     * @param null
     *
     * @return Data Array
     *
     * @throws null
     *
     **/
    public function getFunpromoSectionList($keywords, $page,$recordsPerPage)
    {
        return $this->homeSectionRepository->getFunpromoSectionList($keywords, $page,$recordsPerPage)
    ;
    }
    
    /**
     * @author Employee Id: 4571
     * Description : Get homeSection List
     *
     * @param null
     *
     * @return Data Array
     *
     * @throws null
     *
     **/
    public function setListPosition($homeSection, $pos, $id)
    {
        $homeSection= $this->getHomeSection($id);
        $homeSection->setSortPosition($pos);
        $this->homeSectionRepository->set($homeSection);
        $this->entityManager->flush();
    }
    
    /**
     * @author Employee Id: 4571
     * Description : Get Banner List
     *
     * @param null
     *
     * @return Data Array
     *
     * @throws null
     *
     **/
    public function getBannerListAjax()
    {
        $bannerArray = array();
        $bannerResults = array();
        $param = $this->request->get('_route_params');
        $page = $param['page'];
        $records_per_page = $param['records_per_page'];        
        $startDate = '';
        $endDate = '';
        $countryCode = $this->request->get('country_code');
        if (isset($countryCode) && $countryCode != "")
        	$this->cultureAjax = $this->request->get('country_code');
        
        $searchWord=trim($this->request->get('banner_search_query'));
        if (!empty($this->request->get('start_date'))) {
            $startDate =  date_format(new \DateTime($this->request->get('start_date')), 'Y-m-d H:i:s');
        }
        if (!empty($this->request->get('end_date'))) {
            $endDate =  date_format(new \DateTime($this->request->get('end_date')), 'Y-m-d H:i:s');
        }
        
        $this->getCultureValueAjax();
         
        if ($this->countryCode) {
            $this->countryId = $this->getCountryIdByCode($this->countryCode);
        }
    
        if ($this->languageCode) {
            $this->languageId = $this->getLanguageIdByCode($this->languageCode);
        }
        $bannerArray = $this->homeSectionRepository->getBannerList($this->countryId, $this->languageId, $searchWord, $startDate, $endDate, $page, $records_per_page); //   old
        
        
        $this->responseArray['pagination']=$bannerArray;
        $this->responseArray['records_per_page'] = $records_per_page;
        $this->responseArray['page'] = $page;
        $this->responseArray['culture'] = $this->culture;
        $this->responseArray['languageCode'] = $this->languageCode;
        $this->responseArray['countryCode'] = $this->countryCode;

        return $this->responseArray;
    }
    
    
            
    /**
     * @author Employee Id: 4571
     * Description : Set Banner
     *
     * @param Object $banner
     *
     * @return object
     *
     * @throws null
     *
     **/
    public function setHomeSection($section)
    {
        return $this->homeSectionRepository->saveSection($section);
    }
    
    public function getHomeSectionByType($section){
		return $this->homeSectionRepository->getHomeSectionByType($section);
	}
	
    /**
     * @author Employee Id: 4571
     * Description : Update Banner
     *
     * @param $banner, $positon, $id
     *
     * @return object
     *
     * @throws null
     *
     **/
    public function updateSection($section,$homeSection)
    {
		return $this->homeSectionRepository->saveSection($section,$homeSection);
    }
    
    /**
     * @author Employee Id: 4571
     * Description : Search Banner Type
     *
     * @param $searchWord
     *
     * @return object
     *
     * @throws null
     *
     **/
    public function searchBannerType($searchWord)
    {
        return $this->bannerRepository->searchByName($searchWord);
    }
    
    /**
     * @author Employee Id: 4571
     * Description : Check if valid image is uploaded
     *
     * @param 1: Object $form, $img, $banner
     *
     * @return object
     *
     * @throws null
     */
    public function isValidUpload($form, $img, $banner)
    {
        $allowedExt = array("jpg","jpeg","png","gif","tiff","JPG","JPEG","PNG","GIF","TIFF");
        $assignedImgSize = $form->getData()->getBannerTypeId()->getImageSize(); // master table allowed image
        
        $errFlag=false;
        $ext = $img->getClientOriginalExtension();
        $uploadedImgsize = $img->getClientSize();
        $check =  $this->formatSizeUnits($uploadedImgsize); // mb or kb
        $checkExp = explode("~", $check);
        
//        if ($checkExp[1]=="MB") { // size validation
//            if ($checkExp[0] > $assignedImgSize) {
//                // throw error
//                $errors =  $this->translator->trans('bannertype.header.form.banner_err1');
//                $errFlag=true;
//            }
//        }
         
        if (!in_array($ext, $allowedExt)) { // throw error
            $errors =  $this->translator->trans('bannertype.header.form.banner_err2');
            $errFlag = true;
        }
         
        if ($errFlag) {
            return $this->responseArray['IS_NOT_VALID_IMG']=$errors;
            //return $data;
        }
    }
    
    /**
     * @author Employee Id: 4571
     * Description : get image size in units like mb or in kb or in gb ..
     *
     * @param $bytes
     *
     * @return $bytes
     * @throws null
     *
     */
    public function formatSizeUnits($bytes)
    {
        if ($bytes >= 1073741824) {
            $bytes = number_format($bytes / 1073741824, 2) . '~GB';
        } elseif ($bytes >= 1048576) {
            $bytes = number_format($bytes / 1048576, 2) . '~MB';
        } elseif ($bytes >= 1024) {
            $bytes = number_format($bytes / 1000, 2) . '~KB';
        } elseif ($bytes > 1) {
            $bytes = $bytes . ' bytes';
        } elseif ($bytes == 1) {
            $bytes = $bytes . ' byte';
        } else {
            $bytes = '0 bytes';
        }
    
        return $bytes;
    }
    
        
    /**
     * @author Employee Id: 4571
     * Description : get banner for Home page
     *
     * @param : null
     *
     * @return object
     *
     * @throws null
     *
     **/
    public function fetchActiveBanner()
    {
       $displayOn = $this->request->get('displayOn');
        //$culture= $this->request->get('culture');
        $searchQuery = $this->request->get('searchQuery');
       $categoryFilter = $this->request->get('categoryFilter');
       $slug =  $this->request->get('slug');
        if ($searchQuery == "blank") {
            $searchQuery="";
        }
      if ($this->countryCode) {
            $this->countryId = $this->getCountryIdByCode($this->countryCode);
        }
         
        if ($this->languageCode) {
            $this->languageId = $this->getLanguageIdByCode($this->languageCode);
        }
        
        $this->responseArray = $this->bannerMasterRepository->findBannerByCategory($this->countryId, $this->languageId, $displayOn, $searchQuery, $categoryFilter, $slug);
        
        foreach ($this->responseArray as $key=>$value) {
            $this->responseArray[$key]['bannerHtml'] = (array) json_decode($value['bannerHtml'], true);
        }
               
        return $this->responseArray;
    }

    /**
     * @author Employee Id: 4571
     * Description : Load Banner Transition
     *
     * @param : null
     *
     * @return result
     *
     * @throws null
     *
     **/
    public function findBannerTransition($display)
    {
        if ($this->countryCode) {
            $this->countryId = $this->getCountryIdByCode($this->countryCode);
        }
            
        if ($this->languageCode) {
            $this->languageId = $this->getLanguageIdByCode($this->languageCode);
        }
    
        //return $this->bannerRepository->findHomeBannerTransition($this->countryId, $this->languageId);
        return $this->bannerMasterRepository->findBannerByCategory($this->countryId, $this->languageId, $display);
    }
    
    /**
     * @author Employee Id: 4571
     * Description : load language wise collection
     *
     * @param 1 : banner object
     *
     * @return banner object
     *
     * @throws null
     *
     **/
    public function getLanguage($banner)
    {
        $language = $this->languages;
        foreach ($language as $key => $value) {
            $langid = $value['id'];
            $bannerLang = new BannerLanguage();
            $bannerLang->setLanguageId($langid);           
            $banner->getBannerLanguage()[] = $bannerLang;              
        }         
        return $banner;
    }
    
    /**
     * @author Employee Id: 4571
     * Description : Get language in Edit
     *
     * @param 1 : object $banner
     *
     * @return object
     *
     * @throws null
     *
     **/
    public function getLanguageEdit($banner)
    {
        foreach ($this->countries as $key => $value) {
            $culture[$key]['id'] = $value['id'];
            $culture[$key]['lang'] = $value['language'];
            $culture[$key]['short_name'] = $value['short_name'];
        }
            
        $bannerLang = $banner->getBannerLanguage();
        foreach ($bannerLang as $key=>$val) {
            $banner->getBannerLanguage()[] = $val;
        }
            
        return $banner;
    }
    
    /**
     * @author Employee Id: 4571
     * Description : load Country wise collection
     *
     * @param : null
     *
     * @return banner object
     *
     * @throws null
     *
     **/
    
    public function getCountry()
    {
        $countryConfiguration=array();
        
        foreach ($this->countries as $key=>$value) {
            $countryConfiguration[$value['id']]=$value['name']; // short_name
        }
        
        return $countryConfiguration;
    }
    
    /**
     * @author Employee Id: 4571
     * Description : Filter Form data
     *
     * @param 1 : null
     *
     * @return object
     *
     * @throws null
     *
     **/
    public function filterFormData($form)
    {
        $bannerGroup = $form->getData();
        $countryId = $bannerGroup->getCountryId();
                      
        if ($countryId) {
            $countryCode = $this->getCountryField($countryId, 'id', 'code');
            foreach ($bannerGroup->getBannerLanguage() as $index=>$language) {
                if (!in_array($language->getLanguageId(), $this->countries[$countryCode]["language"])) {
                    unset($bannerGroup->getBannerLanguage()[$index]); // $language->getLanguageId()
                }
            }
        }
    
        return $form;
    }
    
    /**
     * @author Employee Id: 4571
     * Description : Get country field
     *
     * @param 1 : $culture
     * @param 2 : String Search Field
     * @param 3:  string key
     *
     * @return object
     *
     * @throws null
     *
     **/
    public function getCountryField($culture, $searchField, $returnField)
    {
        foreach ($this->countries as $key => $country) {
            if ($culture == $country[$searchField]) {
                if ($returnField != 'code') {
                    return $country[$returnField];
                } else {
                    return $key;
                }
            }
        }
    }
    
    /**
     * @author Employee Id: 4571
     * Description : get culture code
     *
     * @param 1 : string $cultureCode
     *
     * @return int $countryId
     *
     * @throws null
     *
     * */
    public function getCountryIdByCode($cultureCode)
    {
        $countries = $this->countries;
        foreach ($countries as $key => $country) {
            if ($cultureCode == $country['short_name']) {  // $country['short_name'] // $key
                return $country['id'];
            }
        }
    }
    
    /**
     * @author Employee Id: 4571
     * Description : Get Language id by Code
     *
     * @param 1 : string $languageCode
     *
     * @return lang id
     *
     * @throws null
     *
     **/
    public function getLanguageIdByCode($languageCode)
    {
        foreach ($this->languages as $key => $lan) {
            if ($languageCode == $key) {
                return $lan['id'];
            }
        }
    }
     
    /**
     * @author Employee Id: 4571
     * Description : Make a Copy of Banner from Object
     *
     * @param 1: obj $banner1,
     * @param 2: int $countryId
     * @param 3: int $isActive
     *
     * @return object
     *
     * @throws null
     *
     **/
    public function makeCopyBannerGroup($banner1, $countryId, $isActive)
    {
      
        if ($countryId) {
            $banner1->setStatus($isActive);
            $banner1->setCountryId($countryId);
            if($this->request->get('instance_id') > 0)
            {
                
            }
            $countryCode = $this->getCountryField($countryId, 'id', 'code');
            $bannerName = "Copy of " . $banner1->getBannerName();
            $banner1->setBannerName($bannerName);
            $copiedLang = array();
            
            foreach ($banner1->getBannerLanguage() as $langMap) {
                $banner1->removeBannerLanguage($langMap);
            }
            
            foreach ($this->countries[$countryCode]["language"] as $languageId) {
                $lang = new BannerLanguage();
                $lang->setLanguageId($languageId);                 
                $lang->setBannerId($banner1);
                $banner1->addBannerLanguage($lang);
            }
            $this->bannerRepository->set($banner1);
        }
    }
    
    /**
     * @author Employee Id: 4571
     * Description : Make a copy manage from list view
     *
     * @param null
     *
     * @return true/false
     *
     * @throws null
     *
     **/
    public function copyBannerGroup()
    {
        $id = $this->request->get("banner_group_id");
            
        if ($id) {
            $bannerGroup = $this->getBanner($id);
            if ($bannerGroup) {
                $make_copy_country = $this->request->request->get('make_copy_country');
                $make_copy_status = $this->request->request->get('make_copy_status');
    
                foreach ($make_copy_country as $countryId=>$value) {
                    if (isset($make_copy_status[$countryId])) {
                        $this->makeCopyBannerGroup(clone $bannerGroup, $countryId, true);
                    } else {
                        $this->makeCopyBannerGroup(clone $bannerGroup, $countryId, false);
                    }
                }
                // commit persist objects if any
                $this->entityManager->flush();
            }
            return true;
        }
    
        return false;
    }
    
    /**
     * @author Employee Id: 4571
     * Description : get banner details
     *
     * @param null
     *
     * @return result
     *
     * @throws null
     *
     **/
    public function getBannerDetails()
    {
        $id = $this->request->get("banner_id");
                
        if ($id) {
            return $this->bannerRepository->findBannerDetails($id);
        }
    }
    
    /**
     * @author Employee Id: 4571
     * Description : Delete banner
     *
     * @param1: int $id
     *
     * @return object
     *
     * @throws null
     */
    public function deleteBanner($id)
    {
        return $this->bannerRepository->deleteBanners($id, $this->projectSetting['user_id']);
    }
    
    /**
     * @author Employee Id: 4571
     * Description : Delete Banner
     *
     * @param null
     *
     * @return array
     *
     * @throws null
     *
     **/
    public function deleteBannerAjax()
    {
        $id = $this->request->get("banner_id");
        
        if ($id) {
            return $this->bannerRepository->deleteBanners($id, $this->projectSetting['user_id']);
        }
    }
    
    /**
     *
     * @author Employee Id: 4571
     * Description : function to handle image upload
     *
     * @param 1 : type image
     *
     * @return thumbimage name
     *
     * @throws null
     *
     * @return $image
     *
     **/
    public function handleImageUpload($img)
    {
        $thumbimage = 'thumb_'.sha1(time().$img->getClientOriginalName());
        $extension = $img->getClientOriginalExtension();
        $directory =  $this->bannerImgPath; //$this->container->getParameter('banner.image_path');
        $img->move($directory, $thumbimage.'.'.$extension);
        $thumbimage = $thumbimage.'.'.$extension;
         
        return $thumbimage;
    }
    
    /**
     *
     * @author Employee Id: 4835
     * Description : function to get banner details and save in mongoDB.
     *
     * @param 1 : service
     *
     * @param id for getting banner details
     *
     * @return banner url
     *
     * @throws null
     *
     *
     **/
    public function fetchBannerDetail($bannerServiceLog, $bannerId)
    {
        $bannerObj=$this->bannerRepository->findbannerDetailFromId($bannerId);
           
        if ($bannerObj) {
            $bannerCriteria=array("bannerId"=>$bannerObj->getId(),
                                  "bannerType"=>$bannerObj->getBannerTypeId()->getId(),
                                  "bannerCategoryId"=>$bannerObj->getBannerTypeId()->getCategoryId(),
                                  "bannerProductId"=>$bannerObj->getBannerTypeId()->getProductId(),
                                  "bannerKeyword"=>$bannerObj->getBannerTypeId()->getKeywords(),
                                  "bannerName"=>$bannerObj->getBannerName(),
                                  "bannerViewOn"=>$bannerObj->getInstanceType());
            
            $bannerServiceLog->setKeywordBannerLog($this->request, $bannerCriteria);
        }
        
        return $bannerObj->getBannerUrl();
    }
    
    /**
     *
     * @author Employee Id: 4505
     * Description : function to get style of Banner
     *
     * @param 1 : type image
     *
     * @return thumbimage name
     *
     * @throws null
     *
     * @return json
     *
     **/
    public function getStyleOfBanner()
    {
        $bannerId = $this->request->get("banner_id");
        
        if (isset($bannerId) && intval($bannerId)>0) {
            //  $typeId = $this->request->get("type_id");
            //  $bannerTypeRepository = $this->entityManager->getRepository('OfficeBrainBannerBundle:BannerMaster');
            //  $typeId = $bannerTypeRepository->find($typeId);
        
            $result = $this->bannerRepository->findStyleOfBanner($bannerId);
            
           // var_dump($result);exit;
            return $result;
        }
         
        return json_encode(array());
    }
    
    /**
     *
     * @author Employee Id: 4505
     * Description : function to get Banner Preview
     *
     * @param 1 : type image
     *
     * @return thumbimage name
     *
     * @throws null
     *
     * @return json
     *
     **/
    public function getBannerPreview()
    {
        $request = $this->request->get("request_data");
        $bannerImage = $this->request->get("banner_img");
        $bannerEffect = $this->request->get("banner_effect");
        
        return array('result'=>$request,'banner_img'=>$bannerImage,'banner_effect'=>$bannerEffect);
    }
    

    public function changeStatus($id)
    {
    	return $this->bannerRepository->changeStatus($id);
    }
    
        public function uploadBannerImage()
    {
            $file = $this->request->files->get('file');

            if (in_array($file->getMimeType(), array('image/jpeg', 'image/jpg', 'image/png', 'image/gif'))) {
                $originalFileName = 'thumb_'.sha1(time().$file->getClientOriginalName());
                $extension = $file->getClientOriginalExtension();       
                $originalFileName = $originalFileName.'.'.$extension;
         
                if (!file_exists($this->bannerImgPath)) {
                    mkdir($this->bannerImgPath, 0777, true);
                }

                $file->move($this->bannerImgPath, $originalFileName);
                return array('file' => $originalFileName);
            } else {
                return 'INVALID_FILE';
            }     
    }
    
    /**
     * @author Employee Id: 4465
     * Description : Set default Banner for CMS Banner when new subshop created
     *
     * @param $id
     *
     * @return object
     *
     * @throws null
     *
     **/
    public function cmsSetBanner($instanceId,$bannerTypeId,$bannerArray)
    {
    	
    	$uploadedBanner = $bannerArray['image'] ? $bannerArray['image'] : "thumb_default_banner_image.jpg";
    	$effect = 1;
    	$bannerName = $bannerArray['name'] ? $bannerArray['name'] : "Default Banner";
    	$bannerHtml = array();
		for($i=1;$i<=5;$i++){
			$bannerHtml['html'.$i] = "";
		}
    	$bannerHtml = json_encode($bannerHtml);
    	$instanceMaster = $this->entityManager->getRepository('OfficeBrainAccessManagementBundle:InstanceMaster')->find($instanceId);
    	foreach($this->countries as $country)
    	{
    		$countryId = $country['id'];
	    	$banner = new Banner();
	    	$banner->setCountryId($countryId);
	    	$banner->setBannerTypeId($this->entityManager->getRepository('OfficeBrainBannerBundle:BannerMaster')->find($bannerTypeId));
	    	$banner->setUploadedBanner($uploadedBanner);
	    	$banner->setScheduleStartDate(null);
	    	$banner->setScheduleEndDate(null);
	    	$banner->setEffect($effect);
	    	$banner->setStatus(1);
	    	$banner->setCreatedUid($this->projectSetting['user_id']);
	    	$banner->setUpdatedUid($this->projectSetting['user_id']);
	    	$banner->setCreatedAt(new \DateTime());
	    	$banner->setUpdatedAt(new \DateTime());
	    	$banner->setDeletedUid(null);
	    	$banner->setDeletedAt(null);
	    	$banner->setInstanceId($instanceId);
	    	$banner->setInstanceType($instanceMaster->getInstanceType());
	    	$banner->setSortPosition(null);
	    	$banner->setBannerName($bannerName);
	    	$banner->setBannerUrl(null);
	    	$banner->setBannerHtml($bannerHtml);
	    	$banner->setHtml1effect('L');
	    	$banner->setHtml2effect('L');
	    	$banner->setHtml3effect('L');
	    	$banner->setHtml4effect('L');
	    	$banner->setHtml5effect('L');
	    	$banner->setMobileAppSetting(null);
	    	$banner->setHtmlId(null);
	    	$banner->setVisibility(1);
	    	
	    	$this->bannerRepository->set($banner);
        	$this->entityManager->flush();
	    	
	    	$BannerId = $banner->getId();
	    	
	    	$bannerLanguage = new BannerLanguage();
	    	$bannerLanguage->setLanguageId(1);
	    	$bannerLanguage->setAltTags(null);
	    	$bannerLanguage->setBannerTitle(null);
	    	$bannerLanguage->setBannerHtml1(null);
	    	$bannerLanguage->setBannerHtml2(null);
	    	$bannerLanguage->setBannerHtml3(null);
	    	$bannerLanguage->setBannerHtml4(null);
	    	$bannerLanguage->setBannerHtml5(null);
	    	$bannerLanguage->setBannerId($this->entityManager->getRepository('OfficeBrainBannerBundle:Banner')->find($BannerId));
	    	
	    	$this->bannerLanguageRepository->set($bannerLanguage);
	    	$this->entityManager->flush();

	    	if(!file_exists($this->bannerImgPath.$uploadedBanner)){
	    		copy($this->subShopImagePath['path'].$uploadedBanner,$this->bannerImgPath.$uploadedBanner);
	    	}
    	}
    	
    }
    
	/**
     * @author Employee Id: 410175
     * Description : get Mobile APP banner for Home page
     *
     * @param : null
     *
     * @return object
     *
     * @throws null
     *
     **/
    public function fetchActiveMobileApiBanner($bannerTypeId,$bannerBaseUrl='')
    {
       $countryId = $this->request->get('countryId',null);
        
        $bannerList= $this->bannerMasterRepository->getActiveBannerListMobileAPI($bannerTypeId,$countryId);
        
     	$newBannerList = array();
        foreach ($bannerList as $key=>$banner){
        	$newBannerList [$key] = $banner;
        	$newBannerList [$key]['uploadedBanner'] = $bannerBaseUrl.$banner['uploadedBanner'];
        	$newBannerList [$key]['mobileAppSetting'] = json_decode($banner['mobileAppSetting'],true);
        }
		$this->responseArray = $newBannerList; 
        return $this->responseArray;
    }
}
