<?php

namespace OfficeBrain\Bundle\TaxBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\JsonResponse;
use OfficeBrain\Bundle\TaxBundle\Form\TaxMasterType as TaxMasterType;
use OfficeBrain\Bundle\TaxBundle\Form\EditTaxMappingType as EditTaxMappingType;


class ShippingTaxAdminController extends Controller
{
	/**
	 *
	 * @author Employee Id: 4471
	 * To set member variables default value
	 * @return NULL
	 */
	public function __construct()
	{
		$this->request = null;
		$this->user = null;
		$this->userId = null;
		$this->locale = null;
		$this->cultureId = null;
		$this->cultureProductId = null;
		$this->refererUrl = null;
		$this->productIdArray = null;
		$this->responseArray = array();
		$this->projectSetting = null;
		$this->productCultureIdArray = null;
		$this->productId = null;
		$this->productSlug = null;
		$this->productCultureId = null;
		$this->commonLibraryManager = null;
		$this->config = null;
		$this->productDetailconfigurationRule = null;
		$this->erpIntegration = null;
		$this->coreManager = null;
	}
	
	/**
	 *
	 * @author Employee Id: 4471
	 * To unset member variables
	 * @return NULL
	 */
	public function __destruct()
	{
		unset($this->user);
		unset($this->userId);
		unset($this->locale);
		unset($this->request);
		unset($this->refererUrl);
		unset($this->cultureId);
		unset($this->cultureProductId);
		unset($this->responseArray);
		unset($this->projectSetting);
		unset($this->productCultureIdArray);
		unset($this->productId);
		unset($this->productSlug);
		unset($this->productCultureId);
		unset($this->commonLibraryManager);
		unset($this->config);
		unset($this->productDetailconfigurationRule);
		unset($this->erpIntegration);
		unset($this->coreManager);
	}
	
	
	/**
	 *
	 * @author Employee Id: 4471
	 * Create various objects required action in this class
	 * @return NULL
	 */
	public function initAction()
	{
		$this->request = $this->getRequest();
		$this->productId = $this->request->get('product_id', null);
		$this->productSlug = $this->request->get('product_slug', null);
		$this->productCultureId = $this->request->get('culture_product_id', null);
		$this->projectSetting = $this->request->get('project_setting');
		$this->siteOwnerId = $this->projectSetting['site_owner_id'];
		$this->projectUserSetting = $this->request->get('project_user_setting');
		$this->user = $this->projectUserSetting['user_data'];
		$this->locale = $this->projectSetting['culture_code'];
		$this->userId = $this->projectSetting['user_id'];
		$this->instanceType = $this->projectSetting['instance_type'];
		$this->responseArray['product_id'] = $this->productId;
		$this->responseArray['status'] = 'error';
		$this->configurationRule = $this->projectSetting['configuration_rule']['transaction']['tax_management'];
		$this->taxManager = $this->get('office_brain_shipping_tax_manager');
		$this->commonLibraryManager = $this->get('office_brain_common_library');
		$this->sessionManager = $this->get('office_brain_session_manager');
		$this->productDetailManager = $this->get('office_brain_product_detail_manager');
		$this->coreManager = $this->get('office_brain_core_manager');
		$this->productDetailconfigurationRule = $this->projectSetting['configuration_rule']['transaction']['shopping_cart']['product_detail_popup'];
		$this->validationManager = $this->get('office_brain_validation_manager');
		$this->userContactBookManager = $this->get('office_brain_user_contact_book_manager');
		$this->userManager = $this->get('office_brain_user_manager');
		$this->erpIntegration = $this->projectSetting['configuration_rule']['erp_integration'];
		$this->page = $this->request->get('page', '1');
		$this->recordsPerPage = 10;
		$this->culture = $this->projectSetting['culture_code'];
		$this->searchManager = $this->get('office_brain_search_manager');
	}
	
