<?php

namespace Neag\MainBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Neag\MainBundle\Entity\User;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Form\FormError;

class AdminUserController extends ControllerAbstract
{
    /**
     * @Route("/admin/user/edit/{id}")
     * @Template("NeagMainBundle:AdminUser:edit.html.twig")
     */
    public function editAction($id)
    {
        $this->sessionStart();
        
        $request = $this->getRequest();             
        
        $DB = $this->get('database_connection');       
        
        $edit = false;
        if (!empty($id)) {
            $user = $this->getDoctrine()
            ->getRepository('NeagMainBundle:User')
            ->find($id);
            if (!empty($user)) {
                $edit = true; 
            } else {
                return $this->redirect($this->generateURL('admin_user_list'));
            }
        }        

        if (empty($user)) {
            $user = new User();
            $user->setActive(1); 
        }
        
        $email_confirmed = true;
        if ($user->getEmailConfirmToken() != null) {
            $email_confirmed = false;
        }

        $form = $this->createFormBuilder($user)
        ->add('name', 'text', Array('label' => 'Имя пользователя'))
        ->add('email', 'text', Array('label' => 'E-mail', 'required' => false))
        ->add('email_confirmed', 'choice', 
            Array(
                'choices' => array(1 => 'Да', 0 => 'Нет'), 
                'label' => 'E-mail подтверждён',
                'mapped' => false,
                'data' => $email_confirmed ? 1 : 0,
            )
        )
        ->add('description', 'textarea', Array('label' => 'Информация о себе', 'required' => false))
        ->add('contacts', 'textarea', Array('label' => 'Контакты', 'required' => false))
        ->add('blogger', 'choice', Array('choices' => array(1 => 'Да', 0 => 'Нет'), 'label' => 'Блогер'))
        ->add('blogger_alias', 'text', Array('label' => 'Имя блога', 'required' => false, 'help' => 'Допустимы только символы латиницы, цифры, знаки тире и подчёркивания.'))
        ->add('premoderationComments', 'choice', Array('choices' => array(1 => 'Да', 0 => 'Нет'), 'label' => 'Премодерация комментариев'))
        ->add('active', 'choice', Array('choices' => array(1 => 'Да', 0 => 'Нет'), 'label' => 'Активный'))        
        ->getForm();
            
        if ($request->isMethod('POST')) {
            $submitted_values = $_POST[$form->getName()]; 
            if (empty($submitted_values['description'])) {
                $user->setDescription('');
            }
            if (empty($submitted_values['contacts'])) {
                $user->setContacts('');
            }
            $form->bind($request);
            if ($form->isValid()) {
                // perform some action, such as saving the task to the database
                if (isset($submitted_values['email_confirmed'])) {
                    if ($submitted_values['email_confirmed']) {
                        $user->setEmailConfirmToken(null);
                    } else {
                        $user->setEmailConfirmToken(rand(10000, 99999).rand(10000, 99999));
                    }
                }
                $em = $this->getDoctrine()->getManager();                
                $em->persist($user);
                $em->flush();
                $this->clearCache();
                if ($edit) {
                    $this->message('Изменения внесены', 'ok');
                } else {
                    $this->message('Добавлена новая персоналия', 'ok');
                }
                $params = Array();
                return $this->redirect($this->generateUrl('admin_user_list', $params));
            }
        }
        
        $action_params = Array();
        if (!empty($id)) {
            $action_params['id'] = $id;
        }
        $action_link = $this->generateUrl('admin_user_edit', $action_params);    

        return array(
            'action' => $action_link,
            'form' => $form->createView(),
            'edit' => $edit,
        );
    }
    
