<?php

namespace OfficeBrain\Bundle\ProductBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Translation\Translator;
use Symfony\Component\HttpFoundation\JsonResponse;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use OfficeBrain\Bundle\ProductBundle\Helper\ProductDetailHelper;
use OfficeBrain\Bundle\ProductBundle\Form\ProductSharingEmailType;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\Serializer\Exception\Exception;
use Symfony\Component\Config\Util\XmlUtils;
use OfficeBrain\Bundle\ProductBundle\Form\OrderSampleType;
use OfficeBrain\Bundle\ProductBundle\Entity\OrderSample;

/**
 *
 * @author Employee Id: 4532
 *
 * To set member variables default value
 *
 * @return NULL
 *
 * @Route("/{_locale}")
 */

class ProductController extends Controller
{

	/**
	 *
	 * @author Employee Id: 4532
	 *
	 * To set member variables default value
	 *
	 * @return NULL
	 *
	 */
    public function __construct()
    {
		$this->request = null;
        $this->projectSetting = null;
        $this->instanceId = $this->projectSetting['instance_id'];
        $this->productAccessRules = null;
        $this->productConfigurationRules = null;
        $this->cultureCode = null;
        $this->responseArray = array();
        $this->searchManager = null;
        $this->solrManager = null;
        $this->commonLibraryManager = null;
        $this->productDetailManager = null;
        $this->locale = null;
        $this->translator = null;
        $this->twigManager=null;
    }

    /**
     *
     * @author Employee Id: 4532
     * To unseset member variables
     *
     * @return NULL
     */
    public function __destruct()
    {
        unset($this->request);
        unset($this->projectSetting);
        unset($this->productAccessRules);
        unset($this->productConfigurationRules);
        unset($this->cultureCode);
        unset($this->responseArray);
        unset($this->searchManager);
        unset($this->solrManager);
        unset($this->commonLibraryManager);
        unset($this->productDetailManager);
        unset($this->locale);
        unset($this->translator);
        unset($this->twigManager);
    }

    /**
     *
     * @author Employee Id: 4532
     * To Initialize the member variables
     *
     * @return NULL
     */
    public function initAction()
    {
    	$this->responseArray = array();
        $this->request = $this->getRequest();
        $this->session = $this->request->getSession();
        $this->projectSetting = $this->request->get('project_setting');
        $this->productAccessRules = $this->projectSetting['access_rule']['product_management'];
        $this->productConfigurationRules = $this->projectSetting['configuration_rule']['product'];
        $this->cultureCode = $this->projectSetting['culture_code'];
        $this->locale = $this->projectSetting['locale_language'];
        $this->searchManager = $this->get('office_brain_search_manager');
        $this->solrManager = $this->get("office_brain_solr_product_mapping_manager");
        $this->commonLibraryManager = $this->get('office_brain_common_library');
        $this->productDetailManager = $this->get('office_brain_product_detail_manager');
        $this->emailService = $this->get('office_brain_email_service');
        $this->categoryApiManager = $this->get("officebrain_category_api_manager");
        $this->translator = $this->get('translator');
        $this->responseArray['breadcrumbs'] = '';
        $this->sellingIdeaBasePath=$this->container->getParameter('selling_idea_base_url');
        $this->twigManager = $this->get('twig');
//         $this->inventoryLookupBaseURL=$this->container->getParameter('inventorylookup_base_url');
        $this->userManager = $this->get("office_brain_user_manager");
        $this->seoManager = $this->get("office_brain_seo_manager");
        $this->freeFreightAllowCategoryList = $this->getParameter('free_freight_allow_category_list');
        $this->productTagManager = $this->get('office_brain_product_tag_manager');
        
    }


