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

namespace VisualM\FormBundle\Controller;

use ReflectionClass;
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\Form\Type\FormType;
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->container->get('translator');

        $form_manager = $this->container->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->addFlash(
            '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->container->get('translator');
        $authChecker = $this->container->get('security.authorization_checker');
        
        if (!$authChecker->isGranted('ROLE_PERM_LIST_FORM')) {
             throw new AccessDeniedHttpException($translator->trans('form.access_denied', array(), 'exception'));
        }

        // Build AdminList
        $admin_list = $this->container->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 = (new ReflectionClass($this->container->getParameter('visualm.form.entity.form.class')))->newInstance();

        $form_form = $this->createForm(FormType::class, $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")
     *
     * @param Request $request Request
     * 
     * @return array View Data
     */
    public function addAction(Request $request)
    {
        $translator = $this->container->get('translator');
        
        if (!$this->container->get('security.authorization_checker')->isGranted('ROLE_PERM_ADD_FORM')) {
             throw new AccessDeniedHttpException($translator->trans('form.access_denied', array(), 'exception'));
        }      

        // Create Form
        $form = (new ReflectionClass($this->container->getParameter('visualm.form.entity.form.class')))->newInstance();
        $form->getFields()->add(new FormField());
        
        // Create Form form
        $form_form = $this->createForm(FormType::class, $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 Request $request Request
     * @param int     $id      Form Id
     * 
     * @return array View Data
     */
    public function editAction(Request $request, $id)
    {
        $translator = $this->container->get('translator');
       
        if (!$this->container->get('security.authorization_checker')->isGranted('ROLE_PERM_EDIT_FORM')) {
             throw new AccessDeniedHttpException($translator->trans('form.access_denied', array(), 'exception'));
        }
        // Get Manager
        $form_manager = $this->container->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(FormType::class, $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()
        );
    }

    /**
     * Copy Form
     *
     * @Block(view="VisualMFormBundle:ManageForm:form.html.twig", position="main")
     * @Block(view="VisualMFormBundle:ManageForm:toIndex.html.twig", position="titlebar")
     *
     * @param Request $request Request
     * @param int     $id      Form Id
     *
     * @return array View Data
     */
    public function copyAction(Request $request, $id)
    {
        $translator = $this->container->get('translator');

        if (!$this->container->get('security.authorization_checker')->isGranted('ROLE_PERM_EDIT_FORM')) {
             throw new AccessDeniedHttpException($translator->trans('form.access_denied', array(), 'exception'));
        }
        // Get Manager
        $form_manager = $this->container->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 = [];

        // Create Form form
        $form = clone $form;
        $form_form = $this->createForm(FormType::class, $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.copy.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->container->get('translator');
        
        if (!$this->container->get('security.authorization_checker')->isGranted('ROLE_PERM_DELETE_FORM')) {
             throw new AccessDeniedHttpException($translator->trans('exception.form_access_denied', array(), 'exception'));
        }
        // Get Manager
        $form_manager = $this->container->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->addFlash(
            'success',
            $translator->trans('form.form_deleted', array(), 'flashmessage')
        );
        
        return $this->redirect($this->generateUrl('manage_form_index'));
    }
    
}