    /**
     * @Route("/admin/user/info/{id}")
     * @Template("NeagMainBundle:AdminUser:info.html.twig")
     */
    public function infoAction($id = null)
    {       
        $request = $this->getRequest();       
        $DB = $this->get('database_connection');
        $globals = $this->get('globals');
        $edit = false;
        if (!empty($id)) {
            $user = $this->getDoctrine()
            ->getRepository('NeagMainBundle:User')
            ->find($id);
            $edit = true; 
        }
        if (empty($user)) {
            return $this->redirect($this->generateURL('admin_user_list'));
        }
        $type = $user->getType();
        $type_text = '';
        if ($type == 'natural_person') {
            $type_text = 'Физ. лицо';
        }
        if ($type == 'legal_entity') {
            $type_text = 'Юр. лицо';
        }
        if ($type == 'legal_entity_client') {
            $type_text = 'Юр. лицо, клиент компании';
        }
        $info = Array();
        $info[] = Array(
            'label' => 'Тип',
            'value' => $type_text,
        );
        $info[] = Array(
            'label' => 'Ф. И. О.',
            'value' => htmlspecialchars($user->getFio()),
        );
        $info[] = Array(
            'label' => 'E-mail',
            'value' => $user->getEmail(),
        );
        $info[] = Array(
            'label' => 'Дата рождения',
            'value' => !is_null($user->getBirthday()) ? $user->getBirthday()->format('d.m.Y') : null,
        );
        $info[] = Array(
            'label' => 'Адрес',
            'value' => nl2br(htmlspecialchars($user->getAddress())),
        );
        $info[] = Array(
            'label' => 'Телефон',
            'value' => htmlspecialchars($user->getPhone()),
        );
        $info[] = Array(
            'label' => 'Название организации',
            'value' => nl2br(htmlspecialchars($user->getCompanyName())),
        );
        $info[] = Array(
            'label' => 'ИНН организации',
            'value' => nl2br(htmlspecialchars($user->getCompanyInn())),
        );
        $info[] = Array(
            'label' => 'КПП организации',
            'value' => nl2br(htmlspecialchars($user->getCompanyKpp())),
        );
        $info[] = Array(
            'label' => 'Адрес организации',
            'value' => nl2br(htmlspecialchars($user->getCompanyAddress())),
        );
        $info[] = Array(
            'label' => 'Расчётный счёт',
            'value' => nl2br(htmlspecialchars($user->getBankAccount())),
        );
        $info[] = Array(
            'label' => 'Корр. счёт',
            'value' => nl2br(htmlspecialchars($user->getCorrespondentAccount())),
        );
        $info[] = Array(
            'label' => 'БИК',
            'value' => nl2br(htmlspecialchars($user->getBik())),
        );
        $info[] = Array(
            'label' => 'E-mail уведомление о готовности заказа',
            'value' => $user->getOrderReadyEmailNotification() ? 'да' : 'нет',
        ); 
        $info[] = Array(
            'label' => 'IP',
            'value' => $user->getIp(),
        );
        $info[] = Array(
            'label' => 'Cookie-идентификатор',
            'value' => $user->getCookieId(),
        );
        $info[] = Array(
            'label' => 'Время последнего захода',
            'value' => !is_null($user->getTimeVisit()) ? $user->getTimeVisit()->format('d.m.Y H:i:s') : null,
        );
        $info[] = Array(
            'label' => 'Время последней авторизации',
            'value' => !is_null($user->getTimeLogin()) ? $user->getTimeLogin()->format('d.m.Y H:i:s') : null,
        );
        $info[] = Array(
            'label' => 'Время регистрации',
            'value' => !is_null($user->getTimeRegistration()) ? $user->getTimeRegistration()->format('d.m.Y H:i:s') : null,
        ); 
        $info[] = Array(
            'label' => 'Активный',
            'value' => $user->getActive() ? 'да' : 'нет', 
        );       
        $params = Array(            
            'email' => $user->getEmail(),
            'info' => $info,
        );
        return $params;
    }    

