<?php

namespace OfficeBrain\Bundle\EmailBundle\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 OfficeBrain\Bundle\EmailBundle\Entity\EmailEventMaster;
use OfficeBrain\Bundle\EmailBundle\Form\EmailEventMasterType;
use Symfony\Component\HttpFoundation\JsonResponse;
/**
 * @author OfficeBrain 4795 <info@officebrain.com>
 *
 * Description: Manage events of email
 *
 * @Route("/admin/{_locale}")
 */
class EmailEventAdminController extends Controller
{
    /**
     * @author Employee Id: 4795
     *
     * Description : Set variables
     *
     * @param 1 : Null
     *
     * @return type : Null
     *
     * @throws Exception: Null
     **/
    public function __construct()
    {
        $this->responseArray = array();
        $this->request = null;
        $this->manager = null;
        $this->projectSetting = array();
        $this->translator = null;
        $this->accessRules = array();
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Unset variables
     *
     * @param 1 : Null
     *
     * @return type : Null
     *
     * @throws Exception: Null
     **/
    public function __destruct()
    {
        unset($this->request);
        unset($this->manager);
        unset($this->projectSetting);
        unset($this->accessRules);
        unset($this->translator);
        unset($this->responseArray);
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Set request and service
     *
     * @param 1 : Null
     *
     * @return type : Null
     *
     * @throws Exception: Null
     **/
    public function initAction()
    {
        $this->request = $this->getRequest();
        $this->projectSettings = $this->request->get('project_setting');
        $this->accessRules = $this->projectSettings['access_rule'];
        $this->manager = $this->get('office_brain_email_event_manager');
        $this->translator = $this->get('translator');
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Return all events of email
     *
     * @param 1 : Null
     *
     * @return type : Html Response
     *
     * @throws Exception: Null
     *
     * @Route("/email/list-event/{page}",
     * name="office_brain_emailbundle_emaileventadmin_listevent",
     * requirements={"page"="\d+"},
     * defaults={"page"=1})
     *
     * @Template("OfficeBrainEmailBundle:EmailEventAdmin:listEvent.html.twig")
     */
    public function listEventAction()
    {
        return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Return all events of email
     *
     * @param 1 : Null
     *
     * @return type : Html Response
     *
     * @throws Exception: Null
     *
     * @Route("/email/list-master-event/{page}",
     * name="office_brain_emailbundle_emaileventadmin_listmasterevent",
     * requirements={"page"="\d+"},
     * defaults={"page"=1})
     *
     * @Template("OfficeBrainEmailBundle:EmailEventAdmin:masterEvent.html.twig")
     */
    public function listMasterEventAction()
    {
        $this->initAction();
    
        $page  = $this->request->get('page', '1');
        
        $recordsPerPage = $this->projectSettings['configuration_rule']['site_management']['option']['email']['option']['email_record_per_page']['status'];
          
        $masterEvents = $this->manager->getMasterEventList();
            
        $paginator  = $this->get('knp_paginator');
        $this->responseArray['pagination'] = $paginator->paginate($masterEvents, $page, $recordsPerPage, array(), count($masterEvents));
        
        //unset variable
        unset($page);
        unset($recordsPerPage);
        unset($masterEvents);
        unset($paginator);
            
        return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Return all events of email
     *
     * @param 1 : Null
     *
     * @return type : Html Response
     *
     * @throws Exception: Null
     *
     * @Route("/email/list-child-event/{parentId}/{keyword}",
     * name="office_brain_emailbundle_emaileventadmin_listchildevent")
     *
     * @Template("OfficeBrainEmailBundle:EmailEventAdmin:childEvent.html.twig")
     */
    public function listChildEventAction($parentId,$keyword=null)
    {
        $this->initAction();
        
        $this->responseArray['events'] = $this->manager->getChildEventOfMaster($parentId, $keyword);
               
        return $this->responseArray;
    }
     /**
     *
     * @author Employee Id: 4835
     *
     * Description : Change Status email.
     *
     * @param 1 : Event Id
     *
     * @return type : JsonResponse object
     *
     * @throws Exception: No exception
     *
     * @Route("/email/change-event-status/{instance_id}", name="office_brain_emailbundle_emaileventadmin_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->manager->changeEventStatus($id);
    		if ($status) {
    			return new JsonResponse(array('status' => 'success', 'status_message' => $this->translator->trans('email.event.message.status_success')));
    		}
    	}
    
    	return new JsonResponse(array('status' => 'fail', 'status_message' => $this->translator->trans('email.event.message.status_error')));
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Generate event form
     *
     * @param 1 : Null
     *
     * @return type : Html Response
     *
     * @throws Exception: Null
     *
     * @Route("/email/add-event", name="office_brain_emailbundle_emaileventadmin_addevent")
     *
     * @Method("GET")
     *
     * @Template("OfficeBrainEmailBundle:EmailEventAdmin:addEvent.html.twig")
     */
    public function addEventAction()
    {
        $this->initAction();
        
        $form = $this->createForm(new EmailEventMasterType(), new EmailEventMaster());
         
        $this->responseArray['form'] = $form->createView();
        $this->responseArray['admin_email'] = $this->container->getParameter('admin_email');
        
        // unset variable
        unset($form);
        
        return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Store event data to database
     *
     * @param 1 : Null
     *
     * @return type : Html Response
     *
     * @throws Exception: Null
     *
     * @Route("/email/add-event", name="office_brain_emailbundle_emaileventadmin_addeventsubmit")
     *
     * @Method("POST")
     *
     * @Template("OfficeBrainEmailBundle:EmailEventAdmin:addEvent.html.twig")
     */
    public function addEventSubmitAction()
    {
        $this->initAction();
        
        $form = $this->createForm(new EmailEventMasterType(), new EmailEventMaster());
        
        $form->handleRequest($this->request);

        if ($form->isValid()) {
            $data = $this->manager->setEvent($form->getData());
            if (is_array($data) && isset($data['error'])) {
                $this->get('session')->getFlashBag()->add('error_message', $data['error']);
                return array('form' => $form->createView());
            }
            $this->get('session')->getFlashBag()->add('success_message', $this->translator->trans('email.event.message.add_success'));
            return $this->redirect($this->generateUrl('office_brain_emailbundle_emaileventadmin_listevent'));
        }
        
        $this->responseArray['form'] = $form->createView();
        
        // unset variable
        unset($form);
        unset($data);
        
        return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Generate edit event form
     *
     * @param 1 : Null
     *
     * @return type : Html Response
     *
     * @throws Exception: Null
     *
     * @Route("/email/edit-event/{id}", name="office_brain_emailbundle_emaileventadmin_editevent")
     *
     * @Method("GET")
     *
     * @Template("OfficeBrainEmailBundle:EmailEventAdmin:editEvent.html.twig")
     */
    public function editEventAction($id)
    {
        $this->initAction();
        
        $eventMasterEntity = $this->manager->getEvent($id);
        
        $parentEdit = '';
        if(empty($eventMasterEntity->getParentId()))
            $parentEdit = $eventMasterEntity->getName();
        
        $form = $this->createForm(new EmailEventMasterType($parentEdit), $eventMasterEntity);
        
        $this->responseArray['form'] = $form->createView();
        $this->responseArray['admin_email'] = $this->container->getParameter('admin_email');
        
        // unset variable
        unset($eventMasterEntity);
        unset($parentEdit);
        unset($form);
        
        return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Update event data to database
     *
     * @param 1 : Null
     *
     * @return type : Html Response
     *
     * @throws Exception: Null
     *
     * @Route("/email/edit-event/{id}", name="office_brain_emailbundle_emaileventadmin_editeventsubmit")
     *
     * @Method("POST")
     *
     * @Template("OfficeBrainEmailBundle:EmailEventAdmin:editEvent.html.twig")
     */
    public function editEventSubmitAction($id)
    {
        $this->initAction();
        
        $eventMasterEntity = $this->manager->getEvent($id);
        
        $parentEdit = '';
        if(empty($eventMasterEntity->getParentId()))
            $parentEdit = $eventMasterEntity->getName();
        
        $form = $this->createForm(new EmailEventMasterType(), $eventMasterEntity);
    
        $form->handleRequest($this->request);
        
        if ($form->isValid()) {
            $data = $this->manager->updateEvent($form->getData());
            if (is_array($data) && isset($data['error'])) {
                $this->get('session')->getFlashBag()->add('error_message', $data['error']);
            } else {
                $this->get('session')->getFlashBag()->add('success_message', $this->translator->trans('email.event.message.edit_success'));
                return $this->redirect($this->generateUrl('office_brain_emailbundle_emaileventadmin_listevent'));
            }
        }
        
        $this->responseArray['form'] = $form->createView();
        
        // unset variable
        unset($eventMasterEntity);
        unset($parentEdit);
        unset($form);
        unset($data);
        
        return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Soft delete master event from database
     *
     * @param 1 : Master event id
     *
     * @return type : Redirect to list page
     *
     * @throws Exception: Null
     *
     * @Route("/email/delete-master-event/{id}", name="office_brain_emailbundle_emaileventadmin_deletemasterevent")
     *
     * @Method("GET")
     */
    public function deleteMasterEventAction($id)
    {
        $this->initAction();
        
        $this->manager->deleteMasterEvent($id);
        
        return $this->redirect($this->generateUrl('office_brain_emailbundle_emaileventadmin_listevent'));
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Soft delete child event from database
     *
     * @param 1 : Child event id
     *
     * @return type : Redirect to list page
     *
     * @throws Exception: Null
     *
     * @Route("/email/delete-child-event/{id}", name="office_brain_emailbundle_emaileventadmin_deletechildevent")
     *
     * @Method("GET")
     */
    public function deleteChildEventAction($id)
    {
        $this->initAction();
        
        $data = $this->manager->deleteChildEvent($id);
        $this->get('session')->getFlashBag()->set('message', $data['msg']);
        
        // unset variable
        unset($data);
        
        return $this->redirect($this->generateUrl('office_brain_emailbundle_emaileventadmin_listevent'));
    }
    
    /**
     * @author Employee Id: 4795
     *
     * Description : View event
     *
     * @param 1 : Event id
     *
     * @return type : Html Response
     *
     * @throws Exception: Null
     *
     * @Route("/email/view-event/{id}", name="office_brain_emailbundle_emaileventadmin_viewevent")
     *
     * @Method("GET")
     *
     * @Template("OfficeBrainEmailBundle:EmailEventAdmin:viewEvent.html.twig")
     */
    public function viewEventAction($id)
    {
        $this->initAction();
        
        $this->responseArray['event'] = $this->manager->getEvent($id);
        
        return $this->responseArray;
    }
    
    
    /**
     * @author Employee Id: 4795
     *
     * Description : Search event action
     *
     * @param 1 : Null
     *
     * @return type : Html Response
     *
     * @throws Exception: Null
     *
     * @Route("/email/search-event-ajax/{page}",
     * name="office_brain_emailbundle_emaileventadmin_searcheventajax",
     * requirements={"page"="\d+"},
     * defaults={"page"=1})
     *
     * @Template("OfficeBrainEmailBundle:EmailEventAdmin:masterEvent.html.twig")
     */
    public function searchEventAjaxAction()
    {
        $this->initAction();
        
        $page  = $this->request->get('page', '1');
        $recordsPerPage = $this->projectSettings['configuration_rule']['site_management']['option']['email']['option']['email_record_per_page']['status'];
    
        //$dataArr['option'] = $this->request->get('option');
        $dataArr['keyword'] = $this->request->get('keyword');
        $events = $this->manager->searchEvent($dataArr);
        $this->responseArray['keyword'] = $dataArr['keyword'];
        $paginator  = $this->get('knp_paginator');
        $this->responseArray['pagination'] = $paginator->paginate($events, $page, $recordsPerPage, array(), count($events));
        
        //Unset variable
        unset($page);
        unset($recordsPerPage);
        //unset($dataArr);
        unset($events);
        unset($paginator);
        
        return $this->responseArray;
    }
}