	/**
	 * @author Employee Id: 4471
	 * Description :get listing of tax master
	 * @param 1 : No paramater
	 * @throws Exception: Null
	 *
	 * @Route("/admin/{_locale}/tax-master-list",
	 * name="office_brain_taxbundle_taxadmin_taxmaster_list",
	 * options={"expose"=true}
	 * )
	 * @Template("OfficeBrainTaxBundle:TaxAdmin:adminTaxMasterList.html.twig")
	 */
	public function getTaxMasterListAction()
	{
		$this->initAction();
		$this->responseArray['records_per_page'] = $this->recordsPerPage;
		$this->responseArray['page'] = $this->page;
		$this->responseArray['data'] = $this->taxManager->getTaxMasterList($this->page,$this->recordsPerPage);
		return $this->responseArray;
	}
	
	
	/**
	 *
	 * @author Employee Id: 4471
	 * Description : Change Status tax master.
	 * @param 1 : tex Id
	 * @return type : JsonResponse object
	 * @throws Exception: No exception
	 * @Route("/admin/{_locale}/tax-master-change-status", name="office_brain_taxbundle_taxadmin_taxmaster_status_change",
	 * options={"expose"=true}
	 * )
	 * @Template()
	 */
	public function changeStatusTaxMasterAction()
	{
		$this->initAction();
		$id = $this->request->get('id');
		if ($id) {
			$status = $this->taxManager->changeTaxMasterStatus($id);
			if ($status) {
				return new JsonResponse(array('status' => 'success', 'status_message' => $this->get('translator')->trans('admin.tax_master.message.status_success')));
			}
		}
		return new JsonResponse(array('status' => 'fail', 'status_message' => $this->get('translator')->trans('admin.tax_master.message.status_error')));
	}
	
	/**
	 *
	 * @author Employee Id: 4471
	 * Description : delete tax master.
	 * @param 1 : tex Id
	 * @return type : JsonResponse object
	 * @throws Exception: No exception
	 * @Route("/admin/{_locale}/tax-master-delete", name="office_brain_taxbundle_taxadmin_taxmaster_delete",
	 * options={"expose"=true}
	 * )
	 * @Template()
	 */
	public function deleteTaxMasterAction()
	{
		$this->initAction();
		$tax_master_id = $this->request->get('id');
		$result= $this->taxManager->deleteTaxMaster($tax_master_id);
		if($result['status']=='success')
		{
			return new JsonResponse(array('status' => 'success', 'page_url' => $this->generateUrl('office_brain_taxbundle_taxadmin_taxmaster_list')));
		}
		else
		{
			return new JsonResponse(array('status' => 'error', 'error_message' => $this->get('translator')->trans('admin.tax_master.message.delete_error')));
		}
	}
	
	
	/**
	 * @author Employee Id: 4471
	 * Description : add tax master
	 * @Route("admin/{_locale}/tax-master-add", name="office_brain_taxbundle_taxadmin_taxmaster_add", options={"expose"=true})
	 * @method({"GET,POST"})
	 * @Template("OfficeBrainTaxBundle:TaxAdmin:adminTaxMasterAdd.html.twig") 
	 */
	public function addTaxMasterAction()
	{
		$this->initAction();
		$this->type = $this->configurationRule['option']['shipping_tax']['option']['type'];
		$this->form = $this->createForm(new TaxMasterType($this->type,'add',''));
		$this->responseArray['form'] = $this->form->createView();
		if ($this->request->getMethod() == 'POST')
		{
	        $this->form = $this->createForm(new TaxMasterType($this->type,'add',''));
	        $this->form->handleRequest($this->request);
	    	if ($this->form->isValid()) {
	    		$status = $this->taxManager->addTaxMaster($this->form->getData());
	    		if ($status!='SUCCESS') {
	    			$this->response ['status'] = 'success';
	    			$this->response['success_message']  = $this->get('translator')->trans('admin.tax_master.message.add_success_msg');
	    			$this->response['close_modal']  = true;
	    		} else {
					$this->response ['status'] = 'error';
					$this->response['error_message']  = $this->get('translator')->trans('admin.tax_master.message.add_error_msg');
					$this->response['close_modal']  = true;
				}
		   	}
		   	else 
		   	{
	   			$this->response = $this->commonLibraryManager->prepareFormJsonError($this->form);
	    	}
	    	return new JsonResponse($this->response);
    	}
		return $this->responseArray;
	}
	