    /**
     * @Route("admin/user")
     * @Template("NeagMainBundle:AdminUser:list.html.twig")
     */
    public function listAction($parent_id = null)
    {       
        $this->sessionStart();
        
        $request = $this->getRequest();
        
        $globals = $this->get('globals');
                
        $del = $this->getRequest()->query->get('del'); 
        
        $DB = $this->get('database_connection'); 
        
        $session = $globals->getSession();  
        
        if (!empty($del)) {
            $user = $this->getDoctrine()
            ->getRepository('NeagMainBundle:User')
            ->find($del);
            if (!empty($user)) {
                $em = $this->getDoctrine()->getManager();                
                $em->remove($user);
                $em->flush();
                $this->clearCache();
                $this->message('Пользователь успешно удалён', 'ok');
            }
        }
        
        $blogger = 'any';
        $type = 'any';
        $premoderationComments = 'any';
        $active = 'any';
        
        // Сброс фильтра
        $action = $request->query->get('action', null);
        if ($action == 'reset') {
            $session->set('admin_user_filter', null);
            return $this->redirect($this->generateUrl('admin_user_list', Array()));
        }
        
        // Обработка фильтра
        if ($request->isMethod('POST')) {
            $submitted_values = $_POST['form'];            
            $admin_user_filter = Array();
            //$this->message(print_r($submitted_values, true), 'ok');
            if (!empty($submitted_values['active']) && !empty($submitted_values['type'])) {
                if (!empty($submitted_values['premoderation_comments'])) {
                    if ($submitted_values['premoderation_comments'] == 'yes') {
                        $admin_user_filter['premoderation_comments'] = 'yes';
                    }
                    if ($submitted_values['premoderation_comments'] == 'no') {
                        $admin_user_filter['premoderation_comments'] = 'no';
                    }
                }
                if (!empty($submitted_values['blogger'])) {
                    if ($submitted_values['blogger'] == 'yes') {
                        $admin_user_filter['blogger'] = 'yes';
                    }
                    if ($submitted_values['blogger'] == 'no') {
                        $admin_user_filter['blogger'] = 'no';
                    }
                }
                if (!empty($submitted_values['active'])) {
                    if ($submitted_values['active'] == 'yes') {
                        $admin_user_filter['active'] = 'yes';
                    }
                    if ($submitted_values['active'] == 'no') {
                        $admin_user_filter['active'] = 'no';
                    }
                }
                if (!empty($submitted_values['type'])) {
                    //$this->message('chp 1', 'ok');
                    if (in_array($submitted_values['type'], Array('inner', 'vk', 'fb'))) {
                        //$this->message('chp 2', 'ok');
                        $admin_user_filter['type'] = $submitted_values['type'];
                    }
                }
                $session->set('admin_user_filter', $admin_user_filter);
                return $this->redirect($this->generateUrl('admin_user_list', Array()));
            }
        } else {
            $admin_user_filter = $session->get('admin_user_filter');
            if (!empty($admin_user_filter)) {
                if (!empty($admin_user_filter['type'])) {                    
                    $type = $admin_user_filter['type'];
                } 
                if (!empty($admin_user_filter['premoderation_comments'])) {
                    $premoderationComments = $admin_user_filter['premoderation_comments'];
                } 
                if (!empty($admin_user_filter['blogger'])) {
                    $blogger = $admin_user_filter['blogger'];
                }
                if (!empty($admin_user_filter['active'])) {
                    $active = $admin_user_filter['active'];
                } 
            }
        }          
        
        // Filter
        $fb = $this->createFormBuilder();        
        $fb->add('type', 'choice',      
            Array(
                'label' => 'Тип', 
                'choices' => Array(
                    'any' => '-- Без разницы --',
                    'inner' => 'Обычный',
                    'vk' => 'ВКонтакте',
                    'fb' => 'Facebook',
                ),
                'required' => true,
                'data' => $type, 
            )
        );
        $fb->add('premoderation_comments', 'choice',      
            Array(
                'label' => 'Премодерация', 
                'choices' => Array(
                    'any' => '-- Без разницы --',
                    'yes' => 'Да',
                    'no' => 'Нет',
                ),
                'required' => true,
                'data' => $premoderationComments, 
            )
        );
        $fb->add('blogger', 'choice',      
            Array(
                'label' => 'Блогер', 
                'choices' => Array(
                    'any' => '-- Без разницы --',
                    'yes' => 'Да',
                    'no' => 'Нет',
                ),
                'required' => true,
                'data' => $blogger, 
            )
        );  
        $fb->add('active', 'choice',      
            Array(
                'label' => 'Активный', 
                'choices' => Array(
                    'any' => '-- Без разницы --',
                    'yes' => 'Да',
                    'no' => 'Нет',
                ),
                'required' => true,
                'data' => $active, 
            )
        );       

        $filter_form = $fb->getForm();
        
        $sort_by = 'id'; 
        $sort_direction = 'desc';
        
        // Сброс сортировки 
        $action = $request->query->get('action', null);
        if ($action == 'sort_reset') {
            $session->set('admin_user_sort_by', null);
            $session->set('admin_user_sort_direction', null);
            return $this->redirect($this->generateUrl('admin_user_list', Array()));
        }      
        
        //$this->message('chp 0');
        //$this->message($request->getMethod());
        if ($request->isMethod('POST')) { 
            $submitted_values = $_POST['form'];            
            if (!empty($submitted_values['sort_by']) && !empty($submitted_values['sort_direction'])) {
                // Обработка сортировки
                //$this->message('chp 1');
                if (!empty($submitted_values['sort_by'])) { 
                    $sort_by = $submitted_values['sort_by'];
                    //$this->message('chp 2 '.$sort_by);
                }
                if (!empty($submitted_values['sort_direction'])) { 
                    $sort_direction = $submitted_values['sort_direction'];
                    //$this->message('chp 3');
                }
                $session->set('admin_user_sort_by', $sort_by);
                $session->set('admin_user_sort_direction', $sort_direction);
                return $this->redirect($this->generateUrl('admin_user_list', Array()));
            }
        } else {
            $admin_user_sort_by = $session->get('admin_user_sort_by');
            $admin_user_sort_direction = $session->get('admin_user_sort_direction');
            if (!empty($admin_user_sort_by)) {
                $sort_by = $admin_user_sort_by;
            }
            if (!empty($admin_user_sort_direction)) {
                if (in_array($admin_user_sort_direction, Array('asc', 'desc'))) {
                    $sort_direction = $admin_user_sort_direction;
                }
            }
        }  
        
        // Sort form
        $fb = $this->createFormBuilder();
        $fb->add('sort_by', 'choice',       
            Array(
                'label' => 'Сортировать по', 
                'choices' => Array('id' => 'ID', 'name' => 'Имя', 'email' => 'E-mail'),
                'required' => true,
                'data' => $sort_by,
            )
        );
        $fb->add('sort_direction', 'choice',       
            Array(
                'label' => 'Направление', 
                'choices' => Array('desc' => 'По-убыванию', 'asc' => 'По-возрастанию'),
                'required' => true,
                'data' => $sort_direction,
            )
        );   
        $sort_form = $fb->getForm(); 
        
        // Pager
        $pager = $this->get('punk_ave.pager_factory')->createPager("DoctrineORM");
        $request = $this->getRequest();
        $pager->bindRequest($request);
        $currentPage = ($request->query->has('page'))? $request->query->get('page') : 1;
        $pager->setCurrentPage($currentPage);
        $pager->setMaxPerPage(20);
        $pager->setRoute($this->getRequest()->get('_route'), Array());
        // query
        $qb = $this->getDoctrine()->getManager()->createQueryBuilder()
        ->select(Array('u'))
        ->from('NeagMainBundle:User', 'u');
        if ($type !== 'any') {
            if ($type == 'inner') {
                $qb->andWhere('u.vkId IS NULL AND u.fbId IS NULL');
            }
            if ($type == 'vk') {
                $qb->andWhere('u.vkId IS NOT NULL');
            }
            if ($type == 'fb') {
                $qb->andWhere('u.fbId IS NOT NULL');
            }
        }
        if ($premoderationComments !== 'any') {
            $qb->andWhere('u.premoderationComments = :premoderationComments')
            ->setParameter('premoderationComments', $premoderationComments == 'yes');
        }
        if ($blogger !== 'any') {
            $qb->andWhere('u.blogger = :blogger')
            ->setParameter('blogger', $blogger == 'yes');
        }   
        if ($active !== 'any') {
            $qb->andWhere('u.active = :active')
            ->setParameter('active', $active == 'yes');
        } 
        $qb->orderBy('u.'.$sort_by, $sort_direction);
        // bind
        $pager->setQueryBuilder($qb);
        $rows = $pager->getResults();
        $data = Array();
        foreach ($rows as $row) {
            /*
            $type = $row->getType();
            $type_text = '';
            if ($type == 'natural_person') {
                $type_text = 'Физ. лицо';
            }
            if ($type == 'legal_entity') {
                $type_text = 'Юр. лицо';
            }
            if ($type == 'legal_entity_client') {
                $type_text = 'Юр. лицо, клиент компании';
            }
            */
            //$this->trace('type: '.$type);
            //$this->trace($type_text);
            $email = $row->getEmail();
            $data[] = Array(
                'id' => $row->getId(),
                'name' => $globals->formatUserName($row->getName(), $row),                
                //'company_name' => $row->getCompanyName(),
                'email' => $email, 
                //'birthday' => $row->getBirthday(),
                //'phone' => $row->getPhone(),
                //'type' => $type_text,
                //'orders_count' => $orders_count,
                //'orders_link' => $this->generateURL('admin_order_list', Array('user_id' => $row->getId())),
                'blogger' => $row->getBlogger() ? 'да' : 'нет',
                'blogger_alias' => $row->getBloggerAlias(),
                'ip' => $row->getIp(),
                'cookie_id' => $row->getCookieId(),
                'email_confirmed' => !empty($email) ? (($row->getEmailConfirmToken() == null) ? 'да' : 'нет') : '',
                'premoderation_comments' => $row->getPremoderationComments() ? 'да' : 'нет',
                'active' => $row->getActive() ? 'да' : 'нет', 
                'delete_link' => $this->generateUrl('admin_user_list', array('del' => $row->getId())),
                'edit_link' => $this->generateUrl('admin_user_edit', array('id' => $row->getId())), 
                'info_link' => $this->generateUrl('user_info', array('id' => $row->getId())),
            );
        }
        $params = Array();
        //$add_link = $this->generateUrl('admin_user_edit', $params); 
        return Array(
            'sort_form_action' => $this->generateURL('admin_user_list'),
            'sort_form_reset_link' => $this->generateURL('admin_user_list', Array('action' => 'sort_reset')),
            'sort_form' => $sort_form->createView(),
            'filter_form_action' => $this->generateURL('admin_user_list'),
            'filter_form_reset_link' => $this->generateURL('admin_user_list', Array('action' => 'reset')),
            'filter_form' => $filter_form->createView(),
            'data' => $data, 
            //'add_link' => $add_link, 
            //'rearrange_action' => $rearrange_action
            'pager' => $this->renderPager($pager), 
        );
    }
    
