<?php

namespace OfficeBrain\Bundle\BlogBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
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\PostCategoryInfo;
use OfficeBrain\Bundle\BlogBundle\Entity\PostTagInfo;
use OfficeBrain\Bundle\BlogBundle\Form\PostType;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Form\FormError;

/**
 * 
 * @Route("/admin/{_locale}/blog")
 */

class BlogAdminController extends Controller
{
    
    
    public function initAction()
    {
        $this->request = $this->getRequest();
        $data=array();
        
        $data['category']=array();
        $data['tag']=array();
        $em = $this->getDoctrine()->getManager();
        $category   = $em->getRepository('OfficeBrainBlogBundle:Post')->getCategory();
        $tag        = $em->getRepository('OfficeBrainBlogBundle:Post')->getTag();
        if(count($category)>0){$data['category']=$category;}
        if(count($tag)>0){$data['tag']=$tag;}
        $this->data =  $data;
    }
    
    
    /**
     * Lists all Tag entities.
     *
     * @Route("/", name="officebrain_blog_blogadmin_index")
     * requirements={"records_per_page"="12|24|48|96|996","page"="\d+"},
     * defaults={"records_per_page"=2,"page"=1}),
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $this->initAction();
        $em = $this->getDoctrine()->getManager();
        $data = array();
         $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', 10);
        $start_index    = (($page - 1) * $recordsPerPage - 1);
        
        $search = array('postIsDeleted' => 0 );
        if($option!="" && $keywords!=""){
            if($option=="postStatus"){
                if($keywords=="Draft"){
                    $search[$option] = 0 ;
                }
                if($keywords=="Published"){
                    $search[$option] = 1 ;
                }
                if($keywords=="UnPublished"){
                    $search[$option] = 2 ;
                }
                
            }else{
                $search[$option] = $keywords;
            }
        }

        $entities = $em->getRepository('OfficeBrainBlogBundle:Post')->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_blogadmin_index', array('page'=> $page-1)));
            
        }
        //$timeZone = $this->getTimezoneByIp();   //America/New_York
        return array(
            'data' => $data,
             'option'=>$option,
            'keywords'=>$keywords,
            'page'=>$page
        );
    }
    
     /**
     * Creates a new Blog entity.
     *
     * @Route("/new", name="officebrain_blog_blogadmin_create")
     * @Template("OfficeBrainBlogBundle:BlogAdmin:new.html.twig")
     */
    public function createAction(Request $request)
    {
    	$this->initAction();
        $em = $this->getDoctrine()->getManager();
        $entity = new Post();
        $catArr = array();
        $tagArr = array();
        $catArr[0] = 1;
        
        $form = $this->createForm(new PostType($this->data,$catArr, $tagArr), $entity, array(
            'action' => $this->generateUrl('officebrain_blog_blogadmin_create'),
            'method' => 'POST',
        ));
        
        $form->handleRequest($request);
        
        if ($request->isMethod('POST')) {
            $imageError = null;
            $file = $form['featureImage']->getData();
            $allowedMimeTypes = [
                    'image/jpeg',
                    'image/png',
                    'image/gif',
                    'image/webp',
            ];
            $imageError = $this->validateImage($file,$allowedMimeTypes);
            // Add error to featureImage field
            if ($imageError!=NULL) {
                $form->get('featureImage')->addError(
                    new FormError($imageError)
                );
            }
        }

        if ($form->isValid()) {

            $file = $form['featureImage']->getData();
            if ($file) {
                $uploadDir = $this->getParameter('base_path').'/uploads/';
                $filename = uniqid().'.'.$file->guessExtension();
                $file->move($uploadDir, $filename);
                $entity->setFeatureImage($filename);
            }
            $em->persist($entity);
            $entity->setPostIsDeleted(0);
            $timeZone= 'America/Los_Angeles'; //$this->request->get('timezone');
            $date = new \DateTime($form['publishedDate']->getData()->format('Y-m-d H:i:s'), new \DateTimeZone($timeZone));
            $date->setTimezone(new \DateTimeZone('UTC'));
           // echo $date->format('Y-m-d H:i:s'); 
            $entity->setPublishedDate($date);
            $em->flush();
            
            $lastInsertedId =   $entity->getId();
            $form=$request->request->get('post');
            
            $catId  =   isset($form['postCategoryId']['postCategoryId'])?$form['postCategoryId']['postCategoryId']:'';
            $tagId  =   isset($form['postTagId']['postTagId'])?$form['postTagId']['postTagId']:'';
            
            if($catId)
            {
                foreach ($catId as $key => $value)
                {
                    $catObj = $em->getRepository('OfficeBrainBlogBundle:Category')->findOneBy(array('id' => $value));
                    // var_dump(is_object($entity)); die;
                    $postcategory = new PostCategoryInfo();
                    $postcategory->setCategoryId($catObj);
                    $postcategory->setPostId($entity);
                    $em->persist($postcategory);
                }
            }
           
           
           if($tagId)
           {
               foreach ($tagId as $key => $value)
               {
                   $tagObj = $em->getRepository('OfficeBrainBlogBundle:Tag')->findOneBy(array('id' => $value));
                   $posttag = new PostTagInfo();
                   $posttag->setTagId($tagObj);
                   $posttag->setPostId($entity);
                   $em->persist($posttag);
                   
               }
               // $em->flush();            
           }
           
            $em->flush();
            return $this->redirect($this->generateUrl('officebrain_blog_blogadmin_index'));
        }
        
        return array(
            'entity' => $entity,
            'form'   => $form->createView(),

        );
    }