    /**
     * @author Employee Id: 4532
     *
     *   Product Detail data.
     *
     *  @param string product slug
     *
     *  @return product detail information
     *

     * @Route("/product/{productSlug}",
     * 	name="officebrain_product_bundle_product_detail",
     * )

     * @method({"GET"})
     * @Template("OfficeBrainProductBundle:Product:productDetail.html.twig")
     *
     */
    public function productDetailAction($productSlug)
    {
        $this->initAction();
        $colourAttr = $this->request->get('clr',null);
        if (is_numeric($productSlug)){
	       	$productDetailArrayId = $this->productDetailManager->getProductDetailById($productSlug, $this->cultureCode);
	       	$this->responseArray = $productDetailArrayId[$productSlug];
        }else{
        	$this->responseArray = $this->productDetailManager->getProductDetailBySlug($productSlug, $this->cultureCode);
        }
        if ($this->responseArray == null) {
            /* if no product found Through exception */
        	throw $this->createNotFoundException($this->translator->trans('transaction.page_not_found.detail'));
        }
        elseif(($this->responseArray['basic_information']['active'] != 1 && $this->responseArray['basic_information']['active'] != true) || ($this->responseArray['is_deleted'] != 1  && $this->responseArray['is_deleted'] != false) ){
        	throw $this->createNotFoundException($this->translator->trans('transaction.page_not_found.detail'));
        }
        if(is_array($this->responseArray['category']) && count($this->responseArray['category'])){
	        foreach ($this->responseArray['category'] as $key => $value){
	        	$categoryId = $key;
	        }
        	$this->responseArray['breadcrumbs'] = $this->productDetailManager->productDetailBreadcrumbs($categoryId);
        }
        $this->responseArray['compliance_url'] = $this->container->getParameter('web_image.base_url').'uploads/supplier-compliance/';
        $this->complianceManager = $this->get('office_brain_supplier_compliance_manager');
        $this->responseArray['compliance_data'] = null;
        
        if(isset($this->responseArray['supplier']['supplier_id'])){
            $cpm = $this->complianceManager->getCompliaceBySupplierId($this->responseArray['supplier']['supplier_id']);
            if($cpm!=NULL){
                $this->responseArray['compliance_data'] = $cpm; //$cpm->getComplianceId();
            }
        }
        /* Product Tag section Starts */
        if($this->productConfigurationRules['show_product_tags']['status'] == 1){
        	$this->responseArray['product_tags_array'] = $this->productDetailManager->getAllTagsByProductId($this->responseArray['product_id']);
        	$this->responseArray['product_tags_detail'] = $this->productTagManager->getAllTagsByProductId($this->responseArray['product_id']);
        	$simpliColor = $this->container->getParameter('simpli_color');
        	foreach ($this->responseArray['product_tags_array'] as $value) {
        		if($value[0] == $simpliColor['tag_id']) {
        			$this->responseArray['simpli_color_url'] = $simpliColor['url'];
        			break;
        		}
        	}
        }
        if($this->responseArray['supplier']['supplier_id']==447){
            if($colourAttr==null){
                if(count($this->responseArray['attributes'])>0){
                    foreach ($this->responseArray['attributes'] as $color){
                        if($color['id']==10){
                            $colorIds = array_keys($color['values']);
                            $colourAttr = $colorIds[0];
                            break;
                        }
                    }
                }
            }
            if($colourAttr!=null){
                foreach($this->responseArray['images'] as $images){
                    if($images['actual_color_id']==$colourAttr){
                        $this->responseArray['basic_information']['default_image_url'] =$images['url']; 
                        break;
                    }
                }
            }
        }
        $this->responseArray['default_color_id'] = $colourAttr;
        $this->responseArray['colorCodeVal'] = $this->productDetailManager->getColorCodeArray($this->responseArray);
        /* Product Tag section Ends */
		
        $this->productDetailManager->recentViewProductByCookies('recent_product_cookie', $this->responseArray['product_id'], $this->cultureCode);
        unset($productDetailArrayId);
        
        /*
          Check Ob_customer id - for flyer which is visible or not
        */
        
        $this->responseArray['ob_customer_id']=$this->userManager->getObCustomerId($this->responseArray['supplier']['supplier_id']);
        if ($this->session->get('order_guest_shipping_address'))
        {
            $this->session->set('order_guest_shipping_address', array());
        }
        $this->responseArray['userId'] = $this->userId;
        $this->responseArray['instanceId'] = $this->instanceId;
		
        $seoData=$this->seoManager->getSeoDetailBySlug($this->responseArray['basic_information']['slug']);
        if ($seoData) {
			$title= $seoData->getMetaTitle();
			$this->responseArray['seo_meta_title'] = $title;
			$this->responseArray['seo_meta_description'] = $seoData->getMetaDescription();
			$this->responseArray['seo_meta_keywords'] = '';//$seoData->getMetaKeyWords();
        }else{
            $this->responseArray['seo_meta_title'] = $this->responseArray['basic_information']['title'];
            $this->responseArray['seo_meta_description'] = '';
            $this->responseArray['seo_meta_keywords'] = '';
        }
		//echo '<pre>'; print_r($this->responseArray); die;
        return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4532
     *
     *   Product Detail Trim Barrel Color Manage.
     *
     *  @param string color type, id
     *
     *  @return product detail Color Manage.
     *  
     * @Route("/image-color-display", name="officebrain_product_bundle_image_color_display",
     * options={"expose"=true}
     * )
     * @Template()
     *
     */
    public function imageColorDisplayAction()
    {
    	$this->initAction();
    	
    	$colorType = $this->request->get('color_type', null);
    	$colorId = $this->request->get('color_id', null);
    	$otherColorId = $this->request->get('other_color_id', null);
    	$slug = $this->request->get('slug', null); 
    	
    	$productDtl = $this->productDetailManager->getProductDetailBySlug($slug, $this->cultureCode);
    	
    	$colorString = $this->productDetailManager->getColorTrimBarrelIds($productDtl['attributes'],$colorType,$colorId,$otherColorId);
    	
    	$combineImagePath = $this->productDetailManager->getCombineColorImage($colorString,$productDtl['images']);
    	
    	
    	if($combineImagePath == ''){
    		$combineImagePath = $this->productDetailManager->getNormalImage($colorId,$productDtl['images']);
    	}
    	
    	if($combineImagePath == ''){
    		$combineImagePath = $productDtl['basic_information']['default_image_url'];
    	}
    	echo $combineImagePath; die;
    	
    }
    
    /**
     * @author Employee Id: 4532
     *
     *   Product Detail Trim Barrel other color id.
     *
     *  @param string color type, id
     *
     *  @return product detail Color Manage.
     *
     * @Route("/other-color-ids", name="officebrain_product_bundle_other_color_ids",
     * options={"expose"=true}
     * )
     * @Template()
     *
     */
    public function otherColorsIdsAction()
    {
    	$this->initAction();
    	
    	$colorType = $this->request->get('color_type', null);
    	$colorId = $this->request->get('color_id', null);
    	$otherColorId = $this->request->get('other_color_id', null);
    	$slug = $this->request->get('slug', null);
    	
    	$productDtl = $this->productDetailManager->getProductDetailBySlug($slug, $this->cultureCode);
    	
    	$colorString = $this->productDetailManager->getColorTrimBarrelIds($productDtl['attributes'],$colorType,$colorId,$otherColorId);
    	if($colorString != ''){
    		$combineImagePath = $this->productDetailManager->getCombineColorImageSingle($colorString,$productDtl['images']);
    	}else{
    		$combineImagePath = '';
    	}
    	
    	if($combineImagePath == ''){
    		$combineImagePath = $this->productDetailManager->getNormalImage($colorId,$productDtl['images']);
    	}
    	
    	if($combineImagePath == ''){
    		$combineImagePath = $productDtl['basic_information']['default_image_url'];
    	}
    	
    	$finalRes = $this->productDetailManager->getOtherColorIds($colorString,$productDtl['attributes'],$productDtl['images'],$colorType);
    	
    	$this->responseArray['other_colors'] = $finalRes;
    	
    	$this->responseArray['image_path'] = $combineImagePath;
    	
    	return new JsonResponse($this->responseArray);
    }

    /**
     * @author Employee Id: 4532
     *
     * Download product images.
     *
     * @param string product sku
     *
     * @param integer supplier id
     *
     * @return download product image zip
     *
     * @Route("/download-images", name="officebrain_product_bundle_download_images", 
     * options={"expose"=true}
     * )
     * @Template()
     */
    public function downloadImagesAction()
    {
    	$this->initAction();
    	$productSKU = $this->request->get('productSKU', null);
    	$supplierId = $this->request->get('supplierId', null);

    	if($productSKU && $supplierId) {
    		$this->productDetailManager->downloadImageZip($productSKU, $supplierId);
    	}
    	else {
    		throw new NotFoundHttpException('Not found');
    	}
    	return;
    }

    /**
     * @author Employee Id: 4532
     *
     * Download product images.
     *
     *  @param string product sku
     *
     *  @param integer supplier id
     *
     *  @return download product template
     *
     * @Route("/download-zip", name="officebrain_product_bundle_download_zip",
     * options={"expose"=true}
     * )
     * @Template()
     */
    public function downloadZIPAction()
    {
    	$this->initAction();
    	
    	$productSKU = $this->request->get('productSKU', null);
    	$supplierId = $this->request->get('supplierId', null);
    	
    	if($productSKU && $supplierId) {
    		$status_info = $this->productDetailManager->downloadZipTemplate($productSKU, $supplierId);
    		if($status_info == 0){
    			$data['error'] = $this->translator->trans('Bad Url');
    		}
    		return $data;
    	}
    	else {
    		throw new NotFoundHttpException('Not found');
    	}
    	return;
    }
    /**
     * @author Employee Id: 4532
     *
     * Download product images.
     *
     *  @param string product sku
     *
     *  @param integer supplier id
     *
     *  @return download product template
     *
     * @Route("/download-pdf", name="officebrain_product_bundle_download_pdf",
     * options={"expose"=true}
     * )
     * @Template()
     */
    public function downloadPDFAction()
    {
    	$this->initAction();

    	$productSKU = $this->request->get('productSKU', null);
    	$supplierId = $this->request->get('supplierId', null);

    	if($productSKU && $supplierId) {
    		$status_info = $this->productDetailManager->downloadPdfTemplate($productSKU, $supplierId);
    		if($status_info == 0){
    			$data['error'] = $this->translator->trans('Bad Url');
    		}
    		return $data;
    	}
    	else {
    		throw new NotFoundHttpException('Not found');
    	}
    	return;
    }

    /**
     *
     * @author Employee Id: 4861
     *
     * Desciption: Social sharing model.
     *
     * @param null
     *
     * @return json Response
     *
     * @throws null
     * 
  	 * @Route("/social-sharing", name="officebrain_product_bundle_social_sharing",
  	 * options={"expose"=true}
	 * )
     * @Template("OfficeBrainProductBundle:Product:socialSharing.html.twig")
     */
    public function socialSharingAction()
    {
    	return array();
    }

    /**
     * @author Employee Id: 4861
     *
     * Desciption: Email product detail model.
     *
     * @param senderName,fromEmail,recepientEmail,message,url.
     *
     * @return json Response
     *
     * @throws null
     *
     * @Route("/product-detail-email", name="officebrain_product_bundle_product_emailtofriend",
     * options={"expose"=true}
     * )
     * @Template("OfficeBrainProductBundle:Product:emailToFriend.html.twig")
     */
    public function emailToFriendAction()
    {
    	$this->initAction();

    	$emailProduct = null;
    	$this->form = $this->createForm(new ProductSharingEmailType($this->request->query->get('product_id')), $emailProduct, array(
    			'action' => $this->generateUrl('officebrain_product_bundle_product_emailtofriend'),
    	));
    	if($this->request->getMethod() == 'POST'){
	    	$this->form->bind( $this->request );

	    	if ($this->form->isValid ()) {

                if(isset($_POST['g-recaptcha-response']) && $_POST['g-recaptcha-response']!=''){
                    $captcha=$_POST['g-recaptcha-response'];
            
                    $secretKey = "6LdFSNYjAAAAAIRwiVnI4UJIfjq1oCbzWuSFQ9a-";
                    $url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secretKey) .  '&response=' . urlencode($captcha);
                    $response = file_get_contents($url);
                    $responseKeys = json_decode($response,true);
                }
                
                if($responseKeys['success']!=1){

                    $this->responseArray['form_status'] = 'error';
                    $this->responseArray['captcha_error'] = 'Oops, you have to check the recaptcha !';
                    return new JsonResponse($this->responseArray);
                            
                }
	    		$eventKey = 'productDetailEmail';
				//$this->formData = $this->form->getData ();
				$senderName = $this->form->get('senderName')->getData();
				$from = $this->form->get('fromEmail')->getData();
				$to = $this->form->get('recepientEmail')->getData();
				$message = $this->form->get('message')->getData();
				$url = $this->form->get('url')->getData();
				$productDetailArray = $this->productDetailManager->getProductDetailById($url, $this->cultureCode);
				//$response = array('product_email_templete'=> $this->render('OfficeBrainProductBundle:Product:productDetailEmailTemplate.html.twig',array('product_detail'=>$productDetailArray[$url], 'message'=>$message)));
				$productDetailHTML=$this->twigManager->render('OfficeBrainProductBundle:Product:productDetailEmailTemplate.html.twig',array('product_detail'=>$productDetailArray[$url], 'message'=>$message, 'sender_name'=>$senderName));
				$response = array('product_email_template' => $productDetailHTML);
				$this->emailService->sendMail($eventKey, $to, $response, $this->locale, $from);

				unset($emailProduct);
				unset($this->form);
				unset($senderName);
				unset($from);
				unset($to);
				unset($message);
				unset($url);
				unset($params);
				$this->responseArray['status'] = 'success';
				$this->responseArray['email_success_message'] = $this->translator->trans('email.success');

				return new JsonResponse($this->responseArray);
	    	} else {
	    		return new JsonResponse($this->commonLibraryManager->prepareFormJsonError($this->form));
	    	}
    	}
    	$this->responseArray['form'] = $this->form->createView();
    	$this->responseArray['url'] = $this->form->get('url')->getData();
    	unset($emailProduct);
    	unset($this->form);
    	return $this->responseArray;
    }
    /**
     * @author Employee Id: 4861
     *
     * Desciption: Play Video model.
     *
     * @param video_url.
     *
     * @return json Response
     *
     * @Route("/product-detail-video", name="officebrain_product_bundle_product_detail_video",
     * options={"expose"=true}
     * )
     *
     * @Template("OfficeBrainProductBundle:Product:productDetailVideo.html.twig")
     */
    public function productDetailVideoAction()
    {
    	$this->initAction();

    	$this->responseArray['video_url'] = $this->productDetailManager->convertYoutube($this->request->get('video_url',''));

    	return $this->responseArray;
    }