	/**
	 * @author Employee Id: 4471
	 * Description : edit tax master
	 * @Route("admin/{_locale}/tax-master-edit", name="office_brain_taxbundle_taxadmin_taxmaster_edit", options={"expose"=true})
	 * @method({"GET,POST"})
	 * @Template("OfficeBrainTaxBundle:TaxAdmin:adminTaxMasterEdit.html.twig")
	 */
	public function editTaxMasterAction()
	{
		$this->initAction();
		$taxId= $this->request->get('id');
		$this->taxMasterdetail = $this->taxManager->getTaxMasterById($taxId);
		$this->type = $this->configurationRule['option']['shipping_tax']['option']['type'];
		$this->form = $this->createForm(new TaxMasterType($this->type , 'edit',$taxId),$this->taxMasterdetail);
		$this->responseArray['form'] = $this->form->createView();
		if ($this->request->getMethod() == 'POST')
		{
			
			$this->form = $this->createForm(new TaxMasterType($this->type,'edit',$taxId));
			$this->form->handleRequest($this->request);
			if ($this->form->isValid()) {
				$taxArray= $this->request->get('tax_master');
				$taxId=$taxArray['id']; 
				$result= $this->taxManager->deleteTaxMaster($taxId);
				if($result['status']=='success')
				{
					$status = $this->taxManager->addTaxMaster($this->form->getData());
					if ($status!='SUCCESS') {
						$this->response ['status'] = 'success';
						$this->response['success_message']  = $this->get('translator')->trans('admin.tax_master.message.add_success_msg');
						$this->response['close_modal']  = true;
					} else {
						$this->response ['form_status'] = 'error';
						$this->response['error_message']  = $this->get('translator')->trans('admin.tax_master.message.add_error_msg');
						$this->response['close_modal']  = true;
					}
				}
				else
				{
					$this->response ['form_status'] = 'error';
					$this->response ['error_message'] = $this->get('translator')->trans('admin.tax_master.message.edit_error_msg');
				}
			}
			else
			{
				$this->response = $this->commonLibraryManager->prepareFormJsonError($this->form);
			}
			return new JsonResponse($this->response);
		}
		return $this->responseArray;
	}
	
	
	/**
	 * @author Employee Id: 4471
	 * Description : get shipping tax listing 
	 * @param 1 : No paramater
	 * @throws Exception: Null
	 *
	 * @Route("/admin/{_locale}/tax-mapping-list",
	 * name="office_brain_taxbundle_taxadmin_taxmapping_list",
	 * options={"expose"=true}
	 * )
	 * @Template("OfficeBrainTaxBundle:TaxAdmin:adminTaxMappingList.html.twig")
	 */
	public function getTaxMappingListAction()
	{
		$this->initAction();
		$mapProductSku = $this->request->get('mapProductSku');
		$searchArray['productId'] = '';
		$searchArray['taxId'] = $this->request->get('mapTitle');
		$searchArray['countryId'] = $this->request->get('mapCountry');
		$searchArray['stateId'] = $this->request->get('mapState');
		$searchArray['categoryId'] = $this->request->get('mapCategory');
		if($mapProductSku!='')
		{
			$this->request->query->set('search_type','exact');
			$this->request->query->set('sku', $mapProductSku);
			$this->responseSearchArray = $this->searchManager->searchService();
			if(isset($this->responseSearchArray['search_result_array']['data'][0]['product_id']))
				$searchArray['productId'] = $this->responseSearchArray['search_result_array']['data'][0]['product_id'];
			else 
				return new JsonResponse(array('status' => 'error', 'status_message' => $this->get('translator')->trans('admin.tax_mapping.search.product_message')));
		}
		$this->responseArray['records_per_page'] = $this->recordsPerPage;
		$this->responseArray['page'] = $this->page;
		$this->responseArray['data'] = $this->taxManager->getTaxMappingList($this->page,$this->recordsPerPage,$searchArray);
		$this->responseArray['taxTitle']=$this->taxManager->getActiveTaxMasterList();
		$this->responseArray['country'] = $this->coreManager->getCountryData();
		$this->apiManager= $this->get("officebrain_category_api_manager");
// 		$categories = $this->apiManager->getList((array)$this->culture);
// 		$this->responseArray['product_categories']= $categories[$this->culture];
		$product_categories = $this->searchManager->advanceSearchService();
		$this->responseArray['product_categories'] = $product_categories['categoryNameId'];
		$this->responseArray['countryLanguageId']= $this->culture;
		$this->responseArray['configuration']= $this->configurationRule['option']['shipping_tax']['option'];
		return $this->responseArray;
	}
	
