<?php

namespace Neag\MainBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use JMS\SecurityExtraBundle\Annotation\Secure;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;

/**
 * @Route("/")
 */
class SecuredController extends ControllerAbstract
{
    /**
     * @Route("/login", name="login")
     * @Template("NeagMainBundle:Secured:login.html.twig")
     */
    public function loginAction()
    {
        if ($this->get('request')->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
            $error = $this->get('request')->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
        } else {
            $error = $this->get('request')->getSession()->get(SecurityContext::AUTHENTICATION_ERROR);
        }

        return array(
            'last_username' => $this->get('request')->getSession()->get(SecurityContext::LAST_USERNAME),
            'error'         => $error,
        );
    }

    /**
     * @Route("/admin/login_check", name="login_check")
     */
    public function securityCheckAction()
    {
        // The security layer will intercept this request
        //return $this->redirect($this->generateUrl('main'));
    }

    /**
     * @Route("/logout", name="logout")
     * @Template("NeagMainBundle:Secured:logout.html.twig")
     */
    public function logoutAction()
    {
        // The security layer will intercept this request
        /*
        $response = new Response(
            $this->render(
                'NeagMainBundle:Secured:logout.html.twig'
            )
        );
        */
        $response = new RedirectResponse($this->generateUrl('main'));
        $response->headers->setCookie(new Cookie('PHPSESSID', ''));
        return $response;
        //return $this->redirect($this->generateUrl('main'));
    }
    
    /**
     * @Route("/vk_logout", name="vk_logout")
     */
    public function vkLogoutAction()    
    {
        $globals = $this->get('globals');
        $request = $this->get('request');
        $redirect = $request->get('redirect');
        $session = $globals->getSession();
        $session->set('vk', null); 
        return $this->redirect($redirect);
    }   

}
