<?php

namespace OfficeBrain\Bundle\ProductBundle\Manager\Extended;

use Symfony\Component\HttpFoundation\Request;
use OfficeBrain\Bundle\ProductBundle\Manager\AbstractManager\ProductAbstract;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Cookie;
use Doctrine\ORM\EntityManager;

class ProductApiExtended extends ProductAbstract
{
    protected $request;
    protected $productApi;
    protected $serviceContainer;
    protected $productBreadCrumbArray;
    protected $flag;
    protected $paginatorManager;
   
    public function __construct($request, $productApi, $serviceContainer, $commonLibraryManager, $entityManager)
    {
    	parent::__construct($request, $productApi, $serviceContainer, $commonLibraryManager, $entityManager);
    	
        $this->noOfRecord = $this->projectSetting['configuration_rule']['search']['product_detail']['recently_viewed_product']['option']['no_of_records'];
    }
    /**
     * @author Employee Id: 4014
     * Description : To get product details from API
     *
     * @param string $productSlug
     * @param string $culture
     *
     * @return array
     *
     * @throws Exception   
     *
     **/
    public function getProductDetailBySlug($productSlug, $culture)
    {
        $this->productApi->init('view_product');
        $this->productApi->setCallParameters(array('product_slug'=>$productSlug));        
        $this->productApi->setCulture($culture);
        $this->productApi->doProcess();
        if ($this->productApi->isSuccess()) {
            return $this->productApi->getResultArray();
        }
        return array();
    }



    /**
     * @author Employee Id: 5633
     *
     * Description: This Function Used For fetching product_id from sku
     *
     * @param array $productSku
     *
     * @return integer
     */
    public function getProductDetailsBySku($productSku)
    {
    	$searchManager = $this->serviceContainer->get('office_brain_search_manager');
    	$this->request->query->set('sku',$productSku);
    	$searchResponse = $searchManager->searchService();
    	
    	
    	if(isset($searchResponse['search_result_array']['data'][0])){
    		$product = $searchResponse['search_result_array']['data'][0];
    	}else{
    		$product = '';
    	}
    	
    	unset($searchManager);
    	unset($searchResponse);
    
    	return $product;
    }
	
    /**
     * @author Employee Id: 4014
     * Description : To get product details from API
     *
     * @param string $productSlug
     * @param string $culture
     *
     * @return array
     *
     * @throws Exception
     *
     **/
    public function getProductDetailById($productId, $culture,$instanceId='', $isSolr=false)
    {
        $this->productApi->init('view_product');
        $this->productApi->setCallParameters(array('product_ids'=>$productId,'is_solr'=>$isSolr,"instance_id"=>$instanceId));
        $this->productApi->setCulture($culture);
        $this->productApi->doProcess();
        if ($this->productApi->isSuccess()) {
            return $this->productApi->getResultArray();
        }
        return array();
    }
    
    /**
     * @author Employee Id: 4014
     * Description : To get product details from API
     *
     * @param string $productSlug
     * @param string $culture
     *
     * @return array
     *
     * @throws Exception
     *
     **/
    public function getProductDetailByIdDontApplyDiscount($productId, $culture,$instanceId='', $isSolr=false)
    {
    	$this->productApi->init('view_product');
    	$this->productApi->setCallParameters(array('product_ids'=>$productId,'is_solr'=>$isSolr,"instance_id"=>$instanceId,"applyDiscount"=>'no'));
    	$this->productApi->setCulture($culture);
    	$this->productApi->doProcess();
    	if ($this->productApi->isSuccess()) {
    		return $this->productApi->getResultArray();
    	}
    	return array();
    }
    
    /**
     * @author Employee Id: 4532
     * Description : Download images zip
     *
     * @param string $productSKU
     * @param integer $supplierId
     *
     * @return download images
     *
     * @throws Exception
     *
     **/
    public function downloadImageZip($productSKU, $supplierId)
    {	
    	/* Path of server where images zip file is present */
    	$filename = $this->serviceContainer->getParameter('product_image.base_url.high_res').$productSKU.'.zip';
    	$productImageUrl =  $this->serviceContainer->getParameter('product_image.base_url');
    	$downloadPathUrlRelative = $this->serviceContainer->getParameter('product_image.zip_path');
    	$downloadPathUrlAbsolute = $this->serviceContainer->getParameter('product_image.zip_path_absolute');
    		
    	/* Code for download image zip on local site start */
   		$this->downloadFileFromRemoteToLocal($downloadPathUrlAbsolute, $supplierId,$productImageUrl,$downloadPathUrlRelative,$filename);
    	/* Code for download image zip on local folder end */
    }
    
