<?php

namespace OfficeBrain\Bundle\BannerBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use OfficeBrain\Bundle\BannerBundle\Entity\Banner;
use OfficeBrain\Bundle\BannerBundle\Entity\BannerLanguage;
//use OfficeBrain\Bundle\BannerBundle\Entity\BannerCountry;
use OfficeBrain\Bundle\BannerBundle\Form\BannerType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Validator\Constraints\Count;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use OfficeBrain\Bundle\CoreBundle\Cache\RedisCacheService;

/**
 *
 * @author OfficeBrain 4571 <info@officebrain.com>
 * Description: Manage Banner to perform CRUD operation
 *
 * @Route("admin/{_locale}")
 *
 */
class BannerAdminController extends Controller
{
    private $translator;
    
    private $request;
   
    private $responseArray;
    
    private $session;
    
    private $commonLibraryManager;
    
    private $instanceId;
        
    /**
     * @author Employee Id: 4571
     * Description : To set member variables default value
     *
     * @param  : null
     *
     * @return null
     *
     * @throws null
     *
     **/
    public function __construct()
    {
        $this->request = null;
        $this->bannerManager = null;
        $this->responseArray = array();
        $this->session = null;
        $this->instanceId = 0;
    }
        
    /**
     * @author Employee Id: 4571
     * Description : To unset member variables
     *
     * @param  : null
     *
     * @return null
     *
     * @throws null
     *
     **/
    public function __destruct()
    {
        unset($this->request);
        unset($this->bannerManager);
        unset($this->responseArray);
        unset($this->session);
        unset($this->instanceId);
    }
        
    /**
     * @author Employee Id: 4571
     * Description : To initialize request and services
     *
     * @param  : null
     *
     * @return null
     *
     * @throws null
     *
     **/
    public function initAction()
    {
        $this->request = $this->getRequest();
        $this->bannerManager = $this->get('office_brain_banner_manager');
        $instanceId = $this->request->get('project_setting')["instance_id"];
       
        $this->cmsInstanceId = $this->request->get('instance_id');
        if($this->cmsInstanceId > 0)
        {
            $this->instanceId = $this->cmsInstanceId;
        }
        else
        {
            $this->instanceId = $instanceId;
        }
        
        $this->translator = $this->get('translator');
        $this->session = $this->request->getSession();
        //$this->isAjax = $this->request->isXmlHttpRequest();
        $this->commonLibraryManager = $this->get('office_brain_common_library');
        $this->statsh_cache_wrapper=RedisCacheService::create();
		$this->moduleCachePrefix = '__HomePageBannerList__';
    }
      
    /**
     *
     * @author Employee Id: 4571
     * Description : Add banner action to save Banner
     *
     * @param  : null
     *
     * @return Response Array to twig
     *
     * @throws null
     *
     * @Route("/banner/add/{instance_id}", name="office_brain_bannerbundle_banneradmin_addbanner",
     * requirements={"instance_id"="\d+"},
     * defaults={"instance_id"="0"},
     * options={"expose"=true}
     * )
     * @Method("GET")
     * @Template("OfficeBrainBannerBundle:BannerAdmin:addBanner.html.twig")
     *
     **/
    public function addBannerAction()
    {
        $this->initAction();
        
        $country = $this->bannerManager->getCountry();
        $banner = new Banner();
        $banner = $this->bannerManager->getLanguage($banner);
        $param['action']='add';
        $form = $this->createForm(new BannerType($country, $param['action'],$this->instanceId), $banner, array(
                'action' => $this->generateUrl('office_brain_bannerbundle_banneradmin_processbannersubmit'),
                'method' => 'POST',
        ));
            
        $this->responseArray['banner']=$banner;
        $this->responseArray['action']=$param['action'];
        $this->responseArray['form']=$form->createView();
        
        return $this->responseArray;
    }
    