    /**
     * @author Employee Id: 4861
     *
     * Desciption: Enbeded product model.
     *
     * @param product_id.
     *
     * @return json Response
     *
     * @Route("/product-detail-embeded-model", name="officebrain_product_bundle_product_detail_embeded-model",
     * options={"expose"=true}
     * )
     *
     * @Template("OfficeBrainProductBundle:Product:embedCode.html.twig")
     */
    public function embedCodeAction()
    {
    	$this->initAction();

    	$this->responseArray['product_id'] = $this->request->get('product_id');

    	return $this->responseArray;
    }

    /**
     * @author Employee Id: 4861
     *
     * Desciption: Enbeded product.
     *
     * @param product_id.
     *
     * @return json Response
     *
     * @Route("/product-detail-embeded/{product_id}",
     * 	name="officebrain_product_bundle_product_detail_embeded"
     * )
     *
     */
    public function productDetailEmbededAction($product_id)
    {
    	$this->initAction();

    	$productDetailArray = $this->productDetailManager->getProductDetailById($product_id, $this->cultureCode);

    	$htmlResponse = $this->renderView('OfficeBrainProductBundle:Product:embededProduct.html.twig', array('product_detail'=>$productDetailArray[$product_id]));
    	$jsonp = $this->request->get('callback', 'pppc_plugin');
    	$result = array('status'=>TRUE, 'main_data' =>$htmlResponse);
    	$this->responseArray = new JsonResponse($result, 200, array());
    	$this->responseArray->setCallback($jsonp);

    	unset($productDetailArray);
    	unset($result);
    	unset($jsonp);
    	unset($html);

    	return $this->responseArray;
    }

