<?php

namespace OfficeBrain\Bundle\OrderBundle\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\HttpFoundation\JsonResponse;
use OfficeBrain\Bundle\QuoteBundle\Form\AddCustomerType;
use OfficeBrain\Bundle\QuoteBundle\Form\AddCustomerContactType;
use Symfony\Component\DependencyInjection\ContainerInterface;
use PHPExcel;
use PHPExcel_IOFactory;
use Symfony\Component\Translation\Translator;


/**
 *
 *
 * @Route("", defaults={"rule_service"="rule_charges"})
 */
class OrderAdminController extends Controller
{
	
	protected $user;
	protected $form;
	protected $request;
	protected $formData;
	protected $responseArray;
	
	/**
	 * @author Employee Id: 4203
	 * Desciption: Define member variables with thier default value
	 * @param NULL
	 * @return NULL
	 * @throws NULL
	 */
	public function __construct(ContainerInterface $container=null)
	{
		$this->user = null;
		$this->form = null;
		$this->request = null;
		$this->formData = null;
		$this->commonLibraryManager = null;
		$this->responseArray = array();
		$this->locale = null;
		$this->searchParameterArray = array();
		$this->searchKeyWordsArray = array();
		$this->sortingParameterArray = array();
		$this->validationManager =null;
		$this->erpConfigrationField = null;
		$this->queueApiManager = null;
        $this->translator = null;	
	}
	
	/**
	 *
	 * @author Employee Id: 4217
	 * Desciption: Unset member variables
	 * @param NULL
	 * @return NULL
	 * @throws NULL
	 *
	 */
	public function __destruct()
	{
		unset($this->user);
		unset($this->form);
		unset($this->request);
		unset($this->formData);
		unset($this->commonLibraryManager);
		unset($this->locale);
		unset($this->searchParameterArray);
		unset($this->searchKeyWordsArray);
		unset($this->sortingParameterArray);
		unset($this->validationManager);
		unset($this->erpConfigrationField);
		unset($this->queueApiManager);
	}

	
	public function initAction()
	{
		$this->request = $this->getRequest();
		$this->projectSetting = $this->request->get('project_setting');
		$this->projectUserSetting = $this->request->get('project_user_setting');
		$this->erpConfigrationField = $this->projectSetting['configuration_rule']['erp_integration'];
		$this->userId = $this->projectSetting['user_id'];
		$this->user = $this->projectUserSetting['user_data'];
		$this->instanceType = $this->projectSetting['instance_type'];
		$this->cultureId = $this->projectSetting['culture_id'];
		$this->locale = $this->projectSetting['culture_code'];
		$this->responseArray = array();
		$this->configurationRule = $this->projectSetting['configuration_rule']['transaction']['manage_order'];
		$this->userConfigrations = $this->projectSetting['configuration_rule']['user']['user'];
		$this->parameter = $this->userConfigrations['user_photo_upload_parameter'];
		$this->requestStatus = $this->request->get('status', 'draft');
		$this->quoteManager = $this->get('office_brain_quote_manager');
		$this->commonLibraryManager = $this->get('office_brain_common_library');
		$this->coreManager = $this->get('office_brain_core_manager');
		$this->page = $this->request->get('page', '1');
		$this->recordsPerPage = $this->request->get('records_per_page', $this->configurationRule['list_admin']['option']['no_of_product']);
		$this->validationManager = $this->get('office_brain_validation_manager');
		$this->orderManager = $this->get('office_brain_order_manager');
		$this->fedexShippingEstimatorManager = $this->get('office_brain_shipping_estimator_manager_fedex');
		$this->upsShippingEstimatorManager = $this->get('office_brain_shipping_estimator_manager_ups');
		if ($this->has('office_brain_queue_api_manager')) {
			$this->request->attributes->set('object', 'Quote');
			$this->queueApiManager = $this->get('office_brain_queue_api_manager');
		}
	}
	
