<?php

namespace OfficeBrain\Bundle\SeoBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
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\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Translation\Translator;
use OfficeBrain\Bundle\SeoBundle\Form\SeoDetailType;
use OfficeBrain\Bundle\SeoBundle\Entity\SeoDetail;

use OfficeBrain\Bundle\SeoBundle\Form\SeoCategoryType;
use OfficeBrain\Bundle\SeoBundle\Entity\SeoCategory;
/**
 * 
 * @Route("/admin/{_locale}")
 */

class SeoAdminController extends Controller
{


	 public function initAction()
    {
       $this->request = $this->getRequest();
       $data=array();
       $this->projectSetting = $this->request->get('project_setting');
       $this->userId = $this->projectSetting['user_id'];
	   $this->instanceType = $this->projectSetting['instance_type'];
	   $this->instance_id= $this->projectSetting['instance_id'];
	   $this->configurationRule = $this->projectSetting['configuration_rule']['transaction']['manage_order'];
	   $this->page = $this->request->get('page', '1');
 	    $this->recordsPerPage = $this->request->get('records_per_page', $this->configurationRule['list_admin']['option']['no_of_product']);
		$this->seoManager = $this->get('office_brain_seo_manager');
		$this->searchManager = $this->get('office_brain_search_manager');
        $this->data=$data;
    } 
    
    /**
     * Creates a new Seo entity.
     *
     * @Route("/seo-create", name="officebrain_admin_create")
     * @Template("OfficeBrainSeoBundle:SeoAdmin:seocreate.html.twig")
     */
    public function createAction(Request $request)
    {
    	$this->initAction();
        $em = $this->getDoctrine()->getManager();
        $entity = new SeoDetail();
        $entity->setIsPrefix(0);
        $positionValue='';
        $form = $this->createForm(new SeoDetailType($this->data,$positionValue), $entity, array(
            'action' => $this->generateUrl('officebrain_admin_create'),
            'method' => 'POST',
        ));
        
        $form->handleRequest($request);
        
        if ($form->isValid()) { 
            $em->persist($entity);
            $sku=$entity->getProductSku();
            $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'][0]['product_id']))
			{ 
				$productId = $this->responseSearchArray['search_result_array']['data'][0]['product_id'];
				$CheckDublicate = $this->seoManager->checkDublicateSku($sku);
				if($CheckDublicate!=''){
					$this->get('session')->getFlashBag()->set('error', $this->get('translator')->trans('seo.sku_already_exist'));
          	        return $this->redirect($this->generateUrl('officebrain_admin_create'));

				}
		
	            $entity->setProductId($productId);
	            $entity->setUserId($this->userId);
	            $entity->setInstanceType($this->instanceType);
	            $entity->setInstanceId($this->instance_id);
	            $em->flush();
          }else{ 
          	$this->get('session')->getFlashBag()->set('error', $this->get('translator')->trans('seo.invalid_sku'));
          	return $this->redirect($this->generateUrl('officebrain_admin_create'));
          } 
            return $this->redirect($this->generateUrl('officebrain_admin_seolist'));
        }
        
        return array(
            'entity' => $entity,
            'form'   => $form->createView(),

        );
    }

