<?php

namespace OfficeBrain\Bundle\BlogBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Translation\Translator;

use OfficeBrain\Bundle\BlogBundle\Entity\Category;
use OfficeBrain\Bundle\BlogBundle\Form\CategoryType;

/**
 * Category controller.
 *
 * @Route("admin/{_locale}/blog/category")
 */
class CategoryController extends Controller
{

    /**
     * Lists all Category entities.
     *
     * @Route("/", name="officebrain_blog_category_index")
     * requirements={"records_per_page"="12|24|48|96|996","page"="\d+"},
     * defaults={"records_per_page"=12,"page"=1}),
     * @Template()
     */
    public function indexAction()
    {
        $this->request = $this->getRequest();
        $em = $this->getDoctrine()->getManager();
        $option           = $this->request->query->get('option', NULL);
        $keywords           = $this->request->query->get('keywords', NULL);
        $page           = $this->request->get('page', '1');
        $recordsPerPage = $this->request->get('recordsPerPage', 12);
        $start_index    = (($page - 1) * $recordsPerPage - 1);

        $search = array('categoryIsDeleted' => 0 );
        if($option!="" && $keywords!=""){
            if($option=="categoryStatus"){
                $search[$option] = ($keywords=="Active") ? 1: 0 ;
            }else{
                $search[$option] = $keywords;
            }
        }

        $entities = $em->getRepository('OfficeBrainBlogBundle:Category')->findBy($search, array('id' => 'DESC'));
        
        
        $paginator  = $this->get('knp_paginator');
        $data['pagination'] = $paginator->paginate($entities, $page, $recordsPerPage, array(), count($entities));
        if($page>1 && count($data['pagination']->getItems()) == 0) {
            
            return $this->redirect($this->generateUrl('officebrain_blog_category_index', array('page'=> $page-1)));
            
        }
        
        return array(
            'data' => $data,
             'option'=>$option,
            'keywords'=>$keywords,
            'page'=>$page
        );


    }
    /**
     * Creates a new Category entity.
     * @Route("/new", name="officebrain_blog_category_create")
     * @Template("OfficeBrainBlogBundle:Category:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity = new Category();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

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

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Creates a form to create a Category entity.
     *
     * @param Category $entity The entity
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(Category $entity)
    {
       
        $form = $this->createForm(new CategoryType(), $entity, array(
            'action' => $this->generateUrl('officebrain_blog_category_create'),
     
        ));

        //$form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

    
    /**
     * Finds and displays a Category entity.
     * @Route("/show/{id}", name="officebrain_blog_category_show")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('OfficeBrainBlogBundle:Category')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Category entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Displays a form to edit an existing Category entity.
     *
     * @Route("/{id}", name="officebrain_blog_category_edit")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('OfficeBrainBlogBundle:Category')->find($id);
        
        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Category entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'        => $entity,
            'form'          => $editForm->createView(),
            'delete_form'   => $deleteForm->createView(),
        );
    }

    /**
    * Creates a form to edit a Category entity.
    * @param Category $entity The entity
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Category $entity)
    {
        $form = $this->createForm(new CategoryType(), $entity, array(
            'action' => $this->generateUrl('officebrain_blog_category_update', array('id' => $entity->getId())),
        ));

        return $form;
    }
    /**
     * Edits an existing Category entity.
     *
     * @Route("/edit/{id}", name="officebrain_blog_category_update")
     * @Template("OfficeBrainBlogBundle:Category:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('OfficeBrainBlogBundle:Category')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Category entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

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

        return array(
            'entity'      => $entity,
            'form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }
    /**
     * Deletes a Category entity.
     *
     * @Route("/delete/{id}", name="officebrain_blog_category_delete")
     */
    public function deleteAction($id)
    {
        
        $em = $this->getDoctrine()->getManager();
        $entity = $em->getRepository('OfficeBrainBlogBundle:Category')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Category entity.');
        }
        // $em->remove($entity);
        // $em->flush();

        $entity->setCategoryIsDeleted(true);
        $em->persist($entity);
        $em->flush();   
        

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

    /**
     * Creates a form to delete a Category entity by id.
     *
     * @param mixed $id The entity id
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('officebrain_blog_category_index', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm()
        ;
    }
}
