<?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 Nelmio\ApiDocBundle\Annotation\ApiDoc;
use OfficeBrain\Bundle\SearchBundle\Form\Type\ProductSearchType;
use OfficeBrain\Bundle\SearchBundle\Form\Data\ProductSearchData;
use Symfony\Component\HttpFoundation\Session\Session;
/**
 * @author Employee Id: 5052
 *
 *   Product Detail data.
 *
 *  @param string product slug
 *
 *  @return product detail information
 *
 * @Route("/api/v1")
 * */
class ApiProductController extends ProductController
{
	
	/**
	 *
	 * @author Employee Id: 410175
	 *  
	 * To set member variables default value
	 * 
	 * @return NULL
	 */
	public function __construct()
	{		
		parent::__construct();
		$this->responseFormat = null;
	}
	
	/**
	 *
	 * @author Employee Id: 4532
	 *
	 * Create various objects required action in this class
	 *
	 * @return NULL
	 */
	public function initAction()
	{
		parent::initAction();
		$this->request = $this->getRequest();
		$this->responseFormat = $this->request->get('_format', null) ;
		$this->userId = $this->projectSetting['user_id'];
		$this->wishListManager = $this->get('office_brain_wish_list_manager');
		$this->color_attribute_id = $this->projectSetting['configuration_rule']['transaction']['shopping_cart']['color_attribute_id'];
		$this->size_attribute_id = $this->projectSetting['configuration_rule']['transaction']['shopping_cart']['size_attribute_id'];
		$this->colorImageUrl = $this->container->getParameter('api.color_image_base_url');		
	}
	