    /**
     * @Route("admin/user_blogger_demand")
     * @Template("NeagMainBundle:AdminUser:blogger_demand_list.html.twig")
     */
    public function bloggerDemandListAction($parent_id = null)
    {       
        $this->sessionStart();
        
        $request = $this->getRequest();
        
        $globals = $this->get('globals');
                
        $del = $this->getRequest()->query->get('del'); 
        
        $DB = $this->get('database_connection'); 
        
        $session = $globals->getSession();          

        // query
        $qb = $this->getDoctrine()->getManager()->createQueryBuilder()
        ->select(Array('u'))
        ->from('NeagMainBundle:User', 'u');
        $qb->andWhere('u.bloggerDemand = :bloggerDemand')
        ->setParameter('bloggerDemand', true);
        $qb->orderBy('u.id', 'desc');        
        $rows = $qb->getQuery()->getResult();
        $data = Array();
        foreach ($rows as $row) {
            $email = $row->getEmail();
            $data[] = Array(
                'id' => $row->getId(),
                'name' => $globals->formatUserName($row->getName(), $row),
                'name_raw' => stripslashes($row->getName()),                
                'blogger_alias' => $row->getBloggerAlias(),
                'email' => $row->getEmail(),
                'message' => nl2br(htmlspecialchars($row->getBloggerDemandMessage())), 
                'accept_link' => $this->generateUrl('admin_user_blogger_demand_accept', array('id' => $row->getId())),
                'deny_link' => $this->generateUrl('admin_user_blogger_demand_deny', array('id' => $row->getId())),
            );
        }
        $params = Array();
        //$add_link = $this->generateUrl('admin_user_edit', $params); 
        return Array(
            'data' => $data, 
        );
    }
    