    private function validateImage($file,$allowedMimeTypes){
        $imageError =null;
        if (isset($file)) {
            // File size in bytes
            $maxSize= 2 * 1024 * 1024;
            $fileSize = $file->getSize();
            if($fileSize>$maxSize || $fileSize<=0){
                $mb = ini_get("upload_max_filesize");
                $imageError = 'File size exceed more than '.$mb;
                return $imageError;
            }
            
            // File size in MB
            $fileSizeMB = round($fileSize / 1024 / 1024, 2);

            $originalName = $file->getClientOriginalName();

            // File extension
            $extension = $file->guessExtension();

            // MIME / Content Type detected by Symfony
            $mimeType = $file->getMimeType();

            // Browser-provided content type (less reliable)
            $clientMimeType = $file->getClientMimeType();

            if (!in_array($mimeType, $allowedMimeTypes)) {
                $imageError = 'Uploaded file format not allowed.';
                return $imageError;
            }
        }
        return $imageError;
    }

    /*private function getTimezoneByIp(){
        $ip = $_SERVER['REMOTE_ADDR'];
        $response = file_get_contents("http://ip-api.com/json/{$ip}");
        $data = json_decode($response, true);
        $timezone = isset($data['timezone']) ? $data['timezone'] : 'UTC';
        return $timezone;
    }*/
    /**
     * Edits an existing Category entity.
     *
     * @Route("/edit/{id}", name="officebrain_blog_blogadmin_update")
     * @Template("OfficeBrainBlogBundle:BlogAdmin:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
    	$this->initAction();
        $em = $this->getDoctrine()->getManager();
        $postid =   $id;
            
        $entity = $em->getRepository('OfficeBrainBlogBundle:Post')->find($id);
        /*if($entity->getPublishedDate()!=NULL){
            $entity->setPublishedDate(new \DateTime($entity->getPublishedDate()->format('Y-m-d H:i:s')));
        }*/
        $tag = $entity->getPostTagInfo();
        $category = $entity->getPostCategoryInfo();
        
        $catArr = array();
        $tagArr = array();
        
