<?php

namespace Blog\AdminBundle\Controller;


use Blog\AdminBundle\Form\BlogFormType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;


class PostController extends Controller
{

    /**
     * @Route("/", name="blogHome")
     * @Template
     */
    public function indexAction()
    {
        $postManager = $this->get('manager.post');
        $posts = $postManager->getAll();

        return array('posts' => $posts);
    }

    /**
     * @Route("/write", name="blogAdd")
     * @Template
     */
    public function addAction(Request $request)
    {
        $postManager = $this->get('manager.post');
        $form = $this->get('form.factory')->create(new BlogFormType(), null, array());

        if($request->getMethod() == 'POST') {
            $form->handleRequest($request);
            if($form->isValid()) {
                try {
                    $postData = $form->getData();
                    $postManager->savePost($form->getData());
                    return new JsonResponse(array(
                        'success' => true,
                        'message' => 'Post saved successfully!'
                    ));
                }
                catch (\Exception $e) {
                    return new JsonResponse(array(
                        'success' => false,
                        'message' => $e->getMessage()
                    ));
                }

            }
            else {
                error_log('form is not valid');
            }
            error_log(json_encode($form->getErrors()));
        }

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



}