   	/**
     * @author Employee Id: 4532
     * Description : Download Product Template
     *
     * @param string $productSKU
     * @param integer $supplierId
     *
     * @return download product template
     *
     * @throws Exception
     *
     **/
    public function downloadPdfTemplate($productSKU, $supplierId)
    {
    	/* Path of server where images zip file is present */
    	$filename = $this->serviceContainer->getParameter('product_image.base_url.templete').$productSKU.'.pdf';
		$productImageUrl =  $this->serviceContainer->getParameter('product_template.base_url');
	    $downloadPathUrlRelative = $this->serviceContainer->getParameter('product_pdf.pdf_path');
	    $downloadPathUrlAbsolute = $this->serviceContainer->getParameter('product_pdf.pdf_path_absolute');

	    /* Code for download image zip on local site start */
	    $this->downloadFileFromRemoteToLocal($downloadPathUrlAbsolute, $supplierId, $productImageUrl, $downloadPathUrlRelative, $filename);
	    /* Code for download image zip on local folder end */
    }
    public function downloadZipTemplate($productSKU, $supplierId)
    {
    	/* Path of server where images zip file is present */
    	$filename = $this->serviceContainer->getParameter('product_image.base_url.templete').$productSKU.'.zip';
    	$productImageUrl =  $this->serviceContainer->getParameter('product_template.base_url');
    	$downloadPathUrlRelative = $this->serviceContainer->getParameter('product_pdf.pdf_path');
    	$downloadPathUrlAbsolute = $this->serviceContainer->getParameter('product_pdf.pdf_path_absolute');
    	
    	/* Code for download image zip on local site start */
    	$this->downloadTemplateFileFromRemoteToLocal($productImageUrl, $supplierId, $productImageUrl, $downloadPathUrlRelative, $filename);
    	/* Code for download image zip on local folder end */
    }
    public function downloadTemplateFileFromRemoteToLocal($downloadPathUrlAbsolute, $supplierId, $productImageUrl, $downloadPathUrlRelative, $filename)
    {
        $folderName = explode("/",$filename);
        $sourceZipFile = $productImageUrl.$supplierId.'/'.$filename;
        $destinationZip = $downloadPathUrlAbsolute.$supplierId.'/'.$filename;
        $destinationRelativeZip = $downloadPathUrlRelative.$supplierId.'/'.$filename;
        $destinationZipFolder =  $downloadPathUrlRelative.$supplierId."/".$folderName[0];
        $destinationZipFolder1 =  $downloadPathUrlRelative.$supplierId;
        $destinationAbsoluteZipFolder = $downloadPathUrlRelative.$supplierId.'/'.$filename;
        
        if (!file_exists($destinationRelativeZip)) {
            $this->commonLibraryManager->makeDir($destinationZipFolder,$downloadPathUrlRelative);
            $this->commonLibraryManager->saveUrlToFile($sourceZipFile, $destinationRelativeZip,$destinationAbsoluteZipFolder);
        }
        $this->forceFullyDownloadFile($filename, $productImageUrl.$supplierId);
        
    }
    public function convertYoutube($string) 
    {
    	return preg_replace("/\s*[a-zA-Z\/\/:\.]*youtu(be.com\/watch\?v=|.be\/)([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i", "$2", $string);
    }
    
    public function recentViewProductByCookies($cookiesName, $productId, $culture) 
    {
    	$recentView = array();
    	$response = new Response();

    	if($this->request->cookies->has($cookiesName)){
    		$recentView = unserialize($this->request->cookies->get($cookiesName));
    	}

    	if (!in_array($productId, array_column($recentView, 'id'))) {
    		if (count(array_keys($recentView)) >= $this->noOfRecord) {
    			array_shift($recentView);
    			array_push($recentView, array('id'=> $productId,'culture'=> $culture));
    		} else {
    			array_push($recentView, array('id'=> $productId,'culture'=> $culture));
    		}
    	}

    	$response->headers->setCookie(new Cookie($cookiesName, serialize($recentView), time() + (10 * 365 * 24 * 60 * 60), '/', null, false, false));
    	$response->sendHeaders();
    }