    /**
     * @Route("/admin/user_blogger_demand_accept/{id}")
     * @Template("NeagMainBundle:AdminUser:blogger_demand_accept.html.twig")
     */
    public function bloggerDemandAcceptAction($id)
    {
        $this->sessionStart();
        
        $request = $this->getRequest();             
        
        $DB = $this->get('database_connection');       
        
        $globals = $this->get('globals');
        
        $user = null;
        if (!empty($id)) {
            $user = $this->getDoctrine()
            ->getRepository('NeagMainBundle:User')
            ->find($id);            
        }        
        if (empty($user)) {
            return $this->redirect($this->generateURL('admin_user_blogger_demand_list'));
        }
        
        $message = 'Здравствуйте, '.$user->getName().'! Ваша заявка на создание блога принята. Вы можете начинать работу в личном кабинете: ';
        $message .= $this->generateURL('user', Array(), true);

        $form = $this->createFormBuilder()
        ->add('title', 'text', Array('label' => 'Заголовок письма', 'data' => 'Ваша заявка принята'))
        ->add('message', 'textarea', Array('label' => 'Текст сообщения', 'data' => $message, 'required' => false))    
        ->getForm();
            
        if ($request->isMethod('POST')) {
            $submitted_values = $_POST[$form->getName()]; 
            if (empty($submitted_values['title'])) {
                $form->get('title')->addError(new FormError('Не указан заголовок письма'));
            }
            if (empty($submitted_values['message'])) {
                $form->get('message')->addError(new FormError('Не указан текст сообщения'));
            }
            $form->bind($request);
            if ($form->isValid()) {
                // Отправка письма
                $email = $user->getEmail();
                $globals->mail($email, $submitted_values['title'], $submitted_values['message']);
                $user->setBlogger(true);
                $user->setBloggerDemand(false);
                $user->setBloggerDemandMessage('');
                // perform some action, such as saving the task to the database
                $em = $this->getDoctrine()->getManager();                
                $em->persist($user);
                $em->flush();
                $this->clearCache();
                $this->message('Заявка пользователя "'.$user->getName().'" принята.', 'ok');
                $params = Array();
                return $this->redirect($this->generateUrl('admin_user_blogger_demand_list', $params));
            }
        }
        
        $action_params = Array();
        if (!empty($id)) {
            $action_params['id'] = $id;
        }
        $action_link = $this->generateUrl('admin_user_blogger_demand_accept', $action_params);    

        return array(
            'action' => $action_link,
            'form' => $form->createView(),
            'back_link' => $this->generateURL('admin_user_blogger_demand_list'),
        );
    }
    