        /**
     * Edits an existing Seo entity.
     *
     * @Route("/seo-edit/{id}", name="officebrain_admin_update")
     * @Template("OfficeBrainSeoBundle:SeoAdmin:seoedit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
    	$this->initAction();
        $em = $this->getDoctrine()->getManager();
        $seoid =   $id;
            
        $entity = $em->getRepository('OfficeBrainSeoBundle:SeoDetail')->find($id);
        
        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Seo entity.');
        }
        $positionValue=$entity->getIsPrefix();       
        $editForm = $this->createForm(new SeoDetailType($this->data,$positionValue), $entity);
        
        $editForm->handleRequest($request);
        
        if ($editForm->isValid()) {
        	$sku=$entity->getProductSku();
            $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'][0]['product_id']))
			{
				$productId = $this->responseSearchArray['search_result_array']['data'][0]['product_id'];
	        	$entity->setProductId($productId);
	            $entity->setUserId($this->userId);
	            $entity->setInstanceType($this->instanceType);
	            $entity->setInstanceId($this->instance_id);
	                
	            $em->persist($entity);
	            $em->flush();
	        }else{
	        	$this->get('session')->getFlashBag()->set('error', $this->get('translator')->trans('seo.invalid_sku'));
          	    return $this->redirect($this->generateUrl('officebrain_admin_update',array('id'=>$seoid)));

	        }    
            

            return $this->redirect($this->generateUrl('officebrain_admin_seolist'));
        }

        return array(
            'data'        => $entity,
            'form'        => $editForm->createView(),
            
        );
    }
    /**
	 * @author Employee Id: 5083
	 * OB eCommerce Product - preapre  search parameter
	 */
	private function prepareSearchParameterArray()
	{   $this->initAction();
		$this->keywords = $this->request->get('keywords', null);
		$this->searchKeyWordsArray=trim($this->keywords);
		 
	}
	
	/**
     * Creates a new Seo entity.
     *
     * @Route("/seo-list", name="officebrain_admin_seolist",options={"expose"=true})
     * @Template("OfficeBrainSeoBundle:SeoAdmin:adminSeoList.html.twig")
     * @Method({"GET","POST"})
     */
    public function seolistAction()
    { 
    	$this->initAction();
    	$this->prepareSearchParameterArray();
    	$this->responseArray['records_per_page'] = $this->recordsPerPage;
    	$this->responseArray['page'] = $this->page;
    	$this->responseArray['data'] = $this->seoManager->getAdminAllSku($this->page,$this->recordsPerPage,$this->searchKeyWordsArray);
    	return $this->responseArray;
    }


    /**
     * Creates a Category Seo entity.
     *
     * @Route("/category-content-list", name="officebrain_admin_categoryContentlist",options={"expose"=true})
     * @Template("OfficeBrainSeoBundle:SeoAdmin:adminSeoCategoryList.html.twig")
     * @Method({"GET","POST"})
     */
    public function categoryContentListAction()
    { 
        $this->initAction();
        //$this->prepareSearchParameterArray();
        $search['keyword'] = $this->request->get('keywords', '');
        $search['option'] = $this->request->get('option', '');
        $this->responseArray['records_per_page'] = $this->recordsPerPage;
        $this->responseArray['page'] = $this->page;
        $this->responseArray['data'] = $this->seoManager->getAdminCategoryContent($this->page,$this->recordsPerPage,$search);
        return $this->responseArray;
    }

    /**
     * Deletes a Seo entity.
     *
     * @Route("/seo-delete/{id}", name="officebrain_admin_seodelete")
     */
    public function seodeleteAction($id)
    {	$this->initAction();
        $isdeleted=$this->seoManager->deleteSeoDetailById($id);

        
	    return $this->redirect($this->generateUrl('officebrain_admin_seolist'));
    }
    


    /**
     * Edits an existing Seo entity.
     *
     * @Route("/seo-category-edit/{id}", name="officebrain_admin_updateCategory")
     * @Template("OfficeBrainSeoBundle:SeoAdmin:seoCategoryEdit.html.twig")
     */
    public function updateCategoryAction(Request $request)
    {
        $this->initAction();
        $em = $this->getDoctrine()->getManager();
        $id =   $this->request->get('id');
            
        $entity = $em->getRepository('OfficeBrainSeoBundle:SeoCategory')->find($id);
        
        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Seo Category entity.');
        } 
        $editForm = $this->createForm(new SeoCategoryType(), $entity);
        
        $editForm->handleRequest($request);
        
        if ($editForm->isValid()) {
                $content = $editForm->getData()->getCategoryContent();
                $entity->setCategoryContent($content);    
                $em->persist($entity);
                $em->flush();
            return $this->redirect($this->generateUrl('officebrain_admin_categoryContentlist'));
        }

        return array(
            'data'        => $entity,
            'form'        => $editForm->createView(),
            
        );
    }

}