    /**
     * @author Employee Id: 4532
     *
     * Description : Product Detail page Bread Crumbs
     *
     * @param integer $categoryId
     *
     * @return array of category and subcategory tree for given category Id
     *
     * @throws Exception
     *
     **/
    
    public function productDetailBreadcrumbs($categoryId)
    {
    	$subCategoriesList = array();
    	$this->productBreadCrumbArray = array();
    	$this->flag = 0;
    	 
    	$searchObj = $this->serviceContainer->get('office_brain_search_manager');
    	
    	$categories = $searchObj->getCategorySubCategoryList();
       
    	if(!empty($categories)){ 
	    	$this->getProductBreadcrumbs($categoryId,$categories,0);
	    	if($this->flag == 0){
	    		$this->productBreadCrumbArray = array();
	    	}
    	}
        $this->productBreadCrumbArray = array_reverse($this->productBreadCrumbArray,true);
    	return $this->productBreadCrumbArray;
    }
    
    private function getProductBreadcrumbs($categoryId,$categories,$parent=0){
    	 
    	foreach ($categories as $cat){
    		if($cat['parent_id'] == 0 && ($this->flag == 0)){
    			$this->productBreadCrumbArray = array();
    		}
    		if(($cat['pms_id'] == $categoryId) && ($this->flag == 0)){
    			$this->productBreadCrumbArray[$cat['pms_id']]['name'] = $cat['cat_name'];
    			$this->productBreadCrumbArray[$cat['pms_id']]['slug'] = $cat['slug'];
    			$this->productBreadCrumbArray[$cat['pms_id']]['child'] = '0';
    			$this->flag = 1;
    			return true;
    		}
    		if(isset($cat['child']) && $this->flag == 0){
                        $parent = $this->getProductBreadcrumbs($categoryId,$cat['child']);
                        if($parent){
                            $this->productBreadCrumbArray[$cat['pms_id']]['name'] = $cat['cat_name'];
                            $this->productBreadCrumbArray[$cat['pms_id']]['slug'] = $cat['slug'];
                            $this->productBreadCrumbArray[$cat['pms_id']]['child'] = '1';
                            return true;
                        }
    			
    		}
    	}
        return false;
        
    }
    
    /**
     * @author Employee Id: 4532
     *
     * Description : Related Product Information
     *
     * @param integer $productId
     * 
     * @param string $culture
     *
     * @return array of related product information
     *
     * @throws Exception
     *
     **/
    
    public function getRelatedProductDetailInfo($productId, $culture)
    {
    	$this->productApi->init('related_product');
        $this->productApi->setCallParameters(array('product_id'=>$productId));
        $this->productApi->setCulture($culture);        
        $this->productApi->doProcess();
        if ($this->productApi->isSuccess()) {
            return $this->productApi->getResultArray();
        }
        return array();
    }
    
    /**
     * @author Employee Id: 4532
     *
     * Description : Recommended Product Information
     *
     * @param integer $productId
     *
     * @param string $culture
     *
     * @return array of recommended product information
     *
     * @throws Exception
     *
     **/
    
    public function getRecommendedProductDetailInfo($productId, $culture)
    {
    	$this->productApi->init('recommended_product');
    	$this->productApi->setCallParameters(array('product_id'=>$productId, 'culture'=>$culture));
    	//$this->productApi->setCulture($culture);
    	$this->productApi->doProcess();
    	if ($this->productApi->isSuccess()) {
    		return $this->productApi->getResultArray();
    	}
    	return array();
    }
    