	/**
	 * @author Employee Id: 4217
	 * OB eCommerce Product - preapre  search parameter
	 */
	private function prepareSearchParameterArray()
	{
        $this->searchParameterArray['start_date'] =  $this->request->get('start_date', null);
        $this->searchParameterArray['end_date'] =  $this->request->get('end_date', null);
        $jsDateFormat = $this->coreManager->getDateJsFormat();
        if($this->searchParameterArray['start_date'] != null){
            $startDate   =   \DateTime::createFromFormat($jsDateFormat,$this->searchParameterArray['start_date']);
            $this->searchParameterArray['start_date'] = $startDate->format('Y-m-d'); 
        }
        
        if($this->searchParameterArray['end_date'] != null){
            $endDate   =   \DateTime::createFromFormat($jsDateFormat,$this->searchParameterArray['end_date']);
            $this->searchParameterArray['end_date'] = $endDate->format('Y-m-d');
        }
		$this->option = $this->request->get('option', null);
		$this->keywords = $this->request->get('keyword', null);
		$this->searchKeyWordsArray[$this->option]=trim($this->keywords);
		 
	}
	
	/**
	 * @author Employee Id: 4248
	 * Description : Use to display order list in admin
	 * @param 1 : No paramater
	 * @return type : Form view and data.
	 * @throws Exception: Null
	 *
	 * @Route("/admin/{_locale}/order-list",
	 * name="office_brain_orderbundle_orderadmin_adminorderlist",
	 * options={"expose"=true}
	 * )
	 * @Template("OfficeBrainOrderBundle:OrderAdmin:adminOrderList.html.twig")
	 *
	*/
    public function adminOrderListAction()
    {
    	$this->initAction();
    	$this->responseArray['records_per_page'] = $this->recordsPerPage;
    	$this->responseArray['page'] = $this->page;
    	$this->prepareSearchParameterArray();
        $this->responseArray['ob_export_configuration']=$this->configurationRule['export'];
    	$this->responseArray['data'] = $this->orderManager->getOrderAdminList($this->page,$this->recordsPerPage,$this->searchParameterArray,$this->searchKeyWordsArray);
    	return $this->responseArray;
    }