    /**
     * @author Employee Id: 4861
     *
     * Desciption: print page.
     *
     * @param product_id.
     *
     * @return json Response
     *
     * @Route("/product-detail-print-page/{product_id}",
     * 	name="officebrain_product_bundle_product_detail_print_page" ,options={"expose"=true}
     * )
     *
     * @Template("OfficeBrainProductBundle:Product:printProduct.html.twig")
     */
    public function printProductDetailAction($product_id)
    {
    	$this->initAction();

    	$productDetailArray = $this->productDetailManager->getProductDetailById($product_id, $this->cultureCode);

    	$this->responseArray = $productDetailArray[$product_id];

    	unset($productDetailArray);

    	return $this->responseArray;
    }


    /**
     * @author Employee Id: 4861
     *
     * Desciption: Recent view.
     *
     * @param product_id.
     *
     * @return json Response
     *
     *
     * @Route("/product-detail-recent-view/{exclude_product_id}",
     * 	name="officebrain_product_bundle_product_recentlyviewedproduct",
     *  options={"expose"=true}
     * )
     *
     * @Template("OfficeBrainProductBundle:Product:recentlyViewedProduct.html.twig")
     */
    public function recentlyViewedProductAction($exclude_product_id = "")
    {
		
    	//$this->initAction();
    	
    	/*$this->responseArray = array();
        $this->request = $this->getRequest();
        $this->searchManager = $this->get('office_brain_search_manager');
        */
        $projectSetting = $this->getRequest()->get('project_setting');
        $cultureCode = $projectSetting['culture_code'];
        $responseArray = array();
    	$responseArray['recent_view_array'] = array();
    	$excludeProductId = $this->getRequest()->get('exclude_product_id');
    	$recentView = unserialize($this->getRequest()->cookies->get('recent_product_cookie'));
    	$recentProductIdsArray = array();
    	if(!empty($recentView)){
    	    foreach($recentView as $product){
    	        if($excludeProductId != $product['id'] && $product['culture'] == $cultureCode){
    	            $recentProductIdsArray[] = $product['id'];
    	        }
    	    }
    	}
    	
    	if(count($recentProductIdsArray) > 0)
    	{
    	    $recentProductIdsArray = array_unique($recentProductIdsArray);
    	    $this->getRequest()->query->set('recent_product_ids', $recentProductIdsArray);
    	    //$searchResult =  $this->searchManager->searchService(true);
    	    $searchResult =  $this->get('office_brain_search_manager')->searchService();
    	    $responseArray['recent_view_array'] = $searchResult['search_result_array']['data'];
    	}
    	//print_r($this->responseArray['recent_view_array']); die;
		unset($recentView);
		unset($excludeProductId);
		unset($recentProductIdsArray);
		unset($searchResult);
    	return $responseArray;
    }