    /**
     * @author Employee Id: 4464
     * Description : To get product tags in product detail array
     *
     * @param string $productSku
     *
     * @return array
     *
     * @throws Exception
     *
     **/
    public function getAllTagsByProductSku($productSku)
    {
        $searchManager = $this->serviceContainer->get('office_brain_search_manager');
        $this->request->query->set('sku',$productSku);

        $searchResponse = $searchManager->searchService();
        $tagsArray = array();

        if(!empty($searchResponse['search_result_array']['data'][0]['custom_tag_style_ss'])){
            if(is_array($searchResponse['search_result_array']['data'][0]['custom_tag_style_ss'])){
                foreach ($searchResponse['search_result_array']['data'][0]['custom_tag_style_ss'] as $index => $value){
                    if(!empty($value)) $tagsArray[] = explode('|', $value);
                }
            }else{
                $tagsArray[0] = explode('|', $searchResponse['search_result_array']['data'][0]['custom_tag_style_ss']);
            }
        }
        
        unset($searchManager);
        unset($searchResponse);
        
        return $tagsArray;
    }
    
    /**
     * @author Employee Id: 4494
     * Description : To get product tags in product detail array
     *
     * @param string $productSku
     *
     * @return array
     *
     * @throws Exception
     *
     **/
    public function getAllTagsByProductId($productId)
    {
    	$searchManager = $this->serviceContainer->get('office_brain_search_manager');
    	$this->request->query->set('product_id',$productId);
    	$searchResponse = $searchManager->searchService();
    	$tagsArray = array();

    	if(isset($searchResponse['search_result_array']['data'][0]['custom_tag_style_ss']) && !empty($searchResponse['search_result_array']['data'][0]['custom_tag_style_ss'])){
    		if(is_array($searchResponse['search_result_array']['data'][0]['custom_tag_style_ss'])){
    			foreach ($searchResponse['search_result_array']['data'][0]['custom_tag_style_ss'] as $index => $value){
    				if(!empty($value)) $tagsArray[] = explode('|', $value);
    			}
    		}else{
    			$tagsArray[0] = explode('|', $searchResponse['search_result_array']['data'][0]['custom_tag_style_ss']);
    		}
    	}
    	
    	unset($searchManager);
    	unset($searchResponse);
    	
    	return $tagsArray;
    }
    
    /**
     * @author Employee Id: 4116
     * Description : To get Cluture wise Product Slug
     *
     * @param string $productSlug
     * @param string $OldCulture
     * @param string $NewCulture
     *
     * @return String
     *
     * @throws Exception
     *
     **/
    public function getProductSlugClutureWise($productSlug,$oldCulture,$newCulture)
    {
        $productDetailData=$this->getProductDetailBySlug($productSlug,$oldCulture);
        $productId=$productDetailData['product_id'];
        $productDetailData=$this->getProductDetailById($productId,$newCulture);
        if(isset($productDetailData[$productId]) && !empty($productDetailData[$productId]['basic_information']))
        {
            return $productDetailData[$productId]['basic_information']['slug'];
        }
        return null;
    }
    
    public function getCountry() {
    	return $this->serviceContainer->getParameter('country');
    }
    
    public function uploadSwatches($swatchesId,$file){
    	$this->bkpSwatchesImage($swatchesId);
    	return $this->moveUploadFile($swatchesId,$file);
    }
    
    public function moveUploadFile($swatchesId,$file){
    	//echo '<pre>'; print_r($file); die;
    	$data = array();
    	// image type validation
    	if($file[0]['type'] != 'image/jpg' and $file[0]['type'] != 'image/jpeg'){
    		return array('status' => 'error', 'msg' => 'Image type must be jpg');
    	}
    	// image dymention validation
    	$swatchesSize = $this->serviceContainer->getParameter('swatches_size');
    	$image_info = getimagesize($file[0]["tmp_name"]);
    	$image_width = $image_info[0];
    	$image_height = $image_info[1];
    	if($image_width != $swatchesSize and $image_height != $swatchesSize){
    		return array('status' => 'error', 'msg' => 'Image dimension must be '.$swatchesSize.'*'.$swatchesSize);
    	}
    	$swatchesPath = $this->serviceContainer->getParameter('swatches_image.file_path');
    	$swatchesSourcePath = $swatchesPath."/".$swatchesId.'.jpg';
    	$this->unlinkSwatchesFile($swatchesSourcePath);
    	if (move_uploaded_file($file[0]['tmp_name'], $swatchesSourcePath)) {
    		$swatchesUrl = $this->serviceContainer->getParameter('swatches_image.url')."/".$swatchesId.'.jpg';
    		chmod($swatchesSourcePath,0777);
    		return array('status' => 'success', 'msg' => 'Image update successfully','image_url' => $swatchesUrl);
        } 
    }
    
