<?php

namespace OfficeBrain\Bundle\CmsBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use OfficeBrain\Bundle\CmsBundle\Form\CmsPageMasterType;

/**
 * @author OfficeBrain 4494 <info@officebrain.com>
 *
 * Description : CMS Admin controller class
 *
 * @Route("/admin/{_locale}/cms/page")
 **/
class CmsPageAdminController extends Controller
{
    private $request;

    private $session;

    private $translator;

    private $projectSetting;

    private $recordsPerPage;

    private $cmsPageManager;

    private $responseArray;

    public function __destruct()
    {
        unset($this->request);
        unset($this->session);
        unset($this->translator);
        unset($this->projectSetting);
        unset($this->cmsPageManager);
        unset($this->responseArray);
    }

    public function initAction()
    {
        $this->request = $this->getRequest();
        $this->session = $this->request->getSession();
        $this->translator = $this->get('translator');
        $this->projectSetting = $this->request->get('project_setting');
        $this->cmsPageManager = $this->get('office_brain_cms_page_manager');
        $this->responseArray = array();
    }

    /**
     * @author Employee Id: 4494
     * Description : Get the list of pages
     *
     * @Route("/list/{instance_id}/{page}", name="office_brain_cmsbundle_cmspageadmin_pagelist",
     * options={"expose"=true},
     * requirements={"instance_id"="\d+", "page"="\d+"},
     * defaults={"instance_id"="0", "page"=1})
     *
     * @Method("GET")
     * @Template("OfficeBrainCmsBundle:CmsPageAdmin:pageList.html.twig")
     *
     * @return array
     */
    public function pageListAction()
    {
        $this->initAction();

        $this->responseArray = $this->cmsPageManager->getCmsPageList();

        return $this->responseArray;
    }

    /**
     * @author Employee Id: 4795
     * Description : Get the list pages.
     *
     * @Route("/list-ajax/{page}", name="office_brain_cmsbundle_cmspageadmin_pagelistajax",
     * options={"expose"=true},
     * requirements={ "page"="\d+"},
     * defaults={ "page"=1})
     *
     * @Method("POST")
     * @Template("OfficeBrainCmsBundle:CmsPageAdmin:pageListAjax.html.twig")
     *
     * @return array
     */
    public function pageListAjaxAction()
    {
        $this->initAction();
        $this->responseArray = $this->cmsPageManager->getCmsPageList();

        return $this->responseArray;
    }

    /**
     * @author Employee Id: 4494
     * Description : Display page form.
     *
     * @param 1 : No paramater
     *
     * @return type : Form view.
     *
     * @throws Exception: Null
     *
     * @Route("/add/{instance_id}", name="office_brain_cmsbundle_cmspageadmin_pageadd",
     * defaults={"instance_id"="0"},
     * requirements={"instance_id"="\d+"},
     * options={"expose"=true})
     * @Method("GET")
     * @Template("OfficeBrainCmsBundle:CmsPageAdmin:add.html.twig")
     */
    public function pageAddAction()
    {
        $this->initAction();

        $this->responseArray['form'] = $this->createForm(new CmsPageMasterType($this->container), $this->cmsPageManager->getCmsPageMasterWithLanguage())->createView();

        return $this->responseArray;
    }

    /**
     * @author Employee Id: 4136
     * Description : Save page content
     *
     * @param 1 : No paramater
     *
     * @return type : Form view.
     *
     * @throws Exception: Null
     *
     * @Route("/add/{instance_id}", name="office_brain_cmsbundle_cmspageadmin_processpageadd",
     * defaults={"instance_id"="0"},
     * requirements={"instance_id"="\d+"},
     * options={"expose"=true})
     *
     * @Method({"POST"})
     *
     * @Template("OfficeBrainCmsBundle:CmsPageAdmin:add.html.twig")
     */
    public function processPageAddAction()
    {
        $this->initAction();

        $form = $this->createForm(new CmsPageMasterType($this->container), $this->cmsPageManager->getCmsPageMasterWithLanguage());

        $form->handleRequest($this->request);

        $form = $this->cmsPageManager->filterFormData($form, $this->translator);

        if ($form->isValid()) {
            $resultArray = $this->cmsPageManager->setCmsPage($form->getData());
            
            if ($resultArray == 'ERROR_SLUG_ALREADY_EXISTS') {
                $this->responseArray['form'] = $form->createView();  // if error than render form and show error
                 $this->get('session')->getFlashBag()->add('error_message', $this->translator->trans('cms.admin.action.page.cms_slug_duplicate_err'));
                                 
                return $this->responseArray;
            }
            
            $this->session->getFlashBag()->set('success_message', $this->translator->trans('cms.admin.action.page.cms_page_add_success'));
            
            if ($this->request->isXmlHttpRequest()) {
                return new JsonResponse(array('success' => 'success', 'page_url' => 'office_brain_cmsbundle_cmspageadmin_pagelist'));
            } else {
                return $this->redirect($this->generateUrl('office_brain_cmsbundle_cmspageadmin_pagelist'));
            }
        }

        $this->responseArray['form'] = $form->createView();

        return $this->responseArray;
    }

