<?php

namespace OfficeBrain\Bundle\BlogBundle\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 Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Translation\Translator;
use OfficeBrain\Bundle\BlogBundle\Entity\Post;
use OfficeBrain\Bundle\BlogBundle\Entity\Comment;
use OfficeBrain\Bundle\BlogBundle\Entity\PostCategoryInfo;
use OfficeBrain\Bundle\BlogBundle\Entity\PostTagInfo;
use OfficeBrain\Bundle\BlogBundle\Form\PostType;
use OfficeBrain\Bundle\BlogBundle\Form\CommentType;
use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * 
 * @Route("{_locale}/blog")
 */
class BlogController extends Controller
{
	protected $form;
	protected $request;
	protected $formData;
	protected $responseArray;
	protected $commonLibraryManager;
	protected $sessionManager;
	
	/**
	 *
	 * @author Employee Id: 4674
	 *
	 * Desciption: Define member variables with thier default value
	 *
	 * @param NULL
	 *
	 * @return NULL
	 *
	 * @throws NULL
	 *
	 */
	public function __construct()
	{
		$this->form = null;
		$this->request = null;
		$this->formData = null;
		$this->responseArray = array();
		$this->commonLibraryManager = null;
		$this->locale = null;
		$this->page = null;
		$this->recordsPerPage = null;
		$this->sessionManager =null;
	}
	
	/**
	 *
	 * @author Employee Id: 4674
	 *
	 * Desciption: Unset member variables
	 *
	 * @param NULL
	 *
	 * @return NULL
	 *
	 * @throws NULL
	 *
	 */
	public function __destruct()
	{
		
		unset($this->form);
		unset($this->request);
		unset($this->formData);
		unset($this->commonLibraryManager);
		unset($this->locale);
		unset($this->page);
		unset($this->recordsPerPage);
		unset($this->sessionManager);
	}
	
	/**
	 *
	 * @author Employee Id: 4674
	 *
	 * Desciption: Create and initialize various required object and member variables
	 *
	 * @param NULL
	 *
	 * @return NULL
	 *
	 * @throws NULL
	 *
	 */
	public function initAction()
	{
		$this->request = $this->getRequest();
		$this->projectSetting = $this->request->get('project_setting');
		$this->cultureId = $this->projectSetting['culture_id'];
		$this->locale = $this->projectSetting['culture_code'];
		$this->responseArray = array();
		$this->commonLibraryManager = $this->get('office_brain_common_library');
		$this->coreManager = $this->get('office_brain_core_manager');
		$this->page = $this->request->get('page', '1');
		$this->configurationRule = $this->projectSetting['configuration_rule']['transaction']['request_quote'];
		$this->recordsPerPage = $this->request->get('records_per_page', $this->configurationRule['list_front']['option']['no_of_product']);
		$this->sessionManager = $this->get('office_brain_session_manager');
		$this->translator = $this->get('translator');
	}
	