        foreach ($tag as $key => $value) {
        	$tagArr[$key] = $tag[$key]->getTagId()->getId();
        }
        foreach ($category as $key => $value) {
        	$catArr[$key] = $category[$key]->getCategoryId()->getId();
        }
        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Blog entity.');
        }
        
        $editForm = $this->createForm(new PostType($this->data, $catArr, $tagArr), $entity);
        $editForm->handleRequest($request);

       
        if ($request->isMethod('POST')) {
            $imageError = null;
            $file = $editForm['featureImage']->getData();
            $allowedMimeTypes = [
                    'image/jpeg',
                    'image/png',
                    'image/gif',
                    'image/webp',
            ];
            $imageError = $this->validateImage($file,$allowedMimeTypes);
            // Add error to featureImage field
            if ($imageError!=NULL) {
                $editForm->get('featureImage')->addError(
                    new FormError($imageError)
                );
            }
        }
        if ($editForm->isValid()) {
            $previousFile= $this->request->get('previous_image');
            //$file = $editForm['featureImage']->getData();
            if (isset($file)) {
                $uploadDir = $this->getParameter('base_path').'/uploads/';
                $filename = uniqid().'.'.$file->guessExtension();
                $file->move($uploadDir, $filename);
                $entity->setFeatureImage($filename);
                

            }else{
                $entity->setFeatureImage($previousFile);
            }
            
            $timeZone= 'America/Los_Angeles'; //$this->request->get('timezone');
            $date = new \DateTime($editForm['publishedDate']->getData()->format('Y-m-d H:i:s'), new \DateTimeZone($timeZone));
            $date->setTimezone(new \DateTimeZone('UTC'));
           // echo $date->format('Y-m-d H:i:s'); 
            $entity->setPublishedDate($date);
            $postStatus=  $editForm['postStatus']->getData(); 
			$entity->setPostStatus($postStatus);
            $em->persist($entity);
            $em->flush();
            
            $lastInsertedId =   $postid;
            
            $catId  =   $_POST['post']['postCategoryId']['postCategoryId'];
            if($catId)
            {
                $categories = $em->getRepository('OfficeBrainBlogBundle:PostCategoryInfo')->findBy(['postId' => $lastInsertedId]);
                foreach ($categories as $cat) {
                    $em->remove($cat);
                }
                $em->flush();

                foreach ($catId as $key => $value)
                {
                    $catObj = $em->getRepository('OfficeBrainBlogBundle:Category')->findOneBy(array('id' => $value));
                    $postcategory = new PostCategoryInfo();
                    $postcategory->setCategoryId($catObj);
                    $postcategory->setPostId($entity);
                    $em->persist($postcategory);
                }
                $em->flush();            
            }
            
            $tagId  =   $_POST['post']['postTagId']['postTagId'];
            if($tagId)
            {
                $tagsInfos = $em->getRepository('OfficeBrainBlogBundle:PostTagInfo')->findBy(['postId' => $lastInsertedId]);
                foreach ($tagsInfos as $tgs) {
                    $em->remove($tgs);
                }
                $em->flush();

                foreach ($tagId as $key => $value)
                {
                    $tagObj = $em->getRepository('OfficeBrainBlogBundle:Tag')->findOneBy(array('id' => $value));  
                    $posttag = new PostTagInfo();
                    $posttag->setTagId($tagObj);
                    $posttag->setPostId($entity);
                    $em->persist($posttag);
                }
                $em->flush();            
            }
            
            return $this->redirect($this->generateUrl('officebrain_blog_blogadmin_index'));

        }

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

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

        $entity->setPostIsDeleted(true);
        $em->persist($entity);
        $em->flush();   
        
        return $this->redirect($this->generateUrl('officebrain_blog_blogadmin_index'));
    }
    
    
    /**
     * Lists all Comments on all post.
     *
     * @Route("/comment/{id}", name="officebrain_blog_blogadmin_commentlist")
     * requirements={"records_per_page"="12|24|48|96|996","page"="\d+"},
     * defaults={"records_per_page"=12,"page"=1}),
     * @Method("GET")
     * @Template("OfficeBrainBlogBundle:Comment:index.html.twig")
     */
    public function commentListAction($id = null)
    {
        $this->initAction();
        $em = $this->getDoctrine()->getManager();
        $data = array();
        
        $page           = $this->request->get('page', '1');
        $recordsPerPage = $this->request->get('recordsPerPage', 12);
        $start_index    = (($page - 1) * $recordsPerPage - 1);
        
        $entities = $em->getRepository('OfficeBrainBlogBundle:Comment')->getCommentListAdmin($id);
        
        $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_blogadmin_commentlist', array('page'=> $page-1)));
            
        }
        
        return array(
            'data' => $data,
        );
    }
    /**
     * Deletes a Comment entity.
     *
     * @Route("/delete/comment/{id}", name="officebrain_blog_blogadmin_deletecomment")
     */
    public function deleteCommentAction($id)
    {
       
        $em = $this->getDoctrine()->getManager();
        $entity = $em->getRepository('OfficeBrainBlogBundle:Comment')->find($id);

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

        $entity->setCommentIsDeleted(true);
        $em->persist($entity);
        $em->flush();   
        
        return $this->redirect($this->generateUrl('officebrain_blog_blogadmin_commentlist',array('id'=>$entity->getCommentPostId()->getId())));
    }
    /**
     * Deletes a Blog entity.
     *
     * @Route("/edit-comment/{action}/{id}", name="officebrain_blog_blogadmin_editcomment")
     */
    public function editCommentAction($action,$id)
    {
        
        $em = $this->getDoctrine()->getManager();
        $entity = $em->getRepository('OfficeBrainBlogBundle:Comment')->find($id);
        
        
        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Comment entity.');
        }
        if($action == 'Active')
        {
            $entity->setCommentStatus(false);
                        
        }else{
            
            $entity->setCommentStatus(true);
            
        }
                
        $em->persist($entity);
        $em->flush();   
        
        return $this->redirect($this->generateUrl('officebrain_blog_blogadmin_commentlist',array('id'=>$entity->getCommentPostId()->getId())));
    }
    
}