    /**
     *
     * @author Employee Id: 4571
     * Description : Banner Type submit form action to save Banner
     *
     * @param  : null
     *
     * @return Response Array to twig
     *
     * @throws null
     *
     * @Route("/banner/add/{instance_id}", name="office_brain_bannerbundle_banneradmin_processbannersubmit",
     * requirements={"instance_id"="\d+"},
     * defaults={"instance_id"="0"},
     * options={"expose"=true}
     * )
     * @Method("POST")
     * @Template("OfficeBrainBannerBundle:BannerAdmin:addBanner.html.twig")
     *
     **/
    public function processBannerSubmitAction()
    {
        $this->initAction();
       
        $banner = new Banner();
        $country = $this->bannerManager->getCountry();
        $banner = $this->bannerManager->getLanguage($banner);
        $param['action']='add';
        $form   = $this->createForm(new BannerType($country, $param['action'],$this->instanceId), $banner, array(
                'action' => $this->generateUrl('office_brain_bannerbundle_banneradmin_processbannersubmit',array('instance_id'=>$this->instanceId)),
                'method' => 'POST',
        ));
            
        $form->handleRequest($this->request);

        $form = $this->bannerManager->filterFormData($form);

        if ($form->isValid()) { // if form valid than save to db
            $this->bannerManager->setBanner($form->getData());
            RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefix);
            if($this->cmsInstanceId>0)
            {
                $this->responseArray['status'] = strtolower($this->translator->trans('subshop_content.admin.action.success'));
                $this->responseArray['success_message'] = $this->translator->trans('bannertype.header.form.add_banner_msg');
                $this->responseArray['banner_list_url'] = $this->generateUrl('office_brain_bannerbundle_banneradmin_listbanner',array('instance_id'=>$this->request->get('instance_id')) );
                return new JsonResponse($this->responseArray);
            }
            else
            {
                $this->get('session')->getFlashBag()->add('success_message', $this->translator->trans('bannertype.header.form.add_banner_msg'));
                return $this->redirect($this->generateUrl('office_brain_bannerbundle_banneradmin_listbanner'));
            }

        }
        else {
            
            if($this->cmsInstanceId>0)
            {
                
        	$this->responseArray = $this->commonLibraryManager->prepareFormJsonError($form);
        	return new JsonResponse($this->responseArray);
            }
            else
            {
               
                $this->responseArray['banner']=$banner;
                $this->responseArray['action']=$param['action'];
                $this->responseArray['form']=$form->createView();
                return $this->responseArray;
            }
        }                 
 
    }
      
    /**
     *
     * @author Employee Id: 4571
     * Description : Banner edit action to update Banner
     *
     * @param  : null
     *
     * @return Response Array to twig
     *
     * @throws null
     *
     * @Route("/banner/edit/{id}/{instance_id}", name="office_brain_bannerbundle_banneradmin_editbanner",
     * requirements={"instance_id"="\d+"},
     * defaults={"instance_id"="0"},
     * options={"expose"=true}
     * )
     * @Method("GET")
     * @Template("OfficeBrainBannerBundle:BannerAdmin:editBanner.html.twig")
     *
     **/
    public function editBannerAction($id)
    {
        $this->initAction();
        
        $param=$this->request->get('_route_params');
        $param['action'] ="update";
        
        $country = $this->bannerManager->getCountry();
        $banner = $this->bannerManager->getBanner($param['id']);
        $form=$this->createForm(new BannerType($country, $param['action'],$this->instanceId), $banner, array(
                    'action' => $this->generateUrl('office_brain_bannerbundle_banneradmin_processeditbannersubmit', array('id'=>$param['id'])),
                    'method' => 'POST',
            ));
                                 
        $this->responseArray['banner']=$banner;
        $this->responseArray['action']=$param['action'];
        $this->responseArray['form']=$form->createView();
        $this->responseArray['bannerHtml'] = json_decode($form->getData()->getBannerHtml());
        $this->responseArray['banner_id'] = $id;

        return $this->responseArray;
    }
    
    /**
     *
     * @author Employee Id: 4571
     * Description : Banner edit banner submit action to update Banner
     *
     * @param  : null
     *
     * @return Response Array to twig
     *
     * @throws null
     *
     * @Route("/banner/edit/{id}/{instance_id}", name="office_brain_bannerbundle_banneradmin_processeditbannersubmit",
     * requirements={"instance_id"="\d+"},
     * defaults={"instance_id"="0"},
     * options={"expose"=true}
     * )
     * @Method("POST")
     * @Template("OfficeBrainBannerBundle:BannerAdmin:editBanner.html.twig")
     *
     **/
    public function processEditBannerSubmitAction($id)
    {
        $this->initAction();
        
        $banner= $this->bannerManager->getBanner($id);
        $imagePathData  = $banner->getUploadedBanner();
        $country = $this->bannerManager->getCountry();
        $param['action']='update';
        $form = $this->createForm(new BannerType($country, $param['action'],$this->instanceId), $banner);
        $form->handleRequest($this->request);

        if ($form->isValid()) {
        	$this->bannerManager->updateBanner($form->getData());
        	RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefix);
            if($this->cmsInstanceId>0)
            {
                $this->responseArray['status'] = strtolower($this->translator->trans('subshop_content.admin.action.success'));
                $this->responseArray['success_message'] = $this->translator->trans('bannertype.header.form.edit_banner_msg');
                $this->responseArray['banner_list_url'] = $this->generateUrl('office_brain_bannerbundle_banneradmin_listbanner',array('instance_id'=>$this->request->get('instance_id')) );
                return new JsonResponse($this->responseArray);
            }
            else
            {
                $this->get('session')->getFlashBag()->add('success_message', $this->translator->trans('bannertype.header.form.edit_banner_msg'));
            	return $this->redirect($this->generateUrl('office_brain_bannerbundle_banneradmin_listbanner'));
            }
        }
        else {
            if($this->cmsInstanceId>0)
            {
        	$this->responseArray = $this->commonLibraryManager->prepareFormJsonError($form);
        	return new JsonResponse($this->responseArray);
            }
            else
            {
                $this->responseArray['banner']=$banner;
                $this->responseArray['banner_id'] = $id;
                $this->responseArray['action']=$param['action'];
                $this->responseArray['form']=$form->createView();
                $this->responseArray['bannerHtml'] = json_decode($form->getData()->getBannerHtml());
                
                return $this->responseArray;
            }
        }       
       
    }
    
    /**
     *
     * @author Employee Id: 4571
     * Description : Banner delete action
     *
     * @param  : null
     *
     * @return Response Array
     *
     * @throws null
     *
     * @Route("/banner/delete/{action}/{id}/{instance_id}", name="office_brain_bannerbundle_banneradmin_deletebanner",
     * requirements={"instance_id"="\d+"},
     * defaults={"instance_id"="0"},
     * options={"expose"=true}
     * )
     * @Template()
     *
     **/
    public function deleteBannerAction()
    {
        $this->initAction();
        $id=$this->request->get('id');
        $this->bannerManager->deleteBanner($id);
        RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefix);
        return array();
    }
    
    /**
     *
     * @author Employee Id: 4571
     * Description : Banner delete action
     *
     * @param  : null
     *
     * @return Response Json Array
     *
     * @throws null
     *
     * @Route("/banner/delete/{instance_id}", name="office_brain_bannerbundle_banneradmin_deletebanner_ajax",
     * requirements={"instance_id"="\d+"},
     * defaults={"instance_id"="0"},
     * options={"expose"=true}
     * )
     * @Template()
     *
     **/
    public function deleteBannerAjaxAction()
    {
        $this->initAction();
        $bannerGroup = $this->bannerManager->deleteBannerAjax();
        RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefix);
        $this->get('session')->getFlashBag()->add('success_message', $this->get('translator')->trans('bannertype.header.form.banner_delete_msg'));
        
        return new JsonResponse(array('success' => 'success', 'page_url' => $this->generateUrl('office_brain_bannerbundle_banneradmin_listbanner', array())));
    }
    
    /**
     *
     * @author Employee Id: 4571
     * Description : List Banner action
     *
     * @param  : null
     *
     * @return Array
     *
     * @throws null
     *
     * @Route("/banner/list/{page}/{instance_id}", name="office_brain_bannerbundle_banneradmin_listbanner",
     * requirements={"records_per_page"="12|24|48|96|996", "page"="\d+","instance_id"="\d+"},
     * defaults={"records_per_page"=1000,"page"=1, "instance_id"="0"},
     * options={"expose"=true}
     * )
     * @Template("OfficeBrainBannerBundle:BannerAdmin:listBanner.html.twig")
     *
     **/
    public function listBannerAction()
    {
        $this->initAction();
       
        $this->responseArray = $this->bannerManager->getBannerList();

        return $this->responseArray;
    }
    
    
    /**
     *
     * @author Employee Id: 4571
     * Description : List Banner Ajax action
     *
     * @param  : null
     *
     * @return Array
     *
     * @throws null
     *
     * @Route("/banner/list-ajax/{culture}/{page}/{instance_id}", name="office_brain_bannerbundle_banneradmin_listbannerajax",
     * requirements={"records_per_page"="12|24|48|96|996", "page"="\d+","instance_id"="\d+"},
     * defaults={"culture"="en_us","records_per_page"=1000,"page"=1, "instance_id"="0"},
     * options={"expose"=true}
     * )
     * @Template("OfficeBrainBannerBundle:BannerAdmin:tabBannerListContents.html.twig")
     *
     **/
    public function listBannerAjaxAction()
    {
        $this->initAction();
                 
        $this->responseArray = $this->bannerManager->getBannerListAjax();
        
        return $this->responseArray;
    }
    
    /**
     *
     * @author Employee Id: 4571
     * Description : Get the banner view details
     *
     * @param  : null
     *
     * @return Array
     *
     * @throws null
     *
     * @Route("/banner/view-details/{instance_id}", name="office_brain_bannerbundle_banneradmin_bannerdetailsajax",
     * requirements={"instance_id"="\d+"},
     * defaults={"instance_id"="0"},
     * options={"expose"=true}
     * )
     * @Template()
     *
     **/
    public function bannerDetailsAjaxAction()
    {
        $this->initAction();
        
        $this->responseArray = $this->bannerManager->getBannerDetails();
        
        return array('data'=>$this->responseArray);
    }
    
    
    /**
     *
     * @author Employee Id: 4571
     * Description : To Sort Listing
     *
     * @param  : null
     *
     * @return Response
     *
     * @throws null
     *
     * @Route("/banner/sort-position/{instance_id}",
     * name="office_brain_bannerbundle_banneradmin_positionlist",
          * requirements={"instance_id"="\d+"},
     * defaults={"instance_id"="0"},
     * options={"expose"=true}
     * )
     * @Template()
     *
     **/
    public function positionListAction()
    {
        $this->initAction();
        $param=$this->request->request->all();
        if (count($param)) {
            foreach ($param['prod_list'] as $key=>$val) {
                $banner=new Banner();
                $key=$key+1;
                $bannerManager = $this->bannerManager->setBannerListPosition($banner, $key,$val);
            }
        }
        if ($this->request->isXmlHttpRequest()) {
			RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefix);
            $response = new Response();
            $output = array('success' => 'success');
            $response->headers->set('Content-Type', 'application/json');
            $response->setContent(json_encode($output));
            return $response;
        }
    }
    
    /**
     *
     * @author Employee Id: 4571
     * Description : To Search BannerType
     *
     * @param  : null
     *
     * @return Response
     *
     * @throws null
     *
     * @Route("/banner/search/{instance_id}/{culture}/{page}", name="office_brain_bannerbundle_banneradmin_searchbannertypeajax",
     * requirements={"records_per_page"="12|24|48|96|996", "page"="\d+","instance_id"="\d+"},
     * defaults={"culture"="en_us","records_per_page"=10,"page"=1, "instance_id"="0"},
     * options={"expose"=true}
     * )
     * @Template("OfficeBrainBannerBundle:BannerAdmin:tabBannerListContents.html.twig")
     *
     **/
    public function searchBannerTypeAjaxAction()
    {
        $this->initAction();
        
        $this->responseArray = $this->bannerManager->getBannerListAjax();
        
        return $this->responseArray;
    }
          
    
    /**
     *
     * @author Employee Id: 4571
     * Description : Make a copy of banner
     *
     * @param 1 : type image
     *
     * @return thumbimage name
     *
     * @throws null
     *
     * @return $image
     *
     * @Route("/banner/copy-banner/{instance_id}", name="office_brain_bannerbundle_banneradmin_copybanner",
     * requirements={"instance_id"="\d+"},
     * defaults={"instance_id"="0"},
     * options={"expose"=true}
     * )
     * @Method({"POST"})
     *
     **/
    public function copyBannerAction()
    {
        $this->initAction();
        
        $bannerGroup = $this->bannerManager->copyBannerGroup();
        RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefix);
        //$this->session->set('service-list-success', $this->get('translator')->trans('admin.service_group_management.service_group.copy_message'));
        return $this->redirect($this->generateUrl('office_brain_bannerbundle_banneradmin_listbanner', array()));
    }
    
    /**
     *
     * @author Employee Id: 4571
     * Description : Get Banner Style Action
     *
     * @param : null
     *
     * @return Response Array to Twig
     *
     * @throws null
     *
     * @Route("/banner-style/{instance_id}", name="office_brain_bannerbundle_bannermaster_getbannerstyle",
      * requirements={"instance_id"="\d+"},
     * defaults={"instance_id"="0"},
     * options={"expose"=true}
     * )
     * @Template()
     *
     **/
    public function getBannerStyleAction()
    {
        $this->initAction();
         
        $this->responseArray = $this->bannerManager->getStyleOfBanner();
        
        return new JsonResponse(array('success' => 'success', 'resp'=>$this->responseArray));
    }
    
    /**
     *
     * @author Employee Id: 4505
     * Description : get Banner Preview Action
     *
     * @param : null
     *
     * @return Response Array to Twig
     *
     * @throws null
     *
     * @Route("/banner-preview/{instance_id}", name="office_brain_bannerbundle_bannermaster_getbannerpreview",
     * requirements={"instance_id"="\d+"},
     * defaults={"instance_id"="0"},
     * options={"expose"=true}
     * )
     * @Template("OfficeBrainBannerBundle:BannerAdmin:preview.html.twig")
     *
     * @Method({"GET"})
     **/
    public function getBannerPreviewAction()
    {
        $this->initAction();
         
        $this->responseArray = $this->bannerManager->getBannerPreview();
        
        return $this->responseArray;
    }
    

    /**
     *
     * @author Employee Id: 4273
     *
     * Description : Change Status banner.
     *
     * @param 1 : Rule Master Id
     *
     * @return type : JsonResponse object
     *
     * @throws Exception: No exception
     *
     * @Route("/banner/change-status/{instance_id}", name="office_brain_bannerbundle_banner_change_status",
     * requirements={"instance_id"="\d+"},
     * defaults={"instance_id"="0"},
     * options={"expose"=true}
     * )
     *
     * @Method({"POST"})
     *
     * @Template()
     *
     */
    public function changeStatusAction()
    {
    	$this->initAction();
    
    	$id = $this->request->get('id');
    
    	if ($id) {
    		$status = $this->bannerManager->changeStatus($id);
    		RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefix);
    		if ($status) {
    			return new JsonResponse(array('status' => 'success', 'status_message' => $this->translator->trans('banner.admin.status_message_success')));
    		}
    	}
    
    	return new JsonResponse(array('status' => 'fail', 'status_message' => $this->translator->trans('banner.admin.status_message_fail')));
    }
    
    /**
     * @author Employee Id: 4505
     * Description : Ajax Image upload.
     *
     * @param 1 :none
     *
     * @return type : Data.
     *
     * @throws Exception: Null
     *
     * @Route("/upload/banner-image/{instance_id}", name="office_brain_bannerbundle_banneradmin_uploadbannerimageajax",
      * requirements={"instance_id"="\d+"},
     * defaults={"instance_id"="0"},
     * options={"expose"=true}
     * )
     *
     * @Method("POST")
     */
    public function uploadBannerImageAjaxAction()
    {
        $this->initAction();
        $responseArray = $this->bannerManager->uploadBannerImage();
        if ($responseArray == 'SIZE_FILE') {
            $mb = ini_get("upload_max_filesize");
            $this->responseArray['status'] = 'error';
            $this->responseArray['error_message'] = 'File size exceed more than '.$mb;
            return new JsonResponse($this->responseArray);
        }
        if ($responseArray != 'BANNER_IMAGE_NOT_FOUND') {
            $this->responseArray = $responseArray;
            if ($responseArray != 'INVALID_FILE') {
				RedisCacheService::removeCacheByPrefix($this->statsh_cache_wrapper,$this->moduleCachePrefix);
                $this->responseArray['status'] = $this->translator->trans('cms.admin.menu.form.status.success');
                $this->responseArray['success_message'] = $this->translator->trans('cms.admin.menu.form.status.background_upload_success_message');
            } else {
                $this->responseArray['status'] = $this->translator->trans('cms.admin.menu.form.status.error');
                $this->responseArray['error_message'] = $this->translator->trans('cms.admin.menu.error.invalid_file');
            }
        } else {
            $this->responseArray['status'] = $this->translator->trans('cms.admin.menu.form.status.error');
            $this->responseArray['error_message'] = $this->translator->trans('cms.admin.menu.error.no_record_found_menu_item');
        }

        return new JsonResponse($this->responseArray);
    }
}