	/**
	 *
	 * @author Employee Id: 4471
	 * Description : Change Status tax mapping.
	 * @param 1 : tex Id
	 * @return type : JsonResponse object
	 * @throws Exception: No exception
	 * @Route("/admin/{_locale}/tax-mapping-change-status", name="office_brain_taxbundle_taxadmin_taxmapping_status_change",
	 * options={"expose"=true}
	 * )
	 * @Template()
	 */
	public function changeStatusTaxMappingAction()
	{
		$this->initAction();
		$id = $this->request->get('id');
		if ($id) {
			$status = $this->taxManager->changeTaxMappingStatus($id);
			if ($status) {
				return new JsonResponse(array('status' => 'success', 'status_message' => $this->get('translator')->trans('admin.tax_master.message.status_success')));
			}
		}
		return new JsonResponse(array('status' => 'fail', 'status_message' => $this->get('translator')->trans('admin.tax_master.message.status_error')));
	}
	
	/**
	 *
	 * @author Employee Id: 4471
	 * Description : delete tax mapping.
	 * @param 1 : tex Id
	 * @return type : JsonResponse object
	 * @throws Exception: No exception
	 * @Route("/admin/{_locale}/tax-mapping-delete", name="office_brain_taxbundle_taxadmin_taxmapping_delete",
	 * options={"expose"=true}
	 * )
	 * @Template()
	 */
	public function deleteTaxMappingAction()
	{
		$this->initAction();
		$taxmappingId = $this->request->get('id');
		$result= $this->taxManager->deleteTaxMapping($taxmappingId);
		if($result['status']=='success')
		{
			return new JsonResponse(array('status' => 'success', 'page_url' => $this->generateUrl('office_brain_taxbundle_taxadmin_taxmapping_list')));
		}
		else
		{
			return new JsonResponse(array('status' => 'error', 'error_message' => $this->get('translator')->trans('admin.tax_master.message.delete_error')));
		}
	}
	
	
	/**
	 * @author Employee Id: 4471
	 * Description : add tax master
	 * @Route("admin/{_locale}/tax-mapping-add", name="office_brain_taxbundle_taxadmin_taxmapping_add", options={"expose"=true})
	 * @method({"GET,POST"})
	 * @Template("OfficeBrainTaxBundle:TaxAdmin:adminTaxMappingAdd.html.twig")
	 */
	public function addTaxMappingAction()
	{
		$this->initAction();
		$this->responseArray['taxTitle']=$this->taxManager->getActiveTaxMasterList();
		$this->responseArray['country'] = $this->coreManager->getCountryData();
		$this->apiManager= $this->get("officebrain_category_api_manager");
		$product_categories = $this->searchManager->advanceSearchService();
		$this->responseArray['product_categories'] = $product_categories['categoryNameId'];
		$this->responseArray['countryLanguageId']= $this->culture;
		$this->responseArray['configuration']= $this->configurationRule['option']['shipping_tax']['option'];
		if ($this->request->getMethod() == 'POST')
		{
			$data= $this->request->get('data');
			$status = $this->taxManager->addTaxMapping($data);
			if ($status =='success') {
				$this->response ['status'] = 'success';
				$this->response['success_message']  = $this->get('translator')->trans('admin.tax_master.message.add_success_msg');
				$this->response['close_modal']  = true;
			} else {
				$this->response ['status'] = 'error';
				$this->response['error_message']  = $this->get('translator')->trans('admin.tax_master.message.add_error_msg');
				$this->response['close_modal']  = true;
			}
			return new JsonResponse($this->response);
		}
		return $this->responseArray;
	}
	
