<?php
/**
 * ManageForm Controller
 * 
 * Is used for Managing Form's in the backend.
 * 
 * @author Elze Kool <info@visualmedia.nl>
 */

namespace VisualM\FormBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use VisualM\BlockManagerBundle\Annotation\Block;
use VisualM\BlockManagerBundle\Annotation\BlockLayout;
use VisualM\FormBundle\Entity\FormField;
use VisualM\FormBundle\Model\FormModel;

/**
 * ManageFormController
 * 
 * @BlockLayout(layout="backend")
 * @Block(view="page_header", position="titlebar", priority=1)
 * @Block(view="flashmessages", position="flashmessages")
 * 
 * @author Elze Kool <info@visualmedia.nl>
 */
class ManageFormController extends Controller
{
    /**
     * Storage for original form fields
     * @var type
     */
    private $orgFormFields = array();

    /**
     * Handle saving of Form
     *
     * @param FormModel $form       Form
     * @param Form        $form_form  Form Form
     * 
     * @return Response
     */
    protected function handleSave(FormModel $form, $form_form)
    {
        $translator = $this->get('translator');

        $form_manager = $this->get('visualm.form.manager.form');

        foreach($this->orgFormFields as $form_field) {
            if (!$form->getFields()->contains($form_field)) {
                $form_manager->deleteItem($form_field, [ 'flush' => false ]);
            }
        }

        foreach($form->getFields() as $form_field) {
            $form_field->setForm($form);
            $form_manager->saveItem($form_field, [ 'flush' => false ]);
        }

        $form_manager->saveItem($form);

        $this->get('session')->getFlashBag()->add(
            'success', $translator->trans('form.saved', array(), 'flashmessage')
        );

        if ($form_form->get('save')->isClicked()) {
            return $this->redirect($this->generateUrl('manage_form_edit', array('id' => $form->getId())));
        } else {
            return $this->redirect($this->generateUrl('manage_form_index', array()));
        }
    }
    
    /**
     * Show list of Form's
     *      
     * @Block(view="VisualMFormBundle:ManageForm:index.html.twig", position="main")
     * @Block(view="VisualMFormBundle:ManageForm:indexActions.html.twig", position="titlebar-actions")
     *
     * @param Request $request Request
     * @param string  $_route  Current route
     */
    public function indexAction(Request $request, $_route)
    {
        $translator = $this->get('translator');
        $security_context = $this->get('security.context');
        
        if (!$security_context->isGranted('ROLE_PERM_LIST_FORM')) {
             throw new AccessDeniedHttpException($translator->trans('form.access_denied', array(), 'exception'));
        }

        // Build AdminList
        $admin_list = $this->get('visualm.form.admin_list.form');

        return array(
            'page_title' => $translator->trans('form.index.page_title', array(), 'backend'),
            'admin_list' => $admin_list
        );
        
    }

    /**
     * Render HTML template for form or email
     *
     * @param Request $request Request
     * @param string  $type    Type
     *
     * @return Response Response
     */
    public function renderTemplateAction(Request $request, $type)
    {
        $form = $this->get('visualm.form.entity.form');
        $form_form = $this->createForm('visualm_form', $form);
        $form_form->handleRequest($request);

        $html = $this->renderView($this->container->getParameter('visualm.form.template.' . $type), [
            'form' => $form
        ]);

        return new Response(json_encode([
            'html' => $html
        ]), 200, [ 'content-type' => 'application/json']);

    }


    /**
     * Add Form
     *
     * @Block(view="VisualMFormBundle:ManageForm:form.html.twig", position="main")
     * @Block(view="VisualMFormBundle:ManageForm:toIndex.html.twig", position="titlebar")
     * 
     * @return array View Data
     */
    public function addAction()
    {
        $translator = $this->get('translator');
        $request = $this->getRequest();
        
        if (!$this->get('security.context')->isGranted('ROLE_PERM_ADD_FORM')) {
             throw new AccessDeniedHttpException($translator->trans('form.access_denied', array(), 'exception'));
        }      

        // Create Form
        $form = $this->get('visualm.form.entity.form');
        $form->getFields()->add(new FormField());
        
        // Create Form form
        $form_form = $this->createForm('visualm_form', $form);

        // Check if valid form is submitted
        $form_form->handleRequest($request);
        if ($form_form->isValid()) {
            return $this->handleSave($form, $form_form);
        }
        
        return array(
            'page_title' => $translator->trans('form.add.page_title', array(), 'backend'),
            'form' => $form,
            'form_form' => $form_form->createView()
        );
    }
    
    /**
     * Edit Form
     *
     * @Block(view="VisualMFormBundle:ManageForm:form.html.twig", position="main")
     * @Block(view="VisualMFormBundle:ManageForm:toIndex.html.twig", position="titlebar")
     *
     * @param integer $id Form Id
     * 
     * @return array View Data
     */
    public function editAction($id)
    {
        $translator = $this->get('translator');
        $request = $this->getRequest();
        
        if (!$this->get('security.context')->isGranted('ROLE_PERM_EDIT_FORM')) {
             throw new AccessDeniedHttpException($translator->trans('form.access_denied', array(), 'exception'));
        }
        // Get Manager
        $form_manager = $this->get('visualm.form.manager.form');

        // Load Form
        if (null === ($form = $form_manager->getFirst(array('id' => $id)))) {
            throw $this->createNotFoundException($translator->trans('form.not_found', array(), 'exception'));
        }

        $this->orgFormFields = $form->getFields()->toArray();

        // Create Form form
        $form_form = $this->createForm('visualm_form', $form);

        // Check if valid form is submitted
        $form_form->handleRequest($request);
        if ($form_form->isValid()) {
            return $this->handleSave($form, $form_form);
        }
        
        return array(
            'page_title' => $translator->trans('form.edit.page_title', array(), 'backend'),
            'page_sub_title' => $form->getTitel(),
            'form' => $form,
            'form_form' => $form_form->createView()
        );
    }
    
    /**
     * Delete SystemUser
     *
     * @param integer $id SystemUser Id
     *
     * @return array View Data
     */
    public function deleteAction($id)
    {
        $translator = $this->get('translator');
        $request = $this->getRequest();
        
        if (!$this->get('security.context')->isGranted('ROLE_PERM_DELETE_FORM')) {
             throw new AccessDeniedHttpException($translator->trans('exception.form_access_denied', array(), 'exception'));
        }
        // Get Manager
        $form_manager = $this->get('visualm.form.manager.form');

        // Load Form
        if (null === ($form = $form_manager->getFirst(array('id' => $id)))) {
            throw $this->createNotFoundException($translator->trans('exception.form_not_found', array(), 'exception'));
        }
        
        $form_manager->deleteItem($form);
        
        $this->get('session')->getFlashBag()->add(
            'success',
            $translator->trans('form.form_deleted', array(), 'flashmessage')
        );
        
        return $this->redirect($this->generateUrl('manage_form_index'));
    }
    
}