	/**
	 * Lists all Blog entities.
	 *
	 * @Route("", name="siteblog")
	 * requirements={"records_per_page"="12|24|48|96|996","page"="\d+"},
	 * defaults={"records_per_page"=2,"page"=1}),
	 * @Method("GET")
	 * @Template("OfficeBrainBlogBundle:Blog:index.html.twig")
	 */
	public function indexAction()
	{
		$this->initAction();
		$data = array();
		$page = $this->request->get('page', '1');
		$recordsPerPage = $this->request->get('recordsPerPage', 10);
		$start_index = (($page - 1) * $recordsPerPage - 1);
		$em = $this->getDoctrine()->getManager();

		$today = new \DateTime();
		$today = $today->format('Y-m-d H:i:s');
		//$today->setTime(0,0,0);
		$entities = $em->getRepository('OfficeBrainBlogBundle:Post')
		    ->createQueryBuilder('p')
		    ->where('p.postIsDeleted = :deleted')
		    ->andWhere('p.postStatus = :status')
		    ->andWhere('p.publishedDate < :today')
		    ->setParameter('deleted', 0)
		    ->setParameter('status', 1)
		    ->setParameter('today', $today)
		    ;

		if($this->request->get('catslug'))
		{
			$catslug = $this->request->get('catslug');
			$catid = $em->getRepository('OfficeBrainBlogBundle:Category')->findOneBy(array('slug' => $catslug));
			$postID = $em->getRepository('OfficeBrainBlogBundle:Post')->getPostFromCategory($catid->getId());
			$entities->andWhere('p.id IN (:postId)')
         	->setParameter('postId', $postID);
		}elseif($this->request->get('tagslug')){
			$tagslug = $this->request->get('tagslug');
			$tagid = $em->getRepository('OfficeBrainBlogBundle:Tag')->findOneBy(array('slug' => $tagslug));
			$postID = $em->getRepository('OfficeBrainBlogBundle:Post')->getPostFromTag($tagid->getId());
			$entities->andWhere('p.id IN (:postId)')
         		->setParameter('postId', $postID);
		}else{
		    $entities->orderBy('p.id', 'DESC')
		    ->getQuery()
		    ->getResult();

		}
		$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('siteblog', array('page'=> $page-1)));
		}
		return array(
			'data' => $data,
		);
	}
	/**
	 * Finds and displays a Blog entity.
	 * @Route("/{slug}", name="blog_show")
	 * @Template("OfficeBrainBlogBundle:Blog:show.html.twig")
	 */
	public function showAction($slug)
	{
		$this->initAction();
		$em = $this->getDoctrine()->getManager();
		$entity = $em->getRepository('OfficeBrainBlogBundle:Post')->findOneBy(array('slug' => $slug));
		$onePostRecord = $em->getRepository('OfficeBrainBlogBundle:Post')->find($entity->getId());
		
		$nextpost = $em->getRepository('OfficeBrainBlogBundle:Post')->getNextPost($entity->getId());
		$previouspost = $em->getRepository('OfficeBrainBlogBundle:Post')->getpreviousPost($entity->getId());
		// $commentList = $em->getRepository('OfficeBrainBlogBundle:Comment')->findBy(array('commentStatus' => 1,'commentPostId' => $entity->getId(),'commentIsDeleted' => 0));
		$commentList = $em->getRepository('OfficeBrainBlogBundle:Comment')->getCommentList($entity->getId());
		$tag = $onePostRecord->getPostTagInfo();
		$category = $onePostRecord->getPostCategoryInfo();
		
		$catArr = array();
		$tagArr = array();
		foreach ($tag as $key => $value) {
			if($tag[$key]->getTagId()->getTagStatus() == 1 && $tag[$key]->getTagId()->getTagIsDeleted() == 0)
			{
				$id = $tag[$key]->getTagId()->getslug();
				$tagName = $tag[$key]->getTagId()->getTagName();
				$tagArr[$id] = $tagName;
			}
		}
		foreach ($category as $key => $value) {
			if($category[$key]->getCategoryId()->getCategoryStatus() == 1 && $category[$key]->getCategoryId()->getCategoryIsDeleted() == 0)
			{
				$id	  = $category[$key]->getCategoryId()->getslug();
				$catName = $category[$key]->getCategoryId()->getCategoryName();
				$catArr[$id] = $catName;
			}
		}
		if (!$entity) {
			throw $this->createNotFoundException('Unable to find Post entity.');
		}
		$formcomment = new Comment();
		$this->form = $this->createForm(new CommentType(),$formcomment, array( 'action' => $this->generateUrl('blog_show', array('slug' => $slug))));
		if($this->request->isMethod('POST') && $this->request->isXmlHttpRequest()){
			$this->form->handleRequest($this->request);
			if ($this->form->isValid()) {
				$em = $this->getDoctrine()->getManager();
				$crpfRating = $this->request->get('crfp-rating',1);
				$commentParentId = $this->request->get('commentParentId','');
				$commentRating = (!empty($crpfRating)) ? $this->request->get('crfp-rating',1):'';
				$commentParentId = (!empty($commentParentId)) ? $this->request->get('commentParentId'):'';
				$formcomment->setCommentPostId($entity);
				$formcomment->setCommentRating($commentRating);
				$formcomment->setCommentParentId($commentParentId);
				$formcomment->setcommentStatus(0);
				$formcomment->setcommentIsDeleted(0);
				
				$em->persist($formcomment);
				$em->flush();
				if($this->request->isXmlHttpRequest()) {
					$this->sessionManager->setFlashBagMessage('msg',"Thanks for your comment. It's in moderation.");
					//$this->session->getFlashBag()->add('msg',"Thanks for your comment. It's in moderation.");
					//$response = new Response();
					//$output = array('js_function' => 'goToPage("'.$this->generateUrl('blog_show', array('slug' => $slug)).'")');
					//$this->request->getSession()->getFlashBag()->add('msg',"Thanks for your comment. It's in moderation.");
					//$response->headers->set('Content-Type', 'application/json');
					//$response->setContent(json_encode($output));
					//return $response;
					$this->get('session')->getFlashBag()->set('success_message', $this->translator->trans('blog.success_msg'));
					$this->responseArray['js_function'] ='goToPage("'.$this->generateUrl('blog_show', array('slug' => $slug)).'")';
					return new JsonResponse($this->responseArray);
				}
			}	elseif ($this->request->isXmlHttpRequest()) {
					return new JsonResponse($this->commonLibraryManager->prepareFormJsonError($this->form));
				}
		}
		return array(
			'entity'	  => $onePostRecord,
			'category'	=> $catArr,
			'tag'		 => $tagArr,
			'commentList' => $commentList,
			'form'		=> $this->form->createView(),
			'next'		=> (!empty($nextpost)) ? $nextpost[0] : '',  
			'previous'	=> (!empty($previouspost)) ? $previouspost[0] : '',
		);
	}
	/**
	 * Lists all latest blog entities.
	 *
	 * @Route("/latestblog", name="latestblog")
	 * @Template("OfficeBrainBlogBundle:Blog:latestblog.html.twig")
	 */
	public function latestblogAction()
	{
		$em = $this->getDoctrine()->getManager();
		$latestBlogArry = $em->getRepository('OfficeBrainBlogBundle:Post')->findBy(array('postIsDeleted' => 0,'postStatus' => 1), array('id' => 'DESC'), 6);
		return array(
			'latestBlog'	  => $latestBlogArry,
		);
	}


	/**
	 * Lists all latest blog entities.
	 *
	 * @Route("/recentblogs", name="recentblog")
	 * @Template("OfficeBrainBlogBundle:Blog:recent.html.twig")
	 */
	public function recentblogAction()
	{
		$em = $this->getDoctrine()->getManager();
		$latestBlogArry = $em->getRepository('OfficeBrainBlogBundle:Post')->findBy(array('postIsDeleted' => 0,'postStatus' => 1), array('id' => 'DESC'), 4);
		return array(
			'latestBlog'	  => $latestBlogArry,
			'heading' => 'Recent Blogs' 
		);
	}


	/**
	 * Lists all latest blog entities.
	 *
	 * @Route("/get-blog-tag/{tag_slug}", name="blogByTag")
	 * @Template("OfficeBrainBlogBundle:Blog:recent.html.twig")
	 */
	public function blogByTagAction()
	{
		$this->initAction();
		$em = $this->getDoctrine()->getManager();
		$tagslug = $this->request->get('tag_slug');
		$tagid = $em->getRepository('OfficeBrainBlogBundle:Tag')->findOneBy(array('slug' => $tagslug));
		$postID = $em->getRepository('OfficeBrainBlogBundle:Post')->getPostFromTag($tagid->getId());
		$entities = $em->getRepository('OfficeBrainBlogBundle:Post')
		    ->createQueryBuilder('p')
		    ->where('p.postIsDeleted = :deleted')
		    ->andWhere('p.postStatus = :status')
		    ->setParameter('deleted', 0)
		    ->setParameter('status', 1)
			->andWhere('p.id IN (:postId)')
     		->setParameter('postId', $postID)
		 	->orderBy('p.id', 'DESC')
		    ->getQuery()
		    ->getArrayResult();

		
		return array(
			'latestBlog'=> $entities,
			'heading' => 'Popular Blogs'
		);
	}


	/**
	 * Lists all active blog categories.
	 *
	 * @Route("/active-categories", name="activeblogCategoies")
	 * @Template("OfficeBrainBlogBundle:Blog:activeblogCategoies.html.twig")
	 */
	public function activeblogCategoiesAction()
	{
		$em = $this->getDoctrine()->getManager();
		$category   = $em->getRepository('OfficeBrainBlogBundle:Post')->getCategory();
		return array(
			'categories'	  => $category,
		);
	}


	/**
	 * Lists all active blog tags.
	 *
	 * @Route("/active-tags", name="activeblogTags")
	 * @Template("OfficeBrainBlogBundle:Blog:activeblogTags.html.twig")
	 */
	public function activeblogTagsAction()
	{
		$em = $this->getDoctrine()->getManager();
        $tag        = $em->getRepository('OfficeBrainBlogBundle:Post')->getTag();
		return array(
			'tags'	  => $tag,
		);
	}



	/**
	 * Finds and displays a Blog comment and reply.
	 * @Route("/comment-reply/{id}/", name="blog_show_comnment_reply")
	 * @Template()
	 */
	public function showCommentReplyAction()
	{
		$this->initAction();
		$parent_id=$this->request->get('id');
		$em = $this->getDoctrine()->getManager();	   
		$commentList = $em->getRepository('OfficeBrainBlogBundle:Comment')->getChildCommentList($parent_id);
		return array(
			'commentList' => $commentList
		);
	}
}