  /**
     * @author Employee Id: 4217
     * Description : Use to submit Commemt Request Info form.
     * @param 1 : No paramater
     * @return type : Form view and data.
     * @throws Exception: Null
     *
     * @Route("/admin/{_locale}/customer/{user_id}/{user_type}",
     * name="office_brain_orderbundle_orderadmin_admincustomerinfo",
     * options={"expose"=true}
     * )
     * @Template("OfficeBrainOrderBundle:OrderAdmin:adminCustomerInfo.html.twig")
     * @Method({"GET"})
     */
    public function adminCustomerInfoAction()
    {
    	$this->initAction();
    	$this->responseArray['userDetail'] = $this->orderManager->getUserDetail($this->request->get('user_id'),$this->request->get('user_type'));
    	return $this->responseArray;
    }

    
    /**
     * @author Employee Id: 4217
     * Description : Use to submit Commemt Request Info form.
     * @param 1 : No paramater
     * @return type : Form view and data.
     * @throws Exception: Null
     *
     * @Route("admin/{_locale}/guest-customer/{user_id}/{user_type}",
     * name="office_brain_orderbundle_orderadmin_adminguestcustomerinfo",
     * options={"expose"=true}
     * )
     * @Template("OfficeBrainOrderBundle:OrderAdmin:adminGuestCustomerInfo.html.twig")
     * @Method({"GET"})
     */
    public function adminGuestCustomerInfoAction()
    {
    	$this->initAction();
    	$this->responseArray['userDetail'] = $this->orderManager->getUserDetail($this->request->get('user_id'),$this->request->get('user_type'));
    	return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4217
     * Description : Use to submit guest user info form.
     * @param 1 : No paramater
     * @return type : Form view and data.
     * @throws Exception: Null
     *
     * @Route("/admin/{_locale}/order-details/{order_id}",
     * name="office_brain_orderbundle_orderadmin_adminorderdetails",
     * defaults={"order_id"=null},
     * options={"expose"=true}
     * )
     * @Template("OfficeBrainOrderBundle:OrderAdmin:adminOrderDetails.html.twig")
     * 
     */
    public function adminOrderDetailsAction()
    {
    	$this->initAction();
    	$itemLine = $this->request->get('info', null);
    	$this->responseArray['orderId'] = $this->request->get('order_id', null);
    	$this->responseArray['itme_line_obj'] = $this->request->get('itme_line_obj', null);
    	$this->responseArray['data'] = $this->orderManager->getOrderDetailById();
    	
    	foreach($this->responseArray['data']->getOrderItemLine() as $productIndex => $productData)
    	{
    		$productDetailArray = json_decode(base64_decode($productData->getProductDetail()),true);
    		if(isset($productDetailArray['price_type']) && $productDetailArray['price_type']== 'variations')
    		{
    			if(isset($productDetailArray['variation_pricing']))
    			{
    				$firstVariationData = array();
    				$count = 0;
    				foreach($productDetailArray['variation_pricing'] as $variationId => $variationData)
    				{
    					if($count == 0)
    					{
    						$firstVariationData = $variationData['pricing']['decorative'];
    					}
    					$count = $count + 1;
    				}
    				if(!(empty($firstVariationData)))
    				{
    					foreach($firstVariationData as $firstVariationDataIndex => $firstVariationDataData)
    					{
    						$firstVariationData[$firstVariationDataIndex]['rate'] = 'N/A';
    						$firstVariationData[$firstVariationDataIndex]['code'] = '';
    					}
    				}
    				if(!(empty($firstVariationData)))
    				{    					
    					foreach($productDetailArray['variation_pricing'] as $variationId => $variationData)
    					{
    						$variationDataBackup = $variationData['pricing']['decorative'];
    						$productDetailArray['variation_pricing'][$variationId]['pricing']['decorative'] = $firstVariationData;
	    					foreach($firstVariationData as $firstVariationDataIndex => $firstVariationDataData)
	    					{
	    						foreach($variationDataBackup as $variationDataBackupIndex => $variationDataBackupData)
	    						{
	    							if($variationDataBackupData['from_qty'] == $firstVariationDataData['from_qty'])
	    							{
	    								$productDetailArray['variation_pricing'][$variationId]['pricing']['decorative'][$firstVariationDataIndex] = $variationDataBackupData;
	    							}
	    						}
    						}
    					}
    				}
    			}
    		}    		
    		$productDetailEncoded = base64_encode(json_encode($productDetailArray));
    		//$this->responseArray['data']->getOrderItemLine()[$productIndex] = $productDetailEncoded;
    	}
    	return $this->responseArray; 
    }
    
    /**
     * @author Employee Id: 4217
     * Description : Use to submit guest user info form.
     * @param 1 : No paramater
     * @return type : Form view and data.
     * @throws Exception: Null
     *
     * @Route("/admin/{_locale}/order-product-detail/{order_id}",
     * name="office_brain_orderbundle_orderadmin_adminorderproductdetail",
     * defaults={"order_id"=null},
     * options={"expose"=true}
     * )
     * @Template("OfficeBrainOrderBundle:OrderAdmin:adminOrderProductDetail.html.twig")
     *
     */
    public function adminOrderProductDetailAction()
    {
    	$this->initAction();
    	$orderDetail = $this->orderManager->isOrderExists();
    	$this->responseArray['order'] = $orderDetail;
    	$this->responseArray['data'] = $this->orderManager->getProductList();
    	$this->responseArray['instance_type']= $this->instanceType;
    	
    	foreach($this->responseArray ['data'] as $dataIndex => $dataValues)
    	{
    		if(isset($this->responseArray ['data'][$dataIndex]['price_type']) && $this->responseArray ['data'][$dataIndex]['price_type']== 'variations')
    		{
    			if(isset($this->responseArray ['data'][$dataIndex]['variation_pricing_for_other_country']))
    			{
    				foreach($this->responseArray ['data'][$dataIndex]['variation_pricing_for_other_country'] as $countryIndex=> $countryCode)
    				{
    					$firstVariationDataWithSpecial = array();
    					$firstVariationDataWithoutSpecial= array();
    					$count = 0;
    					foreach($this->responseArray ['data'][$dataIndex]['variation_pricing_for_other_country'][$countryIndex] as $variationId => $variationData)
    					{
    						if($count == 0)
    						{
    							$firstVariationDataWithSpecial = $variationData['pricing']['decorative'];
    							$firstVariationDataWithoutSpecial= $variationData['pricing']['decorative'];
    						}
    						$count = $count + 1;
    					}
    					// Now update the rate and other things if provided
    					if(!(empty($firstVariationDataWithSpecial)))
    					{
    						foreach($firstVariationDataWithSpecial as $firstVariationRangeIndex => $firstVariationRange)
    						{
    							if(isset($firstVariationDataWithSpecial[$firstVariationRangeIndex]['rate']))
    							{
    								$firstVariationDataWithSpecial[$firstVariationRangeIndex]['rate'] = 'N/A';
    								$firstVariationDataWithoutSpecial[$firstVariationRangeIndex]['rate'] = 'N/A';
    							}
    							if(isset($firstVariationDataWithSpecial[$firstVariationRangeIndex]['rate_orig']))
    							{
    								$firstVariationDataWithSpecial[$firstVariationRangeIndex]['rate_orig'] = 'N/A';
    								$firstVariationDataWithoutSpecial[$firstVariationRangeIndex]['rate_orig'] = 'N/A';
    							}
    							if(isset($firstVariationDataWithSpecial[$firstVariationRangeIndex]['code']))
    							{
    								$firstVariationDataWithSpecial[$firstVariationRangeIndex]['code'] = '';
    								$firstVariationDataWithoutSpecial[$firstVariationRangeIndex]['code'] = '';
    							}
    							if(isset($firstVariationDataWithSpecial[$firstVariationRangeIndex]['code_orig']))
    							{
    								$firstVariationDataWithSpecial[$firstVariationRangeIndex]['code_orig'] = '';
    								$firstVariationDataWithoutSpecial[$firstVariationRangeIndex]['code_orig'] = '';
    							}
    							
    							// Remove special data from without special array
    							unset($firstVariationDataWithoutSpecial[$firstVariationRangeIndex]['rate_orig']);
    							unset($firstVariationDataWithoutSpecial[$firstVariationRangeIndex]['expired_at']);
    						}
    					}
    					if(!(empty($firstVariationDataWithSpecial)))
    					{
    						foreach($this->responseArray ['data'][$dataIndex]['variation_pricing_for_other_country'][$countryIndex] as $variationId => $variationData)
    						{
    							//echo "<br/><br/><br/><br/>Variation Changed";
    							$originalData = $variationData['pricing']['decorative'];
    							
    							if(isset($this->responseArray ['data'][$dataIndex]['variation_pricing_for_other_country'][$countryIndex][$variationId]['pricing']['decorative'][0]['rate_orig']))
    							{
    								$this->responseArray ['data'][$dataIndex]['variation_pricing_for_other_country'][$countryIndex][$variationId]['pricing']['decorative'] = $firstVariationDataWithSpecial;
    							}
    							else
    							{
    								$this->responseArray ['data'][$dataIndex]['variation_pricing_for_other_country'][$countryIndex][$variationId]['pricing']['decorative'] = $firstVariationDataWithoutSpecial;
    							}
    							foreach($firstVariationDataWithSpecial as $firstVariationRangeIndex => $firstVariationRange)
    							{
    								//echo "<br/><br/><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Variation Range Changed";
    								foreach($originalData as $originalDataRangeIndex => $originalDataRange)
    								{
    									//echo "<br/><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;originalDataRange: ".$originalDataRange['from_qty'];
    									//echo "<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;firstVariationRange: ".$firstVariationRange['from_qty'];
    									if($originalDataRange['from_qty'] == $firstVariationRange['from_qty'])
    									{
    										//echo "<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;We are updating original data";
    										$this->responseArray ['data'][$dataIndex]['variation_pricing_for_other_country'][$countryIndex][$variationId]['pricing']['decorative'][$firstVariationRangeIndex] = $originalDataRange;
    									}
    								}
    							}
    						}
    					}
    				}
    			}
    		}
    	}
    	return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4217
     * Description : Use to delete a record
     * @param 1 : No paramater
     * @return type : Form view and data.
     * @throws Exception: Null
     *
     * @Route("/admin/{_locale}/delete-order",
     * name="office_brain_orderbundle_orderadmin_adminorderdelete",
     * options={"expose"=true}
     * )
     * @Template("OfficeBrainOrderBundle:OrderAdmin:adminOrderDelete.html.twig")
     * @Method({"POST"})
     */
    public function adminOrderDeleteAction()
    {
    	$this->initAction();
    	$orderDetail=$this->orderManager->deleteOrderDetailById();
    	switch ($orderDetail['status']) {
    		case 'ERROR_NOT_FOUND':
    			$this->responseArray['error_message'] = $this->get('translator')->trans('ordeadmin.no_record');
    			break;
    		case 'SUCCESS':
    			$this->responseArray['status'] = 'success';
    			$this->responseArray['order_list'] = 'inquiry';
    			$this->responseArray['success_message'] = $this->get('translator')->trans('orderadmin.remove_success_message');
    			$this->responseArray['page_url'] = $this->generateUrl('office_brain_orderbundle_orderadmin_adminorderlist');
   				if ($this->erpConfigrationField  && $this->erpConfigrationField ['orderManagement'] == 1 && !empty($this->queueApiManager)) {
    				$this->request->attributes->set('object', 'Order');
					$this->queueApiManager->mapQueue('remove', array('id' => $this->request->get('order_id'), 'deleted_at'=> $orderDetail['data']->getDeletedAt()->format('Y-m-d H:i:s')));
    			}
    			break;
    	}
    	return new JsonResponse($this->responseArray);
    }
    
    /**
     * @author Employee Id: 4471
     * Description : display order inline status.
     * @param 1 : No paramater
     * @return type : Form view and edit data.
     * @throws Exception: Null
     *
     * @Route("/admin/{_locale}/track-order",
     * name="office_brain_orderbundle_orderadmin_adminordertrack",
     * options={"expose"=true}
     * )
     * @Template("OfficeBrainOrderBundle:OrderAdmin:adminOrderTrack.html.twig")
     * @Method({"POST"})
     */
    public function adminOrderTrackAction()
    {
    	$this->initAction();
    	$orderId=$this->request->get('orderId', null);
    	$this->responseArray['orderId'] = $orderId;
    	$data=$this->orderManager->getOrderDetailById();
    	$this->responseArray['data'] = $data;
    	$data = $this->orderManager->getOrderDetailById();
    	$this->responseArray['orderInlineProductDetail'] = $this->orderManager->getProductList();
    	return $this->responseArray;
    }
    
    
    /**
     * @author Employee Id: 4471
     * Description : display order inline tracking in detail.
     * @param 1 : No paramater
     * @return type : Form view and edit data.
     * @throws Exception: Null
     *
     * @Route("/admin/{_locale}/track-order-detail",
     * name="office_brain_orderbundle_orderadmin_adminordertrackingdetail",
     * options={"expose"=true}
     * )
     * @Template("OfficeBrainOrderBundle:OrderAdmin:adminOrderTrackingDetail.html.twig")
     * @Method({"POST"})
     */
    public function adminOrderTrackingDetailAction()
    {
    	$this->initAction();
    	$this->shippingId =$this->request->get('shippingId', null);
    	$inLineShippingDetail = $this->orderManager->getOrderLineShippingDetailAdmin($this->shippingId);
    	$this->responseArray['data']=$inLineShippingDetail;
    	$this->responseArray['shippingDetail'] = Null;
    	$this->responseArray['trackingResult'] = Null;
    	$this->status = $inLineShippingDetail->getStatusCode();
    	$this->shippingType= $inLineShippingDetail->getShippingTypeAdmin();
    	//echo $inLineShippingDetail->getTrackingId();
    	if($this->status=='shipping' || $this->status=='delivery')
    	{
    		if($this->shippingType == 'fedex')
    		{
    			$this->shippinEstiConfi = $this->projectSetting['configuration_rule']['transaction']['shipping_estimator']['option']['registered_user']['option']['fedex']['option']['fedex_shipment']['option'];
    			$shippingDetail =  $this->fedexShippingEstimatorManager->callRequest($inLineShippingDetail->getTrackingId(),$this->shippinEstiConfi,'shippingDetail');
    			if($shippingDetail->Notifications->Severity=='SUCCESS'){
	    			if($shippingDetail->TrackDetails->Notification->Severity=='SUCCESS')
	    			{
	    				$this->responseArray['trackingResult']= 'SUCCESS';
	    				$this->responseArray['shippingDetail']=$shippingDetail;
	    				if($shippingDetail->TrackDetails->Events[0]->EventType=='DL' && $this->status!='delivery')
	    				{
	    					$statuschange=$this->orderManager->changeOrderLineStatusAdmin($this->shippingId,'3','delivery','','');
	    				}
	    			}
    			}
    			//echo "<pre>";print_r($this->responseArray['shippingDetail']);exit();
    		}
    		else if ($this->shippingType == 'ups')
    		{
    			$this->shippinEstiConfi = $this->projectSetting['configuration_rule']['transaction']['shipping_estimator']['option']['registered_user']['option']['ups']['option']['ups_track']['option'];
    			$this->responseArray['trackingResult']= 'SUCCESS';
    			$this->responseArray['shippingDetail'] = $this->upsShippingEstimatorManager->callRequest($inLineShippingDetail->getTrackingId(),$this->shippinEstiConfi,'shippingDetail');
    			//echo "<pre>";print_r($this->responseArray['shippingDetail']);exit();
    		}
    	}
    	return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4471
     * Description : change status of order from admin
     * @param 1 : No paramater
     * @return type : Form view and data.
     * @throws Exception: Null
     *
     * @Route("/admin/{_locale}/change-order-line-status-and-track-order",
     * name="office_brain_orderbundle_orderadmin_changeorderlinestatusadmin",
     * options={"expose"=true}
     * )
     *
     */
    public function changeOrderLineStatusAndtTrackAdminAction()
    {
    	$this->initAction();
    	$this->orderInlineId = $this->request->get('orderInlineId', '0');
    	$this->shippingId = $this->request->get('shippingId', '0');
    	$this->status = $this->request->get('status', 'pending');
    	$this->statusId = $this->request->get('statusId','1');
    	$this->shippingType = $this->request->get('shippingType', 'fedex');
    	$this->trackingId = $this->request->get('trackingId', NULL); //1Z12345E1512345676 ups // 122816215025810 fedex
    	
    	
    	$statuschange=$this->orderManager->changeOrderLineStatusAdmin($this->shippingId,$this->statusId,$this->status,$this->shippingType,$this->trackingId);
    	return new JsonResponse($statuschange);
    }

    /**
     * @author Employee Id: 5632
     * Description : Order detail Export in xml
     * @param 1 : No paramater
     * @return type : Form view and data.
     * @throws Exception: Null
     *
     * @Route("/admin/{_locale}/order-list-export",
     * name="office_brain_orderbundle_orderadmin_adminorderlist_export",
     * options={"expose"=true}
     * )
     *
     */
    public function adminOrderListExportAction()
    {
        $this->initAction();
        
        $this->translator =  $this->get('translator');
        //echo $this->translator->trans('order_item_line', array(), 'export');;die;
        
        $this->responseArray['records_per_page'] = $this->recordsPerPage;
        $this->responseArray['page'] = $this->page;
        $this->prepareSearchParameterArray();
        $this->responseArray['data'] = $this->orderManager->getOrderAdminListExport($this->searchParameterArray,$this->searchKeyWordsArray);
    
        $new_file_name = $this->orderManager->generateXMLOfOrder($this->responseArray['data'],$this->translator);
        
        $path = $this->getParameter('place_order_xml_path');
        $fullPath = $path.''.$new_file_name;
        if(file_exists($fullPath)){
            if ($fd = fopen ($fullPath, "r")) {
                $fsize = filesize($fullPath);
        
                header("Content-type: application/octet-stream");
                header("Content-Disposition: filename=".$new_file_name);
                header("Content-length: $fsize");
                header("Cache-control: private"); //use this to open files directly
                while(!feof($fd)) {
                    $buffer = fread($fd, 2048);
                    echo $buffer;
                }
            }
            fclose ($fd);
        }
        die;
        //echo '<pre>';print_r($data);die;
         //$this->responseArray;
    }
    
    
    /**
     * @author Employee Id: 5632
     * Description : Order detail Export in xml
     * @param 1 : No paramater
     * @return type : Form view and data.
     * @throws Exception: Null
     *
     * @Route("/admin/{_locale}/order-list-export-xls",
     * name="office_brain_orderbundle_orderadmin_adminorderlist_export_xls",
     * options={"expose"=true}
     * )
     *
     */
    public function adminOrderListExportXlsAction()
    {
        $this->initAction();
        
        $this->translator =  $this->get('translator');
        //echo $this->translator->trans('order_item_line', array(), 'export');;die;
         
        $this->responseArray['records_per_page'] = $this->recordsPerPage;
        $this->responseArray['page'] = $this->page;
        $this->prepareSearchParameterArray();
        $this->responseArray['data'] = $this->orderManager->getOrderAdminListExport($this->searchParameterArray,$this->searchKeyWordsArray);
        //echo '<pre>';print_r($this->responseArray['data']);die;
        $orderData = $this->orderManager->generateObjectToArray($this->responseArray['data'],$this->translator);
        //echo '<pre>';print_r($orderData);die;
        $this->adminOrderXls($orderData);
        
        
        //$this->responseArray;
    }
    public function adminOrderXls($data)
    {   
        //echo '<pre>';print_r($data);die;
        //XLS Generate
        if(isset($data) && count($data)>0){
            
            $response = new Response();
            $objPHPExcel = new PHPExcel();
            
            // Set document properties
            $objPHPExcel->getProperties()->setCreator("Me")
            ->setLastModifiedBy("Someone")
            ->setTitle("Order Details")
            ->setSubject("Order Details");
            
            $this->setXlsData($objPHPExcel,$data[0],0);//die;
            
            $sheetNames = $objPHPExcel->getSheetNames();
            $count = 1;
            //$this->orderCounter[0] = 2;
            foreach($data as $key => $value) {
                $count ++; 
                $this->setXlsDataValue($objPHPExcel,$value,0,$sheetNames,$count);
                //echo $count.'<br/>';
            }//die;
            /* echo '<pre>';print_r($this->orderCounter);
            echo 'sasasa';
            die; */
            //echo '<pre>';print_r($sheetNames);die;
            
            /* $alpha = 'A';
            $sheet = '1';
            foreach($data[0] as $key => $value) {
                //foreach($value as $key2 => $value2) {
                //echo $key.'<br/>';
                if(is_array($value)) {
                    if(!is_numeric($key)){
                        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($alpha.'1', $key);
                        $alpha++; 
                        $objPHPExcel->createSheet();
                        $objPHPExcel->setActiveSheetIndex($sheet);
                        $objPHPExcel->getActiveSheet()->setTitle($key);
                        $sheet++;
                    }
                }else{
                    if(!is_numeric($key)){
                        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($alpha.'1', $key);
                        $alpha++;
                    }
                    $objPHPExcel->setActiveSheetIndex(0);
                    $objPHPExcel->getActiveSheet()->setTitle('Order Master');
                }
                    
            } */
            /* foreach($data as $key => $value) {
                $alpha = 'A';
                $count = $key+2;
                foreach($value as $key2 => $value2) {
                    if(!is_numeric($key2)){
                        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($alpha.''.$count, $value2);
                        $alpha++;
                    }
                }
            } */
            
            
            // Add some data
            /* $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'Hello')
            ->setCellValue('B1', 'world!')
            ->setCellValue('C1', 'Hello')
            ->setCellValue('D1', 'world!'); */
            // Set active sheet index to the first sheet
//          $objPHPExcel->setActiveSheetIndex(0);
//          $objPHPExcel->getActiveSheet()->setTitle('Order Master');
            
            // Redirect output to a client’s web browser (Excel5)
            $response->headers->set('Content-Type', 'application/vnd.ms-excel');
            $response->headers->set('Content-Disposition', 'attachment;filename="demo.xls"');
            $response->headers->set('Cache-Control', 'max-age=0');
            //$response->prepare();
            $response->sendHeaders();
            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
            $objWriter->save('php://output');
            exit();
        }
        
    }
    
    public function setXlsData($objPHPExcel,$data,$sheet){
        $alpha = 'A';
        $sheetNames = array();
        //$sheet = $sheet+1;
        //echo $sheet.'<br/>';
        //$count = $objPHPExcel->setActiveSheetIndex($sheet)->getHighestColumn() + 2;
        //echo 'Count == '.$count.'<br/>';
        foreach($data as $key => $value) {
            //echo '<pre>';print_r($value).'</pre>';echo '======================';
            //foreach($value as $key2 => $value2) {
            //echo $key.'<br/>';
            $key= substr($key, 0, 25);
            if(is_array($value)) {
                if(count($value)>0){
                    if(!is_numeric($key)){
                        //echo $sheet;die;
                        if(!in_array($key,$sheetNames)){
                            $sheet = $objPHPExcel->getSheetCount();
                            $objPHPExcel->createSheet();
                            $objPHPExcel->setActiveSheetIndex($sheet);
                            $objPHPExcel->getActiveSheet()->setTitle($key);
                        }else{
                            $asheet = array_keys($sheetNames, $key);
                            $sheet =$asheet[0]; 
                            $objPHPExcel->setActiveSheetIndex($sheet);
                        }   
                        //$objPHPExcel->setActiveSheetIndex($sheet);
                        $sheetNames = $objPHPExcel->getSheetNames();
                        //echo '<pre>';print_r($sheetNames);
                        $objPHPExcel->setActiveSheetIndex($sheet)->setCellValue($alpha.'1', $key);
                        //$count = $objPHPExcel->setActiveSheetIndex($sheet)->getHighestRow() + 1;
                        //$objPHPExcel->setActiveSheetIndex($sheet)->setCellValue($alpha.''.$count, $value);
                        $alpha++;
                        
                        $this->setXlsData($objPHPExcel,$value,$sheet);
                    }else{
                        $this->setXlsData($objPHPExcel,$value,$sheet);
                    }
                }
            }else{
                if(!is_numeric($key)){
                    $objPHPExcel->setActiveSheetIndex($sheet)->setCellValue($alpha.'1', $key);
                    //$count = $objPHPExcel->setActiveSheetIndex($sheet)->getHighestRow() + 1;
                    //$objPHPExcel->setActiveSheetIndex($sheet)->setCellValue($alpha.''.$count, $value);
                    $alpha++;
                }
                $objPHPExcel->setActiveSheetIndex(0);
                $objPHPExcel->getActiveSheet()->setTitle('Order Master');
                //$sheet++;
            }
            
        }
    }
    
    public function setXlsDataValue($objPHPExcel,$data,$sheet,$sheetNames,$counts){
        $alpha = 'A';
        $totalrec = 1;
        //$sheetNames = array();
        //$sheet = $sheet+1;
        //echo $sheet.'<br/>';
        //echo '<pre>';print_r($sheetNames);die;
        $count = $objPHPExcel->setActiveSheetIndex($sheet)->getHighestColumn() + 2;
        //echo 'Count == '.$count.'<br/>';
        foreach($data as $key => $value) {
            //echo '<pre>';print_r($value).'</pre>';echo '======================';
            //foreach($value as $key2 => $value2) {
            //echo $key.'<br/>';
            $key= substr($key, 0, 25);
            if(is_array($value)) {
                if(count($value)>0){
                    if(!is_numeric($key)){
                        //echo $sheet;die;
                        if(in_array($key,$sheetNames)){
                            $asheet = array_keys($sheetNames, $key);
                            $sheet = $asheet[0];
                            $objPHPExcel->setActiveSheetIndex($sheet);
                            $totalrec = count($value);
                            $this->orderCounter[$sheet] = $this->orderCounter[$sheet] + 1;
                        }
                        $objPHPExcel->setActiveSheetIndex($sheet)->setCellValue($alpha.''.($this->orderCounter[$sheet]+1), $value);
                        $alpha++;
                             
                        $this->setXlsDataValue($objPHPExcel,$value,$sheet,$sheetNames,$counts);
                    }else{
                        $this->orderCounter[$sheet] = $this->orderCounter[$sheet] + 1;
                        //echo 'Aheet Counter['.$sheet.'] == '.$this->orderCounter[$sheet].'<br/>';
                        $count = $objPHPExcel->setActiveSheetIndex($sheet)->getHighestRow();
                        /* echo 'Aheet Counter['.$sheet.'] == '.$count.'<br/>';
                        echo '<pre>';print_r($value); */
                        $this->setXlsDataValue($objPHPExcel,$value,$sheet,$sheetNames,($this->orderCounter[$sheet]));
                    }
                }
            }else{
                if(!is_numeric($key)){
                    //echo 'sheet == '.$sheet.'<br/>';
                    //echo $counts.'<br/>';
                    
                    $objPHPExcel->setActiveSheetIndex($sheet)->setCellValue($alpha.''.$counts, $value);
                    $alpha++;
                }
                $objPHPExcel->setActiveSheetIndex(0);
                $objPHPExcel->getActiveSheet()->setTitle('Order Master');
            }
        }
    }



    

}