    /**
     * @author 4532
     *
     * Desciption: Product Quick view on search page.
     *
     * @param string product slug
     *
     * @return product quick view information
     *
     *
     * @Route("/product_quickview/{productSlug}",
     * 	name="officebrain_search_bundle_product_quickview",
     * )
     *
     * @Template("OfficeBrainProductBundle:QuickView:productQuickView.html.twig")
     *
     */
    public function productQuickViewAction($productSlug)	
    {
    	$this->initAction();
    	list($defaultCulture,$defaultCountry) = explode("_",$this->request->get("_locale"));
    	$culture = $this->request->get('language',$defaultCulture);
    	$activeCulture = $culture;
    	$cultureCategory =  $activeCulture . "_" . $country;
    	$categoryAndSubCategoryData = $this->categoryApiManager->getList(array($cultureCategory),array(),true);
    	 
    	$this->responseArray = $this->searchManager->getQuickProductDetailBySlug($productSlug, $this->cultureCode);
    	$categoryAndSubCategoryList = array();
    	$categoryAndSubCategoryList = $this->categoryApiManager->getParentChildCategoryList($categoryAndSubCategoryData,$this->responseArray['category'],$activeCulture);
    	$existValue = 0;
        /*foreach($this->freeFreightAllowCategoryList as $key => $value){ 
         	if(array_key_exists($value,$categoryAndSubCategoryList['parent_id'])){ 
         		$existValue = 1;
         		break;
         	}else{
         		if(count($categoryAndSubCategoryList['parent_id'][$value]['child'])>0){
         			if(array_key_exists($value,$categoryAndSubCategoryList[$value]['child'])){
		   				$existValue = 1;
		   				break;
		    		}
         		}
         	}	
         }*/	
         $this->responseArray['dispalyText'] = $existValue;
    	
    	if ($this->responseArray == null) {
    		throw new NotFoundHttpException('Product not found');
    	}

    	if($this->productConfigurationRules['show_product_tags']['status'] == 1){
    		$this->responseArray['product_tags_array'] = $this->productDetailManager->getAllTagsByProductSku($this->responseArray['basic_information']['sku_number']);
    		
    		$simpliColor = $this->container->getParameter('simpli_color');
    		foreach ($this->responseArray['product_tags_array'] as $value) {
    			if($value[0] == $simpliColor['tag_id']) {
    				$this->responseArray['simpli_color_url'] = $simpliColor['url'];
    				break;
    			}
    		}
    	}

    	return $this->responseArray;
    }

    /**
     * @author 4532
     *
     * Desciption: Related Product Information.
     *
     * @param integer product id
     *
     * @return product related information
     *
     * @Route("/related-product/{productId}",
     * 	name="officebrain_product_bundle_product_relatedproduct",
     *  options={"expose"=true}
     * )
     *
     * @Template("OfficeBrainProductBundle:Product:relatedProduct.html.twig")
     *
     */

    public function relatedProductAction($productId)
    {
        $this->initAction();
        
        $relatedProductIds = $this->productDetailManager->getRelatedProductDetailInfo($productId, $this->cultureCode);
        $this->responseArray['related_product'] = array();
        if ($relatedProductIds == null) {
            return $this->responseArray;
        }
        
        $relatedProductIdsArray = array();
        foreach($relatedProductIds['relatedProducts'] as $rpi){
            $relatedProductIdsArray[] = $rpi['relatedProductId'];
        }
        
        if(count($relatedProductIdsArray) > 0)
        {
            $relatedProductIdsArray = array_unique($relatedProductIdsArray);
            $this->request->query->set('related_product_ids', $relatedProductIdsArray);
            $this->result =  $this->searchManager->searchService(true);
            $this->responseArray['related_product'] = $this->result['search_result_array']['data'];
        }
        
        return $this->responseArray;
    }