	/*
	 * @author Employee Id: 5052
	 *
	 *   Product Detail data.
	 *
	 *  @param string product slug
	 *
	 *  @return product detail information
	 *
	 * @Route("/{_locale}/product/{productSlug}",
	 * 	name="officebrain_product_bundle_product_detail_api",
	 * )
	 * @ApiDoc(
	 *      resource=true,
	 *      section="Product-Detail",
	 *      description="Return the Product Details",
	 *      statusCodes={
	 *              1="Returned when success",
	 *              403="Returned when the user is not authorized to see this link",
	 *              0="Returned when form validation is failed",
	 *      },
	 *      requirements={
	 *      		{"name"="_locale", "default"="en_us","dataType"="string"},
     *             {"name"="access_token", "dataType"="string", "required"=false, "description"="valid access token"},
     *      }
	 * )
	 * @method({"GET"})
	 * @Template()
	 *
	 * /
	public function productDetailAction($productSlug)
	{
		$this->initAction();
		
		$wishListProducts = array();
		if( $this->userId > 0 ){
			$this->wishListManager->getWishListId();
			$wishListProducts = $this->wishListManager->productIdArray;
		}
		
		$this->initAction();
		$this->responseArray = 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) {
			return array('status'=>'error','status_code'=>0, 'message' => 'No product found');
			// 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) ){
			return array('status'=>'error','status_code'=>0, 'message' => 'No product found');
			//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);
		}
		
		// Product Tag section Starts 
		if(isset($this->productConfigurationRules['show_product_tags']['status'])&&$this->productConfigurationRules['show_product_tags']['status'] == 1){
			$this->responseArray['product_tags_array'] = $this->productDetailManager->getAllTagsByProductSku($this->responseArray['basic_information']['sku_number']);
		}
		// Product Tag section Ends 
		
		$this->productDetailManager->recentViewProductByCookies('recent_product_cookie', $this->responseArray['product_id'], $this->cultureCode);
		unset($productDetailArrayId);
		$data = $this->responseArray;
		
		//$data = parent::productDetailAction( $productSlug );
		
		if($this->responseFormat == 'json'){
			if( is_array($data) ){
				if(isset($data['pricing']['decorative']) && count($data['pricing']['decorative'])>0){
		        	foreach ($data['pricing']['decorative'] as $priceKey=>$priceData){		        		
		        		if($priceData['to']=='')$data['pricing']['decorative'][$priceKey]['to']=0;
		        		if($priceData['from']=='')$data['pricing']['decorative'][$priceKey]['from']=0;
		        		if(isset($priceData['rate']))$data['pricing']['decorative'][$priceKey]['rate'] = (double)$priceData['rate'];
		        		if(isset($priceData['rate_orig']))$data['pricing']['decorative'][$priceKey]['rate_orig'] = (double)$priceData['rate_orig'];
		        	}
		        }
				if(isset($data['pricing']['blank']) && count($data['pricing']['blank'])>0){
		        	foreach ($data['pricing']['blank'] as $priceKey=>$priceData){		        		
		        		if($priceData['to']=='')$data['pricing']['blank'][$priceKey]['to']=0;
		        		if($priceData['from']=='')$data['pricing']['blank'][$priceKey]['from']=0;
		        		if(isset($priceData['rate']))$data['pricing']['blank'][$priceKey]['rate'] = (double)$priceData['rate'];
		        		if(isset($priceData['rate_orig']))$data['pricing']['blank'][$priceKey]['rate_orig'] = (double)$priceData['rate_orig'];
		        	}
		        }
		        
				if(isset($data['pricing_for_other_country'])){
					foreach ($data['pricing_for_other_country'] as $countryName=>$priceType){						
						foreach ($priceType as $typeKey=>$typeData){						
							foreach ($typeData as $priceKey=>$priceData){								
								if($priceData['to']=='')$data['pricing_for_other_country'][$countryName][$typeKey][$priceKey]['to']=0;
		        				if($priceData['from']=='')$data['pricing_for_other_country'][$countryName][$typeKey][$priceKey]['from']=0;
		        				if(isset($priceData['rate']))$data['pricing_for_other_country'][$countryName][$typeKey][$priceKey]['rate'] = (double)$priceData['rate'];
		        				if(isset($priceData['rate_orig']))$data['pricing_for_other_country'][$countryName][$typeKey][$priceKey]['rate_orig'] = (double)$priceData['rate_orig'];
							}
						}
		        	}
		        }
		         if(isset($data['images']) && count($data['images'])>0){
		        	foreach ($data['images'] as $iKey=>$imgData){
		        		foreach ($imgData as $imgKey=>$img){
			        		if($img==""){
			        			$data['images'][$iKey][$imgKey] = null;
			        		}else if(is_numeric($img)){
			        			$data['images'][$iKey][$imgKey] = (double)$img;
			        		}
		        		}
		        	}
		        }
		        if(isset($data['imprint_methods']) && count($data['imprint_methods'])>0){
		        	$newImrpintData = array();
		        	foreach ($data['imprint_methods'] as $iKey=>$iData){
		        		$newImrpintData[] = array('key'=>$iKey,'value'=>$iData);
		        	}
		        	$data['imprint_methods'] = $newImrpintData;		        	
		        }
		        if(isset($data['imprint_position_and_methods']) && count($data['imprint_position_and_methods'])>0){
		        	$newImrpintPositionData = array();
		        	foreach ($data['imprint_position_and_methods'] as $iKey=>$iData){
		        		$innerData = $iData;
		        		if(isset($iData['imprint_method'])){
		        			$innerDataImprintMethod = array();
		        			foreach ($iData['imprint_method'] as $k=>$v){
		        				$innerDataImprintMethod[] = array('key'=>$k,'value'=>$v);
		        			}
		        			$innerData['imprint_method'] = $innerDataImprintMethod; 
		        		}
		        		$newImrpintPositionData[] = $innerData;
		        	}
		        	$data['imprint_position_and_methods'] = $newImrpintPositionData;
		        }
		       if(isset($data['imprint_information']) && isset($data['imprint_information']['standard_imprint_color_information']) && count($data['imprint_information']['standard_imprint_color_information'])>0){
		        	$newImprintColor = array();
		        	foreach ($data['imprint_information']['standard_imprint_color_information'] as $iKey=>$iData){		        		
		        		$newImprintColor[] = array('key'=>$iKey,'value'=>$iData);
		        	}
		        	$data['imprint_information']['standard_imprint_color_information'] = $newImprintColor;
		        }
		        if(isset($data['imprint_information']) && isset($data['imprint_information']['imprint_method_information']) && count($data['imprint_information']['imprint_method_information'])>0){		        	
		        	$data['imprint_information']['imprint_method_information'] = array_values($data['imprint_information']['imprint_method_information']);
		        }
		        
		        if(isset($data['attributes']) && count($data['attributes']) > 0){
		        	foreach ($data['attributes'] as $attrKey=>$attr){
		        		if($attr['id'] == $this->color_attribute_id){
		        			if(isset($attr['values']) && count($attr['values']) > 0){
		        				$newColorValueAry = array();
		        				foreach ( $attr['values'] as $colorId => $colorName ){
		        					$newColorValueAry[] = array('color_id'=>$colorId, 'color_name'=>$colorName, 'color_image'=>$this->colorImageUrl.$colorId.'.jpg') ;
		        				}
		        				$data['new_attributes']['color'] = $attr;
		        				$data['new_attributes']['color']['values'] = $newColorValueAry;
		        			}
		        		}
		        		if($attr['id'] == $this->size_attribute_id){
		        			if(isset($attr['values']) && count($attr['values']) > 0){
		        				$newColorValueAry = array();
		        				foreach ( $attr['values'] as $colorId => $colorName ){
		        					$newColorValueAry[] = array('size_id'=>$colorId, 'size_name'=>$colorName) ;
		        				}
		        				$data['new_attributes']['size'] = $attr;
		        				$data['new_attributes']['size']['values'] = $newColorValueAry;
		        			}
		        		}
		        	}
		        }
		        
		        if(count($wishListProducts)>0 && in_array($data['product_id'],$wishListProducts)){
		        	$data['is_wishlist_product'] = 1;
		        }else{
		        	$data['is_wishlist_product'] = 0;
		        }
				return array('status'=>'success','status_code'=>1 , 'data' => $data);
			}
		}
		return $data;
	}
	
	/**
	 * @author 410175
	 *
	 * Desciption: Related Product Information.
	 *
	 * @param integer product id
	 *
	 * @return product related information
	 *
	 * @Route("/{_locale}/related-product/{productId}", name="officebrain_product_bundle_product_relatedproduct_api")
	 *
	 * @ApiDoc(
	 *      resource=true,
	 *      section="Product-Detail",
	 *      description="Return the Related Product list",
	 *      statusCodes={
	 *              1="Returned when success",
	 *              403="Returned when the user is not authorized to see this link",
	 *              0="Returned when form validation is failed",
	 *      },
	 *      requirements={
	 *      		{"name"="_locale", "default"="en_us","dataType"="string"},
     *             {"name"="access_token", "dataType"="string", "required"=false, "description"="valid access token"},
     *      }
	 * )
	 * @method({"GET"})
	 *
	 * @Template()
	 *
	 * / 
	
	public function relatedProductAction($productId)
	{	
		$data = parent::relatedProductAction($productId);
		
		if($this->responseFormat == 'json'){
			return array('status'=>'success','status_code'=>1 , 'data' => $data);
		}
		
		return $data ;
	}
	
	/**
	 * @author Employee Id: 410175
	 *
	 * Desciption: Inventory Lookup
	 *
	 * @param video_url.
	 *
	 * @return json Response
	 *
	 * @Route("/product-inventory-lookup",name="officebrain_product_bundle_product_inventory_lookup_api")
	 * 
	 * @ApiDoc(
	 *      resource=true,
	 *      section="Product-Detail",
	 *      description="get inventory hookup detail",
	 *      statusCodes={
	 *              1="Returned when success",
	 *              403="Returned when the user is not authorized to see this link",
	 *              0="Returned when form validation is failed",
	 *      },
	 *      requirements={
	 *      		{"name"="_locale", "default"="en_us","dataType"="string"},
     *             	{"name"="access_token", "dataType"="string", "required"=false, "description"="valid access token"},
     *             	{"name"="itemno", "description"="valid product SKU","dataType"="string"},
     *      }
	 * )
	 * 
	 * @Template()
	 * @Method("POST")
	 * /
    public function productInventoryLookupAction()
	{
		$this->initAction();
		
		$itemNo = $this->request->get("itemno");
		$inventoryHookupData = $this->productDetailManager->getProductInventoryDetails( $itemNo );
		$inventoryHookupData = $this->convertObjectToArray($inventoryHookupData);
		
		$errorMsg = null;
		if(!isset($inventoryHookupData) || (isset($inventoryHookupData[0])&&$inventoryHookupData[0] == 'NORECORDFOUND')){
			$errorMsg = 'Data Not Available';	
		}else{
			if(isset($inventoryHookupData['lstItemInv'])&&count($inventoryHookupData['lstItemInv'])<=0){
				$inventoryHookupData['lstItemInv'] = null;
			}else if(isset($inventoryHookupData['lstItemInv']['ItemInventory']) && !isset($inventoryHookupData['lstItemInv']['ItemInventory'][0])){
				$inventory = $inventoryHookupData['lstItemInv']['ItemInventory'];
				unset($inventoryHookupData['lstItemInv']);
				$inventory['color'] = (($inventory['color_image_url']===false)?null:$inventory['color_image_url']);
				$inventoryHookupData['lstItemInv']['ItemInventory'][] = $inventory;
			}else if(isset($inventoryHookupData['lstItemInv']['ItemInventory']) && count($inventoryHookupData['lstItemInv']['ItemInventory'])>0){
				foreach ($inventoryHookupData['lstItemInv']['ItemInventory'] as $key=>$inventoryObj){
					
				    
				    $inventoryHookupData['lstItemInv']['ItemInventory'][$key]['color'] = (($inventoryObj['color_image_url']===false)?null:$inventoryObj['color_image_url']);
				}
			}
		}
		
		if($errorMsg != null){
			return array('status'=>'error','status_code'=>0,'message'=>$errorMsg);
		}else{
			return array('status'=>'success','status_code'=>1,'data'=>$inventoryHookupData);
		}
	}
	
	public function convertObjectToArray($object){
	    $object = (array)$object;
	    foreach ($object as $objKey=>$objValue){
	        if(is_object($objValue) || is_array($objValue)){
	            $object[$objKey] = $this->convertObjectToArray($objValue);
	        }
	    }
	    return $object; 
	}*/
}