	/**
	 * @author Employee Id: 4471
	 * Description : add tax master add new row
	 * @Route("admin/{_locale}/tax-mapping-add-row", name="office_brain_taxbundle_taxadmin_taxmapping_add_row", options={"expose"=true})
	 * @method({"GET,POST"})
	 * @Template("OfficeBrainTaxBundle:TaxAdmin:adminTaxMappingAddRow.html.twig")
	 */
	public function addRowTaxMappingAction()
	{
		$this->initAction();
		$this->responseArray['taxTitle']=$this->taxManager->getActiveTaxMasterList();
		$this->responseArray['country'] = $this->coreManager->getCountryData();
		$this->apiManager= $this->get("officebrain_category_api_manager");
		$categories = $this->apiManager->getList((array)$this->culture);
		$this->responseArray['product_categories']= $categories[$this->culture];
		$this->responseArray['countryLanguageId']= $this->culture;
		$this->responseArray['count'] = $this->request->get('count');
		return $this->responseArray;
	}
	
	/**
	 * @author Employee Id: 4471
	 * Description : check sku is exsists or not
	 * @Route("admin/{_locale}/tax-mapping-check-sku", name="office_brain_taxbundle_taxadmin_taxmapping_check_sku", options={"expose"=true})
	 * @method({"GET,POST"})
	 * @Template()
	 */
	