    /**
     * @author 4532
     *
     * Desciption: Recommended Product Information.
     *
     * @param integer product id
     *
     * @return product related information
     *
     * @Route("/recommended-product/{productId}",
     * 	name="officebrain_product_bundle_product_recommendedproduct", options={"expose"=true}
     * )
     *
     * @Template("OfficeBrainProductBundle:Product:recommendedProduct.html.twig")
     *
     */

    public function recommendedProductAction($productId)
    {
    	$this->initAction();

    	$recommendedProductIds = $this->productDetailManager->getRecommendedProductDetailInfo($productId, $this->cultureCode);
    	$this->responseArray['recommended_products'] = array();
    	if ($recommendedProductIds == null) {

    		return $this->responseArray;
    	}
    	foreach($recommendedProductIds['recommendedProducts'] as $rpi){
    		$recommendedProductInfo = $this->productDetailManager->getProductDetailById($rpi['recommendedProductId'], $this->cultureCode);
    		$this->responseArray['recommended_products'][] = $recommendedProductInfo[$rpi['recommendedProductId']];
    	}
    	return $this->responseArray;
    }

    /**
     * @author 4846
     *
     * Desciption: logo everything from virtual
     *
     * @return JSON Response
     *
     * @Route("/logo-everything/{sequenceid}",
     * 	name="officebrain_product_bundle_logo_everything", options={"expose"=true}
     * )
     */

    public function logoEverythingAction()
    {
    	$this->initAction();
    	$sequenceid=$this->request->get('sequenceid');
    	$this->session->set('virtualsequenceid', $sequenceid);
    	$logoeverything['status']="success";
    	return new JsonResponse($logoeverything);
    }

    /**
     * @author 4505
     *
     * Desciption: Remove logo everything from virtual
     *
     * @return JSON Response
     *
     * @Route("/remove-logo-everything",
     * 	name="officebrain_product_bundle_remove_logo_everything", options={"expose"=true}
     * )
     */
    
    public function removeLogoEverythingAction()
    {
    	$this->initAction();
    	$this->session->remove('virtualsequenceid');
    	$logoeverything['status']="success";
    	return new JsonResponse($logoeverything);
    }
    /**
	 * @author Employee Id: 4532
	 *
	 *   Check remote file avaibility.
	 *
	 *  @param string product sku
	 *
	 *  @param integer supplier id
	 *
	 *  @return download product image zip
	 *
	 * @Route("/check-file-exist", name="officebrain_product_bundle_check_file_exist",
	 * options={"expose"=true}
	 * )
	 * @Template()
	 */
	public function checkRemoteFileAvaibilityAction()
	{
		$this->initAction();

		$productSKU = $this->request->get('productSKU');
		$supplierId = $this->request->get('supplierId');
		$type = $this->request->get('type');
		if($type == 'pdf'){
			$fileType = 'Template';
		}else{
			$fileType = 'Images';
		}
		if($productSKU && $supplierId) {
			if($this->productDetailManager->checkRemoteFileAvaibility($productSKU, $supplierId, $type)){
				return new JsonResponse(array('status'=>'success'));
			}else{
				return new JsonResponse(array('status'=>'error','message' => $fileType.' File not Found'));
			}
		}

		return;
	}
	/**
	 *  @author
	 *   Inventory
	 *
	 *  @param string product id
	 *
	 *  @return Reponse
	 *
	 *
	 * @Route("/product-check-inventory",
	 *  name="officebrain_product_bundle_product_load_inventory_popup",
	 *  requirements={"_locale"="en_us"}, options={"expose"=true},
	 * )
	 * @Template()
	 */
	public function loadInventoryPopupAction() {
	    $request = $this->getRequest();
	    $data['sku'] = $request->get( 'sku');
	    $data['slug'] = $request->get( 'slug');
	    return $data;
	}

	/**
	 *  @author
	 *   Inventory
	 *
	 *  @param string product id
	 *
	 *  @return Reponse
	 *
	 *
	 * @Route("/product-check-inventory-call",
	 *  name="officebrain_product_bundle_product_load_inventory_popup_call",
	 *  requirements={"_locale"="en_us"}, options={"expose"=true},
	 * )
	 * @Template()
	 */
	public function loadInventoryPopupCallAction() {
	    return array();
	}


