<?php

namespace OfficeBrain\Bundle\RequestQuoteBundle\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\CoreBundle\CustomeHandler as FormErrorManager;
use OfficeBrain\Bundle\RequestQuoteBundle\Form\RequestQuoteCommentType;
use OfficeBrain\Bundle\RequestQuoteBundle\Entity\RequestQuoteComment;
use OfficeBrain\Bundle\UserBundle\Form\ContactBookType;
use OfficeBrain\Bundle\UserBundle\Entity\ContactBook;

/**
 *
 *
 * @Route("", defaults={"rule_service"="rule_charges"})
 */
class RequestQuoteAdminController 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()
	{
		$this->user = null;
		$this->form = null;
		$this->request = null;
		$this->formData = null;
		$this->commonLibraryManager = null;
		$this->responseArray = array();
		$this->locale = null;
		$this->productId = null;
		$this->productSlug = null;
		$this->userId = null;
		$this->user = null;
        $this->queueApiManager = null;
	}
	
	/**
	 *
	 * @author Employee Id: 4203
	 *
	 * 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->productId);
		unset($this->productSlug);
		unset($this->locale);
		unset($this->productId);
		unset($this->productSlug);
		unset($this->locale);
		unset($this->userId);
		unset($this->user);
        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->userId = $this->projectSetting['user_id'];
		$this->user = $this->projectUserSetting['user_data'];
		$this->productId = $this->request->get('product_id',null);
		$this->productSlug = $this->request->get('product_slug',null);
		$this->requestQuoteMasterId = $this->request->get('requestQuoteMasterId',null);
		$this->cultureId = $this->projectSetting['culture_id'];
		$this->locale = $this->projectSetting['culture_code'];
		$this->responseArray = array();
		$this->configurationRule = $this->projectSetting['configuration_rule']['transaction']['request_quote'];
		$this->requestQuoteManager = $this->get('office_brain_request_quote_manager');
		$this->commonLibraryManager = $this->get('office_brain_common_library');
		$this->userContactBookManager = $this->get('office_brain_user_contact_book_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->erpIntegration = $this->request->get('project_setting')['configuration_rule']['erp_integration'];
        if ($this->has('office_brain_queue_api_manager')) 
         {
            $this->request->attributes->set('object', 'RequestQuote');
            $this->queueApiManager = $this->get('office_brain_queue_api_manager');
        }
	}
	
     /**
     * Description : Use to submit guest user info form.
     * @param 1 : No paramater
     * @return type : Form view and data.
     * @throws Exception: Null
     *
     * @Route("/admin/{_locale}/list-request-quote",
     * name="office_brain_requestquotebundle_requestquoteadmin_listrequestquote",
     * options={"expose"=true}
     * )
     * @Template("OfficeBrainRequestQuoteBundle:RequestQuoteAdmin:listRequestQuote.html.twig")
     * @Method({"GET"})
     */
    public function listRequestQuoteAction()
    {
    	$this->initAction();
    	$this->responseArray['records_per_page'] = $this->recordsPerPage;
    	$this->responseArray['page'] = $this->page;
		$this->responseArray['data'] = $this->requestQuoteManager->getRequestQuoteAdminList($this->page,$this->recordsPerPage);
		$this->responseArray['total'] = $this->requestQuoteManager->getTotalCountUserWiseAdmin();
		return $this->responseArray;
    }
    
    
    /**
     * @author Employee Id: 4471
     * Description : Use to submit Commemt Request quote form.
     * @param 1 : No paramater
     * @return type : Form view and data.
     * @throws Exception: Null
     *
     * @Route("/{_locale}/admin-list-comment-request-quote/{request_quote_id}",
     * name="office_brain_requestquotebundle_requestquote_adminlistcommentrequestquote",
     * options={"expose"=true}
     * )
     * @Template("OfficeBrainRequestQuoteBundle:RequestQuoteAdmin:adminListCommentRequestQuote.html.twig")
     * @Method({"GET"})
     */
    public function adminListCommentRequestQuoteAction()
    {
    	$this->initAction();
    	$this->responseArray['data']=$this->requestQuoteManager->getCommentRequestQuoteList();
    	return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4217
     * 
     * Description : Use to submit Commemt Request Quote 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_requestquotebundle_requestquote_admincustomerinfo",
     * options={"expose"=true}
     * )
     * @Template()
     * @Method({"GET"})
     */
    public function adminCustomerInfoAction()
    {
    	$this->initAction();
    	$this->responseArray['userDetail'] = $this->requestQuoteManager->getUserDetail($this->request->get('user_id'),$this->request->get('user_type'));
    	return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4217
     * Description : Use to submit Commemt Request Quote 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_requestinfobundle_requestquotebundle_adminguestcustomerinfo",
     * options={"expose"=true}
     * )
     * @Template()
     * @Method({"GET"})
     */
    public function adminGuestCustomerInfoAction()
    {
    	$this->initAction();
    	$this->responseArray['userDetail'] = $this->requestQuoteManager->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}/detail-request-quote/{request_quote_id}",
     * name="office_brain_requestquotebundle_requestquoteadmin_admindetailrequestquote",
     * options={"expose"=true}
     * )
     * @Template()
     * @Method({"GET"})
     */
    public function adminDetailRequestQuoteAction()
    {
    	$this->initAction();
    	$this->responseArray['data'] = $this->requestQuoteManager->getRequestQuoteDetailById();
    	return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4217
     * Description : Use to render Commemt Request Quote form.
     * @param 1 : No paramater
     * @return type : Form view.
     * @throws Exception: Null
     *
     * @Route("/admin/{_locale}/admin-add-comment-request-quote/{request_id}",
     * name="office_brain_requestquotebundle_requestquote_adminaddcommentrequestquote",
     * options={"expose"=true}
     * )
     * @Template()
     * @Method({"GET"})
     */
    public function adminAddCommentRequestQuoteAction()
    {
    	$this->initAction();
    	$this->requestQuoteMasterId = $this->request->get('request_id');
    	$this->form = $this->createForm(new RequestQuoteCommentType(), new RequestQuoteComment() );
    	$this->responseArray['form']=$this->form->createView ();
    	$this->responseArray['request_id']=$this->requestQuoteMasterId;
    	return $this->responseArray;
    	 
    }
    
    
    /**
     * @author Employee Id: 4217
     * Description : Use to submit Commemt Request quote form.
     * @param 1 : No paramater
     * @return type : Form view and data.
     * @throws Exception: Null
     *
     * @Route("/admin/{_locale}/add-comment-request-quote",
     * name="office_brain_requestquotebundle_requestquote_adminprocesscommnentrequestquotesubmit",
     * options={"expose"=true}
     * )
     * @Template("OfficeBrainRequestQuoteBundle:RequestQuoteAdmin:adminAddCommentRequestQuote.html.twig")
     * @Method({"POST"})
     */
    public function adminAddCommentRequestQuoteSubmitAction()
    {
    	$this->initAction();
    	$data=array();
    	$this->form=$this->createForm(new RequestQuoteCommentType(), new RequestQuoteComment() );
    	$this->form->handleRequest($this->request);
    	if ('POST' === $this->request->getMethod()){
    		$requestId=$this->form->getData()->requestQuoteId;
    		if ($this->form->isValid()){
    			$result=$this->requestQuoteManager->setRequestQuoteComment($this->form->getData());
    			switch ($result['status']) {
    				case 'COMMENT_ADDED_SUCESSFULLY':
    					if ($this->request->isXmlHttpRequest ()) {
    						$response = new Response();
    						$url=$this->generateUrl('office_brain_requestquotebundle_requestquote_adminlistcommentrequestquote',array('request_quote_id'=>$requestId));
    						$output = array('status'=>'success','success_message'=>$this->get('translator')->trans('request_info.comment_added_successfully'),'url'=>$url);
    						$response->headers->set('Content-Type', 'application/json');
    						$response->setContent(json_encode($output));
    						return $response;
    					}
    					break;
    			}
    		}
    		else if ($this->request->isXmlHttpRequest ()) {
    			return new JsonResponse ( $this->commonLibraryManager->prepareFormJsonError($this->form));
    		}
    	}
    	return array (
    			'form' => $this->form->createView (),
    			'request_id'=>$requestId
    	);
    }
    

    /**
     *
     * @author Employee Id: 4217
     * Desciption: Get Detail Admin Customer. 
     * @param NULL
     * @return Html Response
     * @throws NULL
     *
     * @Route("/{_locale}/customer-detail/{user_id}/{user_type}",
     *  name="office_brain_requestquotebundle_requestquoteadmin_adminCustomerDetailInfo"
     * )
     *
     * @Method({"GET"})
     *
     * @Template()
     *
     */
    public function adminCustomerDetailInfoAction()
    {
    	$this->initAction();
    	$userType= $this->request->get('user_type');
    	$this->responseArray['user_detail'] = $this->requestQuoteManager->getUserDetail($this->request->get('user_id'), $this->request->get('user_type'));
    	$this->responseArray['user_type']= $userType;
    	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-request-quote/{request_quote_id}",
     * name="office_brain_requestquotebundle_requestquoteadmin_deleterequestquote",
     * options={"expose"=true}
     * )
     * @Template()
     * @Method({"GET"})
     */
    public function adminDeleteRequestQuoteAction()
    {
    	$this->initAction();
    	$requestQuoteDetail=$this->requestQuoteManager->deleteRequestQuoteDetailById();
    	switch ($requestQuoteDetail['status']) {
    		case 'ERROR_NOT_FOUND':
    			$this->responseArray['error_message'] = $this->get('translator')->trans('request_quote.no_record');
    			break;
    		case 'SUCCESS':
                if ($this->erpIntegration && $this->erpIntegration['orderManagement'] == 1 && !empty($this->queueApiManager)) {
                    $this->queueApiManager->mapQueue("remove", array('id' =>$this->request->get('request_quote_id'), 'deleted_at' => $requestQuoteDetail['data']->getDeletedAt()->format('Y-m-d H:i:s'), 'culture' => $requestQuoteDetail['data']->getCulture()));
                }
    			$this->responseArray['status'] = 'success';
				$this->responseArray['inquiry_list'] = 'inquiry';
    			$this->responseArray['success_message'] = $this->get('translator')->trans('request_quote.remove_success_message');
    			break;
    	}
    	return new JsonResponse($this->responseArray);
    }
	
    /**
     *
     * @author Employee Id: 4217
     *
     * Desciption: Use to get Product Detail By id
     *
     * @param product_id
     *
     * @return Html Response
     *
     * @throws NULL
     *
     * @Route("/{_locale}/product-detail-byid/{product_id}",
     *  name="office_brain_requestquotebundle_requestquoteadmin_adminProductdetailbyid"
     * )
     *
     * @Method({"GET"})
     *
     * @Template()
     *
     */
    public function adminProductDetailByIdAction()
    {
    	$this->initAction();
    	$productId = $this->request->get('product_id');
    	$this->responseArray['product_detail'] = $this->requestQuoteManager->getProductDetailById();
    	return new JsonResponse($this->responseArray['product_detail']);
    	
    }
    
    /**
     * @author Employee Id: 4248
     * Description : Use to edit the existing shipping address
     *
     * @Route("/admin/{_locale}/request-quote-edit-address/{contactBookId}",
     * name="office_brain_requestquotebundle_editadminrequestquoteaddress",
     * )
     * @Method({"GET"})
     * @Template()
     */
    public function editAdminContactBookAction()
    {
    	$this->initAction();
    	$contactBookId = $this->request->get('contactBookId');
    	$contactBookArray = $this->userContactBookManager->getSingleContactBook($contactBookId);
    	$this->form = $this->createForm(new ContactBookType($this->container), $contactBookArray);
    	$this->form->handleRequest($this->request);
    	return array('contactBookForm'=> $this->form->createView(),'contactBookId'=>$contactBookId);
    	 
    }
}