    public function bkpSwatchesImage($swatchesId){
    	$swatchesSourcePath = $this->serviceContainer->getParameter('swatches_image.file_path').'/'.$swatchesId.'.jpg';
    	$swatchesDestinationPath = $this->serviceContainer->getParameter('swatches_image.file_path').'/swatches_bkp/'.$swatchesId.'.jpg';
    	$this->copySwatchesImages($swatchesSourcePath,$swatchesDestinationPath);
    }
    
    public function unlinkSwatchesFile($swatchesSourcePath){
    	unlink($swatchesSourcePath);
    }
    
    public function copySwatchesImages($swatchesSourcePath,$swatchesDestinationPath){
    	
    	if(!copy($swatchesSourcePath, $swatchesDestinationPath)){
    		return true;
    	}else{
    		return false;
    	}
    }
    
    public function revertSwatches($swatchesId){
    	$swatchesDestinationPath = $this->serviceContainer->getParameter('swatches_image.file_path').'/'.$swatchesId.'.jpg';
    	$swatchesSourcePath = $this->serviceContainer->getParameter('swatches_image.file_path').'/swatches_bkp/'.$swatchesId.'.jpg';
    	$swatchesUrl = $this->serviceContainer->getParameter('swatches_image.url')."/".$swatchesId.'.jpg';
    	if(!file_exists($swatchesSourcePath)){
    		return array('status' => 'error', 'msg' => 'Revert image not exist','image_url' => $swatchesUrl);
    	}
    	
    	$this->copySwatchesImages($swatchesSourcePath,$swatchesDestinationPath);
    	$this->unlinkSwatchesFile($swatchesSourcePath);
    	chmod($swatchesDestinationPath,0777);
    	return array('status' => 'success', 'msg' => 'Image revert successfully','image_url' => $swatchesUrl);
    }
    public function getAttributeIds(){
    	$data = array();
    	
    	$data['trim_color_id'] = $this->serviceContainer->getParameter('trim_attr_color_id');
    	$data['barrel_color_id'] = $this->serviceContainer->getParameter('barrel_attr_color_id');
    	$data['ink_color_id'] = $this->serviceContainer->getParameter('ink_attr_color_id');
    	$data['color_attr_id'] = $this->serviceContainer->getParameter('color_attribute_id');
    	$data['std_color_id'] = $this->serviceContainer->getParameter('standard_color_id');
    	
    	return $data;
    	
    }
    
    public function getColorCodeArray($productDtlArray){
    	
    	$result = array();
    	foreach ($productDtlArray['images'] as $k=>$v){
    		if($v['actual_color_id'] != '' && $v['color_name'] != ''){
    			if (preg_match("/^BR\|".$v['actual_color_id']."/", $v['color_name']))
    			{
    				$result['BR|'.$v['actual_color_id']] = $v['color_name'];
    			}
    			if (preg_match("/^TR\|".$v['actual_color_id']."/", $v['color_name']))
    			{
    				$result['TR|'.$v['actual_color_id']] = $v['color_name'];
    			}
    		}
    	}
    	return $result;
    }
    