	/**
	 *  @author
	 *   Inventory
	 *
	 *  @param string product id
	 *
	 *  @return Reponse
	 *
	 *
	 * @Route("/product-check-inventory-web-service",
	 *  name="officebrain_product_bundle_product_check_inventory_web_service",
	 *  requirements={"_locale"="en_us"}, options={"expose"=true},
	 * )
	 * @Template()
	 */
	public function checkInventoryWebServiceAction() {


	    $this->initAction();

	    $response =array();

	    $this->request = $this->getRequest ();
	    $skuStr = $this->request->get('productSku', null);
	    $skuAry = explode("-",$skuStr);
	    $sku = trim($skuAry[0]);
	    $slug = $this->request->get('productSlug', null);
	    $qty = $this->request->get('qty', null);
	    $error = false;


	    $localizationCountry = 'US';
	    $localizationLanguage = 'en';
	    $inventoryData = array();
	    $responseData = array();

	    $token = $this->container->get('security.context')->getToken();
	    $sessionUser = $token->getUser();
	    $isLoggedIn = 0;
	    if(is_object($sessionUser ))$isLoggedIn  = 1;
	    $responseData['is_logged_in'] = $isLoggedIn  ;

	    $wsdlUserPwdProductData= array('id'=>'99990005','pwd'=>'f1677f1164084a19a6e1f7bf4a6472f2','wsVersion'=>'1.0.0');
	    $evnasWsdlUserPwd = array('id'=>'99990005','pwd'=>'f1677f1164084a19a6e1f7bf4a6472f2','wsVersion'=>'1.2.1');
	    $isSameDesc = true;
	    $AllColorAry = array();
	    //PHP5 now supports soap client and soap server
	    //Use default class for soap service
	    if (version_compare(phpversion(), '5.3.10', '>')) {
	        //If PHP is higher than 5.3.10, than use default PHP class
	        $client = new \SoapClient('https://psapi.goldstarpens.com/PSInventory/GsInventoryService.svc?singleWsdl');
	        $response = $client->getInventoryLevels(array('productID'=>$sku,'id'=>$evnasWsdlUserPwd['id'],'password'=>$evnasWsdlUserPwd['pwd'],'wsVersion'=>$evnasWsdlUserPwd['wsVersion']));  //call this to get response from server

	        if($response->errorMessage && trim($response->errorMessage)!=''){
	            $responseData ['error'] = $error = $response->errorMessage;
	        }else if(isset($response->ProductVariationInventoryArray)){
	            $lastDesc = '';
	            $response = $response->ProductVariationInventoryArray;
	            $response = $response->ProductVariationInventory;

	            foreach ($response as $resData){
	                if(isset($resData->quantityAvailable)){
	                    if($lastDesc != '' && $lastDesc != trim($resData->partDescription)){ $isSameDesc = false;break; }
	                    $lastDesc = trim($resData->partDescription);
	                }
	            }


	            foreach ($response as $key=>$resData)
	            {
	                if(isset($resData->quantityAvailable)){
	                    $thisQty = (int)$resData->quantityAvailable;
	                    $originalColor = $thisColor =  trim($resData->attributeColor);
	                    $thisColor = str_replace('Trans ','Translucent ',$thisColor);
	                    if(!array_key_exists($thisColor,$productColorAry)){
	                        $thisColor = str_replace('Trans ','Transparent ',$originalColor);
	                    }

	                    if($isSameDesc===false || array_key_exists($thisColor,$productColorAry)){
	                        $inventoryData[$key]['qty'] = $thisQty;
	                        if(array_key_exists($thisColor,$productColorAry)){
	                            $inventoryData[$key]['color_image'] =  $productColorAry[$thisColor];
	                        }else if(array_key_exists($thisColor,$AllColorAry)){
	                            $inventoryData[$key]['color_image'] =  $AllColorAry[$thisColor];
	                        }
	                        $inventoryData[$key]['color'] = $thisColor;
	                        $inventoryData[$key]['desc'] = $resData->partDescription;
	                        $inventoryData[$key]['partId'] = $resData->partID;

	                    }
	                }
	            }
	        }
	    }

	    $clientProductData = new \SoapClient('https://psapi.goldstarpens.com/PSProductData/GsProductDataService.svc?singleWsdl');
	    $responseProductData = $clientProductData->getProduct(array('productId'=>$sku,'id'=>$wsdlUserPwdProductData['id'],'password'=>$wsdlUserPwdProductData['pwd'],'wsVersion'=>$wsdlUserPwdProductData['wsVersion'],'localizationCountry'=>$localizationCountry,'localizationLanguage'=>$localizationLanguage));
      //echo "<pre>";

      //print_r($responseProductData);die;
        foreach ($responseProductData as $key=>$resData){
            foreach($resData->ProductPartArray as $responseProductPartData){
                foreach($responseProductPartData as $key => $value){
                   $responseData['productDataDesc'][] = $value->description;
                   $responseData['productDataPartID'][] = $value->partId;
                   $responseData['productDataColor'][] = $value->ColorArray->Color->colorName;
                   $responseData['productDataColorHex'][] = $value->ColorArray->Color->hex;

                }
             }
         }
	     if(count($inventoryData)<=0){
	        if($setDefaultManufactureProduct || (!isset($responseData ['error']))){
	            foreach ($productColorAry as $colorName=>$colorImg){
	                $thisAry = array();
	                $thisAry['show_chat'] = 0;
	                $thisAry['qty'] = 0;
	                $thisAry['color'] = $colorName;
	                $thisAry['color_image'] = $colorImg;
	                $inventoryData[] = $thisAry ;
	            }
	            $responseData ['inventory_data'] = $inventoryData;
	            $responseData ['no_desc'] = 1;
	        }
	    }else{
	        $responseData ['inventory_data'] = $inventoryData;
	    }
      //print_r($responseData['productDataColorHex']);die;
    //print_r($responseData['productDataDesc']);exit;
	    return $responseData;
	  }