    /**
     * @Route("/admin/user_blogger_demand_deny/{id}")
     * @Template("NeagMainBundle:AdminUser:blogger_demand_deny.html.twig")
     */
    public function bloggerDemandDenyAction($id)
    {
        $this->sessionStart();
        
        $request = $this->getRequest();             
        
        $DB = $this->get('database_connection');       
        
        $globals = $this->get('globals');
        
        $user = null;
        if (!empty($id)) {
            $user = $this->getDoctrine()
            ->getRepository('NeagMainBundle:User')
            ->find($id);            
        }        
        if (empty($user)) {
            return $this->redirect($this->generateURL('admin_user_blogger_demand_list'));
        }
        
        $message = 'Здравствуйте, '.$user->getName().'! Ваша заявка на создание блога отклонена.';

        $form = $this->createFormBuilder()
        ->add('title', 'text', Array('label' => 'Заголовок письма', 'data' => 'Ваша заявка отклонена'))
        ->add('message', 'textarea', Array('label' => 'Текст сообщения', 'data' => $message, 'required' => false))    
        ->getForm();
            
        if ($request->isMethod('POST')) {
            $submitted_values = $_POST[$form->getName()]; 
            if (empty($submitted_values['title'])) {
                $form->get('title')->addError(new FormError('Не указан заголовок письма'));
            }
            if (empty($submitted_values['message'])) {
                $form->get('message')->addError(new FormError('Не указан текст сообщения'));
            }
            $form->bind($request);
            if ($form->isValid()) {
                // Отправка письма
                $email = $user->getEmail();
                $globals->mail($email, $submitted_values['title'], $submitted_values['message']);
                $user->setBlogger(false);
                $user->setBloggerAlias(null);
                $user->setBloggerDemand(false);
                $user->setBloggerDemandMessage('');
                // perform some action, such as saving the task to the database
                $em = $this->getDoctrine()->getManager();                
                $em->persist($user);
                $em->flush();
                $this->clearCache();
                $this->message('Заявка пользователя "'.$user->getName().'" отклонена.', 'ok');
                $params = Array();
                return $this->redirect($this->generateUrl('admin_user_blogger_demand_list', $params));
            }
        }
        
        $action_params = Array();
        if (!empty($id)) {
            $action_params['id'] = $id;
        }
        $action_link = $this->generateUrl('admin_user_blogger_demand_deny', $action_params);    

        return array(
            'action' => $action_link,
            'form' => $form->createView(),
            'back_link' => $this->generateURL('admin_user_blogger_demand_list'),
        );
    }
    
    /**
     * Очищает кеш
     */
    public function clearCache()
    {
        $cm = $this->cacheManager();
        //$cm->clear('main_users');
        //$cm->clear('block_users');
    } 


}