    /**
     * @author Employee Id: 4136
     * Description : Display page form.
     *
     * @param 1 : No paramater
     *
     * @return type : Form view.
     *
     * @throws Exception: Null
     *
     * @Route("/edit/{id}/{instance_id}", name="office_brain_cmsbundle_cmspageadmin_pageedit",
     * defaults={"instance_id"="0"},
     * requirements={"id"="\d+", "instance_id"="\d+"},
     * options={"expose"=true})
     * @Method("GET")
     * @Template("OfficeBrainCmsBundle:CmsPageAdmin:edit.html.twig")
     */
    public function pageEditAction()
    {
        $this->initAction();

        $this->responseArray['form'] = $this->createForm(new CmsPageMasterType($this->container), $this->cmsPageManager->getCmsPageById())->createView();

        return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 4494
     * Description : Display page form.
     *
     * @param 1 : No paramater
     *
     * @return type : Form view.
     *
     * @throws Exception: Null
     *
     * @Route("/edit-by/{slug}/{instance_id}", name="office_brain_cmsbundle_cmspageadmin_pageeditbyslug",
     * defaults={"instance_id"="0"},
     * requirements={"id"="\d+", "instance_id"="\d+"},
     * options={"expose"=true})
     * @Method("GET")
     * @Template("OfficeBrainCmsBundle:CmsPageAdmin:editBySlug.html.twig")
     */
    public function pageEditBySlugAction()
    {
    	$this->initAction();
    	
    	$page = $this->cmsPageManager->getCmsPageBySlug();
    	
    	if (!isset($page['error'])) {
    		$this->responseArray['page_id'] = $page['id'];
    		$this->responseArray['form'] = $this->createForm(new CmsPageMasterType($this->container), $this->cmsPageManager->getCmsPageById($page['id']))->createView();
    	}
    	
    	return $this->responseArray;
    }

    /**
     * @author Employee Id: 4136
     * Description : Display page form.
     *
     * @param 1 : No paramater
     *
     * @return type : Form view.
     *
     * @throws Exception: Null
     *
     * @Route("/edit/{id}/{instance_id}", name="office_brain_cmsbundle_cmspageadmin_processpageedit",
     * defaults={"instance_id"="0"},
     * requirements={"id"="\d+", "instance_id"="\d+"},
     * options={"expose"=true})
     * @Method("POST")
     * @Template("OfficeBrainCmsBundle:CmsPageAdmin:edit.html.twig")
     */
    public function processPageEditAction()
    {
        $this->initAction();

        $form = $this->createForm(new CmsPageMasterType($this->container), $this->cmsPageManager->getCmsPageById());

        $form->handleRequest($this->request);

        if ($form->isValid()) {
            $pageObj = $this->cmsPageManager->updateCmsPage($form->getData());

            $this->session->getFlashBag()->set('success_message', $this->translator->trans('cms.admin.action.page.cms_page_update_success'));

            if ($this->request->isXmlHttpRequest()) {
                return new JsonResponse(array('success' => 'success', 'page_url' => 'office_brain_cmsbundle_cmspageadmin_pagelist'));
            } else {
            	if ($this->request->get('iframe')) {
            		return $this->redirect($this->generateUrl('office_brain_cmsbundle_cmspageadmin_pageeditbyslug', array('slug' => $pageObj->getSlug(), 'instance_id' => $this->request->get('instance_id'), 'iframe' => $this->request->get('iframe'))));
            	}
            	
                return $this->redirect($this->generateUrl('office_brain_cmsbundle_cmspageadmin_pagelist'));
            }
        }

        $this->responseArray['form'] = $form->createView();

        return $this->responseArray;
    }

    /**
     * @author Employee Id: 4795
     * Description : make copy of page
     *
     * @Route("/copy", name="office_brain_cmsbundle_cmspageadmin_cmspagecopy")
     *
     * @Method({"POST"})
     */
    public function cmsPageCopyAction()
    {
        $this->initAction();

        $this->cmsPageManager->copyCmsPage();

        $this->session->getFlashBag()->add('success_message', $this->translator->trans('admin.service_group_management.make_copy.copy_message'));

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

    /**
     * @author Employee Id: 4795
     * Description : Delete page.
     *
     * @Route("/delete/{id}/{instance_id}", name="office_brain_cmsbundle_cmspageadmin_cmspagedelete",
     * defaults={"instance_id"="0"},
     * requirements={"id"="\d+", "instance_id"="\d+"},
     * options={"expose"=true})
     * @Method("GET")
     */
    public function cmsPageDeleteAction()
    {
        $this->initAction();

        $response = $this->cmsPageManager->deleteCmsPage();

        if ($response) {
            $this->session->getFlashBag()->add('success_message', $this->translator->trans('cms.admin.action.page.cms_page_delete_success'));
        } else {
            $this->get('session')->getFlashBag()->add('error_message', $this->translator->trans('cms.admin.action.page.cms_page_delete_error'));
        }

        if ($this->request->isXmlHttpRequest()) {
            return new JsonResponse(array('success' => 'success', 'page_url' => $this->generateUrl('office_brain_cmsbundle_cmspageadmin_pagelist', array())));
        } else {
            return $this->redirect($this->generateUrl('office_brain_cmsbundle_cmspageadmin_pagelist'));
        }
    }

    /**
     * @author Employee Id: 4494
     *
     * Description : Ajax base cms page search
     *
     * @Route("/search/{page}", name="office_brain_cmsbundle_cmspageadmin_cmspagesearch",
     * requirements={"page"="\d+"},
     * options={"expose"=true},
     * defaults={"page"=1})
     *
     * @Method("POST")
     * @Template("OfficeBrainCmsBundle:CmsPageAdmin:pageListAjax.html.twig")
     */
    public function cmsPageSearchAction()
    {
        $this->initAction();

        $this->responseArray = $this->cmsPageManager->searchCmsPage();

        return $this->responseArray;
    }
    
    /**
     * @author Employee Id: 5058
     *
     * Description : Ajax base cms page change status
     *
     * @Route("/change-status/{instance_id}", name="office_brain_cmsbundle_cmspageadmin_cmspage_change_status",
     * requirements={"instance_id"="\d+"},
     * options={"expose"=true},
     * defaults={"instance_id"="0"})
     *
     * @Method("POST")
     * @Template()
     */
    public function cmsPageChangeStatusAction()
    {
    	$this->initAction();
    	$id = $this->request->get('id');
    	
    	if ($id) {
    	$status = $this->cmsPageManager->changeStatus($id);
    	if ($status) {
    		return new JsonResponse(array('status' => 'success', 'status_message' => $this->translator->trans('cms.admin.status_message_success')));
    	}
    	}
    	return new JsonResponse(array('status' => 'fail', 'status_message' => $this->translator->trans('cms.admin.status_message_fail')));
    }
    
    /**
     * * @author Employee Id: 4795
     * Description : Get the page content and render page on fronend
     * 	 *
     * @Route("/view/{slug}/{instance_id}", name="office_brain_cmsbundle_cmspageadmin_cmspage_view",
     * requirements={"instance_id"="\d+"},
     * options={"expose"=true},
     * defaults={"instance_id"="0"})
     * 
     * @Template("OfficeBrainCmsBundle:CmsPageAdmin:cmsview.html.twig")
     */
    public function pageAction()
    {
    	$this->initAction();
    
    	$this->responseArray = $this->cmsPageManager->getCmsPageBySlug();
    
    	if (!empty($this->responseArray['error']) && $this->responseArray['error'] == "PAGE_NOT_FOUND") {
    		throw $this->createNotFoundException($this->translator->trans('cms.front.page_not_found'));
    	}
    
    	return $this->responseArray;
    }
}