	public function checkProductSkuAction()
	{
		$this->initAction();
		$sku = $this->request->get('sku');
		$categories = $this->request->get('categories');
		//print_r($categories);die;
		if($sku != '')
		{
			$this->request->query->set('search_type','exact');
			$this->request->query->set('sku', $sku);
			$this->responseSearchArray = $this->searchManager->searchService();
			if(isset($this->responseSearchArray['search_result_array']['data']) && count($this->responseSearchArray['search_result_array']['data'])>0)
			{
				$catresult = $this->responseSearchArray['search_result_array']['data'][0]['category_name_id_ss'];
				$skucat=array();
				foreach($catresult as $cat){
					$value = explode('|',$cat);
					$skucat[] =$value[0]; 
				}
				if(count($categories) > 0){
					$comparecount = count(array_intersect($categories, $skucat));
				}else{
					$comparecount = 1;
				}
				
				if($comparecount > 0){
					if(isset($this->responseSearchArray['search_result_array']['data'][0]['product_id']))
					{
						$productId = $this->responseSearchArray['search_result_array']['data'][0]['product_id'];
						return new JsonResponse(array('status' => 'success', 'productId' => $productId));
					}
					else{
						return new JsonResponse(array('status' => 'error', 'status_message' => $this->get('translator')->trans('admin.tax_mapping.search.product_message')));
					}
				}else{
					return new JsonResponse(array('status' => 'error', 'status_message' => $this->get('translator')->trans('admin.tax_mapping.search.product_message')));
				}
			}
			else
			{
				return new JsonResponse(array('status' => 'error', 'status_message' => $this->get('translator')->trans('admin.tax_mapping.search.product_message')));
			}
		}
	}
	
	
	/**
	 * @author Employee Id: 4471
	 * Description : edit tax mapping
	 * @Route("admin/{_locale}/tax-mapping-edit", name="office_brain_taxbundle_taxadmin_taxmapping_edit", options={"expose"=true})
	 * @method({"GET,POST"})
	 * @Template("OfficeBrainTaxBundle:TaxAdmin:adminTaxMappingEdit.html.twig")
	 */
	public function editTaxMappingAction()
	{
		$this->initAction();
		$taxId= $this->request->get('id');
		$this->taxMappingdetail = $this->taxManager->getTaxMappingById($taxId);
		$this->confi = $this->configurationRule['option']['shipping_tax']['option'];
		$this->taxTitle=$this->taxManager->getActiveTaxMasterList();
		$this->country = $this->coreManager->getCountryData();
		$this->state = NULL;
		$this->apiManager= $this->get("officebrain_category_api_manager");
		$categories = $this->apiManager->getList((array)$this->culture);
		$this->productCategories = $categories[$this->culture];
		$this->countryLanguageId = $this->culture;
		//$this->categoryList= $this->taxManager->getCategoryList($this->productCategories,$this->countryLanguageId);
		$product_categories = $this->searchManager->advanceSearchService();
		$categoryLists = $product_categories['categoryNameId'];
		$categoryList =array();
		foreach($categoryLists as $catList){
			$categoryList[$catList['id']] = $catList['name'];
		}
		
		$this->categoryList= $categoryList;
		if ($this->request->getMethod() == 'POST')
		{
			$action = 'update';
			$this->taxMappingdetail = array();
			$postdata = $_POST;
			$this->taxMappingdetail = $postdata['edit_tax_mapping'];
			
			if($postdata['sku']!='')
				$this->taxMappingdetail['sku'] = json_decode($postdata['sku'], true);
			else
				$this->taxMappingdetail['sku'] = $postdata['sku'];
			
			if($postdata['selectProductId']!='')
				$this->taxMappingdetail['productId'] = json_decode($postdata['selectProductId'], true);
			else
				$this->taxMappingdetail['productId'] = $postdata['selectProductId'];
					
			$this->taxMappingdetail['catName'] = $postdata['catName'];
			if($this->taxMappingdetail['countryId']!=NULL)
			{
				$this->state = $this->coreManager->getStateData($this->taxMappingdetail['countryId']);
			}
			$this->form = $this->createForm(new EditTaxMappingType($this->taxTitle,$this->country,$this->state,$this->categoryList,$this->confi,$taxId,$this->taxMappingdetail,$action));
			$this->form->handleRequest($this->request);
			if ($this->form->isValid()) {
				$status = $this->taxManager->EditTaxMapping($this->taxMappingdetail);
					
				if ($status =='success') {
					$this->response ['status'] = 'success';
					$this->response['success_message']  = $this->get('translator')->trans('admin.tax_master.message.update_success_msg');
					$this->response['close_modal']  = true;
				} else {
					$this->response ['status'] = 'error';
					$this->response['error_message']  = $this->get('translator')->trans('admin.tax_master.message.add_error_msg');
					$this->response['close_modal']  = true;
				}
				return new JsonResponse($this->response);
			}
			else
			{
				$this->response = $this->commonLibraryManager->prepareFormJsonError($this->form);
			}
			return new JsonResponse($this->response); 
		}else{
			if($this->taxMappingdetail->getCountryId() != NULL)
			{
				$this->state = $this->coreManager->getStateData($this->taxMappingdetail->getCountryId());
			}
			
			$action ='edit';
			$this->form = $this->createForm(new EditTaxMappingType($this->taxTitle,$this->country,$this->state,$this->categoryList,$this->confi,$taxId,$this->taxMappingdetail,$action ),$this->taxMappingdetail);
			$this->responseArray['form'] = $this->form->createView();
			$this->responseArray['confi'] = $this->confi;
			$this->responseArray['productSku'] = $this->taxMappingdetail->getProductSku();
			$this->responseArray['productId'] = $this->taxMappingdetail->getProductId();
		}
		
		return $this->responseArray;
	}
	
}