    public function getColorTrimBarrelIds($attributes,$colorType,$colorId,$otherColorId){
    	$trimAttrColorId = $this->serviceContainer->getParameter('trim_attr_color_id');
    	$barrelAttrColorId = $this->serviceContainer->getParameter('barrel_attr_color_id');
    	
    	$result = array();
    	$result_other = array();    	
    	if($colorType == 'TR'){
    		$colorTypeOther = 'BR';
    	}
    	if($colorType == 'BR'){
    		$colorTypeOther = 'TR';
    	}
    	foreach ($attributes as $attr){
    		if($attr['id'] == '10'){
    			foreach ($attr['values'] as $k=>$at){
    				if($k == $colorId){
    					$result[$colorType] = $at;
    				}
    				if($k == $otherColorId[0]){
    					$result[$colorTypeOther] = $at;
    				}
    			}
    		}
    	}
    	//echo '<pre>'.$colorType.'--'.$colorTypeOther; print_r($result); die;
    	$rs = array();
    	foreach ($result as $key=>$val){
    		if($key == 'BR'){
    			foreach ($attributes as $attr){
    				if($attr['id'] == $barrelAttrColorId){
    					foreach ($attr['values'] as $k=>$at){
    						$at_val = $at;
    						if(strtolower(str_replace(" ", "",$val)) == strtolower(str_replace(" ", "",$at))){
    							//$rs[$attr['id']] = $key.'|'.$k.'::SEP::'.$at_val;
    							$rs[$attr['id']] = $key.'|'.$at_val;
    						}
    					}
    				}
    			}
    		}
    		
    		if($key == 'TR'){
    			foreach ($attributes as $attr){
    				if($attr['id'] == $trimAttrColorId){
    					foreach ($attr['values'] as $k=>$at){
    						$at_val = $at;
    						if(strtolower(str_replace(" ", "",$val)) == strtolower(str_replace(" ", "",$at))){
    							//$rs[$attr['id']] = $key.'|'.$k.'::SEP::'.$at_val;
    							$rs[$attr['id']] = $key.'|'.$at_val;
    						}
    					}
    				}
    			}
    		}
    	}

    	ksort($rs);
    	
    	$str = '';
    	$cnt = 0;
    	foreach ($rs as $k1=>$v1){
    		if($cnt == 0){
    			$str .= $v1;
    		}else{
    			$str .= '|'.$v1;
    		}
    		$cnt++;
    	}
    	//echo $str; die;
    	return $str;
    }
    
    public function getCombineColorImage($colorString,$productDtlImages){
    	$combineImage = '';
    	foreach ($productDtlImages as $pdi){
    		if($pdi['color_name'] == $colorString){
    			$combineImage = $pdi['url'];
    		}
    		if($combineImage == ''){
    			if( strpos( $pdi['color_name'], $colorString) !== false ) {
    				$combineImage = $pdi['url'];
    			}
    		}
    	}
    	return $combineImage;
    }
    
    public function getNormalImage($colorId,$productDtlImages){
    	$combineImage = '';
    	foreach ($productDtlImages as $pdi){
    		if($pdi['actual_color_id'] == $colorId){
    			$combineImage = $pdi['url'];
    		}
    	}
    	return $combineImage;
    }
    public function getCombineColorImageSingle($colorString,$productDtlImages){
    	$combineImage = '';
    	foreach ($productDtlImages as $pdi){
    		if($pdi['color_name'] == $colorString){
    			$combineImage = $pdi['url'];
    		}
    		if($combineImage == ''){
    			if( strpos( $pdi['color_name'], $colorString) !== false ) {
    				$combineImage = $pdi['url'];
    			}
    		}
    	}
    	return $combineImage;
    }
    
    public function getOtherColorIds($colorString,$attributes,$productDtlImages,$colorType){
    	$colstr = explode('::SEP::',$colorString);
    	if($colorType == 'TR'){
    		$colorTypeOther = 'BR';
    	}
    	if($colorType == 'BR'){
    		$colorTypeOther = 'TR';
    	}
    	$colorCompArray = array();
    	
    	foreach ($productDtlImages as $pdi){

    		if (strpos($pdi['color_name'], $colstr[0]) !== false) {
    			$colorCompArray[] = $pdi['color_name'];
    		}
    	}
    	$res = array();
    	foreach ($colorCompArray as $cca){
    		if (strpos($cca, $colorTypeOther) !== false) {
    			$res[] =$cca;
    		}
    	}
    	$finalRes = array();
    	foreach ($res as $r){
    		$result = explode('|TR|',$r);
    		if($colorTypeOther == 'BR'){
    			$newres = explode('::SEP::',$result[0]);
    			$finalRes[] = $newres[1];
    		}
    		if($colorTypeOther == 'TR'){
    			$newres = explode('::SEP::',$result[1]);
    			$finalRes[] = $newres[1];
    		}
    	}
    	
    	$final = array();
    	foreach ($attributes as $attr){
    		if($attr['id'] == '10'){
    			foreach ($attr['values'] as $k=>$at){
    				foreach ($finalRes as $val){
    					if(strtolower(str_replace(" ", "",$val)) == strtolower(str_replace(" ", "",$at))){
    						$final[]= $k;
    					}
    				}
    			}
    		}
    	}
    	
    	return implode(',',$final); 
    }
    
}