	   /**
     * @author Employee Id: 6804
     *
     * Desciption: sample order detail model.
     *
     * @param senderName,fromEmail,recepientEmail,message,url.
     *
     * @return json Response
     *
     * @throws null
     *
     * @Route("/order-sample", name="officebrain_product_bundle_product_ordersample",
     * options={"expose"=true}
     * )
     * @Template("OfficeBrainProductBundle:Product:orderSample.html.twig")
     */
    public function orderSampleAction()
    {   
    	$this->initAction();
        $this->projectUserSetting =$this->request->get('project_user_setting')['user_data'];
        $user_id=$this->projectSetting['user_id'];
        $orderSample = null;
        $productId = $this->request->get('product_id', null); 
		$form_type = $this->request->get('form_type', "request_sample"); 
        $productDetailArray = $this->productDetailManager->getProductDetailById($productId, $this->cultureCode);
        // echo $productId;
        // echo "<pre>";print_R(\Doctrine\Common\Util\Debug::dump($productDetailArray[$productId]));echo "</pre>";
        $isSize=$productDetailArray[$productId]['is_size'];
        $productColorData=$productDetailArray[$productId]['attributes'];
        $productColorArray=array(''=>'Select color');
        foreach($productColorData as $colorattribute){
           if($colorattribute['label']=='Colors'){
                foreach($colorattribute['values'] as $color){
                    $productColorArray[$color]=$color;

                }
            }
        }

        $productSizeArray=array();
        if($isSize==1){
        $productSizeArray=array(''=>'Select size');  
        foreach($productColorData as $colorattribute){
           if($colorattribute['label']=='Size'){
                foreach($colorattribute['values'] as $size){
                    $productSizeArray[$size]=$size;

                }
            }
        }

        }
        
    	$this->form = $this->createForm(new OrderSampleType($form_type,$productColorArray,$productSizeArray),new OrderSample(), array(
                'action' => $this->generateUrl('officebrain_product_bundle_product_ordersample',array("product_id"=>$this->request->query->get('product_id'),"form_type"=>$form_type))
        ));

    	if($this->request->getMethod() == 'POST'){
            $userinfo['user_id'] =$this->projectSetting['user_id'];
            $userinfo['instance_type'] = $this->projectSetting['instance_type'];
            $userinfo['instance_id'] = $this->projectSetting['instance_id'];
            $productData['product_id']=$productId;
            $productData['sku_number']=$productDetailArray[$productId]['basic_information']['sku_number'];
			$this->form->bind( $this->request );

	    	if ($this->form->isValid()) {

				$orderSampleData = $this->form->getData();
                if(isset($_POST['g-recaptcha-response']) && $_POST['g-recaptcha-response']!=''){
                    $captcha=$_POST['g-recaptcha-response'];
            
                    $secretKey = "6LdFSNYjAAAAAIRwiVnI4UJIfjq1oCbzWuSFQ9a-";
                    $url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secretKey) .  '&response=' . urlencode($captcha);
                    $response = file_get_contents($url);
                    $responseKeys = json_decode($response,true);
                }

                if($responseKeys['success']!=1){

                    $this->responseArray['form_status'] = 'error';
                    $this->responseArray['captcha_error'] = 'Oops, you have to check the recaptcha !';
                            
                }else{
    				$add = $this->productDetailManager->addOrderSample($orderSampleData, $productData,$userinfo);
                    $isSendEmail = false;
    				switch ($add['status']) {
    					case  'SUCCESS' :
                            $isSendEmail = true;
    						$this->responseArray['status'] = 'success';
                            if($form_type=='request_sample'){
    						$this->responseArray['email_success_message'] = $this->translator->trans('Request Sample saved successfully');
                            }else{
                                $this->responseArray['email_success_message'] = $this->translator->trans('Ask Question saved successfully');

                            }
    						  break;
    					case  'FAIL':
    						$this->responseArray['form_status'] = 'error';
    						$this->responseArray['email_success_message'] = $this->translator->trans('email.success');
    								break;
    				}
            }

	            //$isSendEmail = true;
				if($isSendEmail){
					$from =  $this->projectSetting['admin_email'];
					$to   = $this->form->get('email')->getData();
                    $data['product_detail']=$productDetailArray[$productId];
                    $data['color']=$this->form->get('color')->getData();
                    $data['size']=$this->form->get('size')->getData();
                    $data['firstName']=$this->form->get('firstName')->getData();
                    $data['lastName']=$this->form->get('lastName')->getData();
                    $data['email'] =$to;
                    $data['phone'] =$this->form->get('phone')->getData();
                    $data['companyName'] =$this->form->get('companyName')->getData();
                    $data['comment'] = $this->form->get('comment')->getData();
                    if($data['comment']==''){
                      $data['title'] ='Request Sample';
                      $eventKey = 'request_sample_email';
                    }else{
                       $data['title']='Ask Question';
                       $eventKey = 'ask_question_email'; 
                    }

					$productDetailHTML=$this->twigManager->render('OfficeBrainProductBundle:Product:productDetailRequestSampleEmailTemplate.html.twig',array('data'=>$data));
                    if($data['comment']==''){
					$response = array('send_request_sample_mail_template' => $productDetailHTML);
                    }else{
                    $response = array('send_ask_question_mail_template' => $productDetailHTML);
                    }
					$this->emailService->sendMail($eventKey, $to, $response, $this->locale, $from);
	
					unset($orderSample);
					unset($this->form);
					unset($firstName);
					unset($from);
					unset($to);
					unset($params);
				}
                

				return new JsonResponse($this->responseArray);
	    	} else {
	    		return new JsonResponse($this->commonLibraryManager->prepareFormJsonError($this->form));
	    	}
    	}
        $this->responseArray['user_data']= $this->userManager->getUserByIdArray($user_id);
		$this->responseArray['form'] = $this->form->createView();
        $this->responseArray['product_detail'] = $productDetailArray[$productId];
        $this->responseArray['product_size']=$productSizeArray;
		$this->responseArray['form_type'] = $form_type;
    	unset($orderSample);
    	unset($this->form);
    	return $this->responseArray;
    }
}
