<?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\LangVar;
use Symfony\Component\Filesystem\Exception\IOException;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Response;

class AdminLangVarController extends ControllerAbstract
{
    public $formats = Array(
        'text' => 'текст',
        'html' => 'HTML',
        'bbcode' => 'BBcode',
    );
    
    /**
     * @Route("/admin/lang_var/edit/{id}")
     * @Template("NeagMainBundle:AdminLangVar:edit.html.twig")
     */
    public function editAction($id = null)
    {
        $request = $this->getRequest();
        
        $globals = $this->get('globals'); 
       
        $DB = $this->get('database_connection'); 
        
        $session = $globals->getSession();      
        
        $LangVar = null;
        $edit = false;
        if (!empty($id)) {
            $query = $this->getDoctrine()->getManager()->createQueryBuilder()
            ->select(Array('lv'))
            ->from('NeagMainBundle:LangVar', 'lv')
            ->where('lv.id = :id')
            ->setParameter('id', $id)
            ->getQuery(); 
            $rows = $query->getResult();
            if (!empty($rows)) {
                $LangVar = $rows[0];
            } else {
                $LangVar = null;
            }
            $edit = true; 
        }
        if (empty($LangVar)) {
            $this->redirect($this->generateUrl('admin_lang_var_list', array()));
        }

        $builder = $this->createFormBuilder($LangVar);
        $builder->add('scope', 'text', Array(
            'label' => 'Группа', 
            'trim' => true, 
            'required' => true,
            'disabled' => true,
        ));
        $builder->add('name', 'text', Array(
            'label' => 'Имя переменной', 
            'trim' => true, 
            'required' => true,
            'disabled' => true,
        ));
        $builder->add('content', 'textarea', Array(
            'label' => 'Содержимое', 
            'trim' => true, 
            'required' => false
        ));
        $builder->add('format', 'choice',       
            Array(
                'label' => 'Формат', 
                'choices' => $this->formats,
                'required' => true,
            )
        ); 
        $form = $builder->getForm();
            
        if ($request->isMethod('POST')) {
            $submitted_values = $_POST[$form->getName()];
            $form->bind($submitted_values);
            if ($form->isValid()) {
                // perform some action, such as saving the task to the database
                if (!empty($LangVar)) {
                    $em = $this->getDoctrine()->getManager();                
                    $em->persist($LangVar);
                    $em->flush();
                    $this->message('Изменения внесены', 'ok');
                    return $this->redirect($this->generateUrl('admin_lang_var_list', Array()));
                }
            }
        }    

        return array(
            'form' => $form->createView(),
            'edit' => $edit,
            'action' => $this->generateURL('admin_lang_var_edit', Array('id' => $id)),
            'fileadmin_url' => $this->generateURL('admin_fileadmin', Array('type' => 'popup')),
        );
    }

    /**
     * @Route("/admin/lang_var")
     * @Template("NeagMainBundle:AdminLangVar:list.html.twig")
     */
    public function listAction()
    {
        $del = $this->getRequest()->query->get('del'); 
        
        $DB = $this->get('database_connection'); 
        
        $globals = $this->get('globals');
        
        $request = $this->getRequest();
        
        $session = $globals->getSession(); 
        
        if (!empty($del)) {
            $query = $this->getDoctrine()->getManager()->createQueryBuilder()
            ->select(Array('lv'))
            ->from('NeagMainBundle:LangVar', 'lv')
            ->where('lv.id = :id')
            ->setParameter('id', $del)
            ->getQuery(); 
            $rows = $query->getResult();
            if (!empty($rows)) {
                $LangVar = $rows[0];
            } else {
                $LangVar = null;
            }
            if (!empty($LangVar)) {
                $em = $this->getDoctrine()->getManager();                
                $em->remove($LangVar);
                $em->flush();
                $this->message('Языковая переменная успешно удалена', 'ok');
           }
            $this->clearCache();
        }
        
        $scope = 'none';
        
        // Сброс фильтра
        $action = $request->query->get('action', null);
        if ($action == 'reset') {
            $session->set('admin_lang_var_filter', null);
            return $this->redirect($this->generateUrl('admin_lang_var_list', Array()));
        }
        
        // Обработка фильтра
        if ($request->isMethod('POST')) {
            $submitted_values = $_POST['form'];            
            if (!empty($submitted_values['scope'])) {                
                if ($submitted_values['scope'] == 'none') {
                    $scope = 'none';
                } else {
                    $scope = $submitted_values['scope'];
                }
            }
            $admin_lang_var_filter = Array();
            $admin_lang_var_filter['scope'] = $scope;
            $session->set('admin_lang_var_filter', $admin_lang_var_filter);
            return $this->redirect($this->generateUrl('admin_lang_var_list', Array()));
        } else {
            $admin_lang_var_filter = $session->get('admin_lang_var_filter');
            //$this->trace($admin_lang_var_filter);
            if (!empty($admin_lang_var_filter)) {
                if (!empty($admin_lang_var_filter['scope'])) {                    
                    $scope = $admin_lang_var_filter['scope'];
                }
            }
        }          
        
        // Filter
        $fb = $this->createFormBuilder();
        $fb->add('scope', 'choice',       
            Array(
                'label' => 'Группа', 
                'choices' => $this->getFilterScopeChoices(),
                'required' => true,
                'data' => $scope,
            )
        ); 
        $filter_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());
        // qb
        $qb = $this->getDoctrine()->getManager()->createQueryBuilder()
        ->select(Array('lv'))
        ->from('NeagMainBundle:LangVar', 'lv');
        if (!empty($scope) ? $scope != 'none' : false) {
            //$this->trace('scope: '.$scope);
            $qb->andWhere('lv.scope = :scope')
            ->setParameter('scope', $scope);
        }
        $qb->orderBy('lv.id', 'DESC');
        // bind
        $pager->setQueryBuilder($qb);
        $rows = $pager->getResults();
        $data = Array(); 
        foreach ($rows as $row) {
            //$this->trace();
            $data[] = Array(
                'id' => $row->getId(),
                'scope' => $row->getScope(),                
                'name' => $row->getName(), 
                'content' => $row->getContent(), 
                'format' => $this->formats[$row->getFormat()], 
                'delete_link' => $this->generateUrl('admin_lang_var_list', array('del' => $row->getId())),
                'edit_link' => $this->generateUrl('admin_lang_var_edit', array('id' => $row->getId())),
            ); 
        }
        return Array(
            'filter_form_action' => $this->generateURL('admin_lang_var_list'),
            'filter_form_reset_link' => $this->generateURL('admin_lang_var_list', Array('action' => 'reset')),
            'filter_form' => $filter_form->createView(),
            'data' => $data, 
            'pager' => $this->renderPager($pager),            
        );
    }  
    
    /**
     * Наполняет массив списка групп для селекта в форме фильтра
     */
    public function getFilterScopeChoices()
    {
        $query = $this->getDoctrine()->getManager()->createQueryBuilder()
        ->select('DISTINCT(lv.scope)')
        ->from('NeagMainBundle:LangVar', 'lv')
        ->orderBy('lv.id', 'asc')
        ->getQuery(); 
        $rows = $query->getResult();
        $data = Array();
        $data['none'] = '-- Выберите группу --';
        foreach ($rows as $row) {
            $data[$row[1]] = $row[1];        
        }
        return $data;       
    }
    
    /**
     * Наполняет массив списка разделов для селекта в форме фильтра
     */
    public function getFilterSportCategoryChoices($parent_id = null, $prefix = '')
    {
        $repository = $this->getDoctrine()
        ->getRepository('NeagMainBundle:SportCategory');
        if (empty($parent_id)) {
            $query = $repository->createQueryBuilder('c')
            ->where('c.parent IS NULL')
            ->orderBy('c.weight', 'ASC')
            ->getQuery();
        } else {
            $query = $repository->createQueryBuilder('c')
            ->where('c.parent = :parent')
            ->setParameter('parent', $parent_id)
            ->orderBy('c.weight', 'ASC')
            ->getQuery();
        }
        $rows = $query->getResult();
        $data = Array();
        if (empty($parent_id)) {
            $data['any'] = '-- Любой --';
            $data['none'] = '-- Без раздела --';
        }    
        foreach ($rows as $row) {
            $row->setTitlePrefix($prefix);
            //$data[$row->getId()] = $row;
            $data[$row->getId()] = $row->getTitle();
            $prefix_next = $prefix.'-';
            $data_next = $this->getFilterSportCategoryChoices($row->getId(), $prefix_next);
            foreach ($data_next as $key => $value) {
                $data[$key] = $value;
            }      
            //$data = array_merge($data, $this->getCategoryChoices($row->getId(), $suffix_next));
        }
        return $data;         
    }
    
    /**
     * Наполняет массив списка разделов Joker для селекта в форме фильтра
     */
    public function getFilterJokerCategoryChoices($parent_id = null, $prefix = '')
    {
        $repository = $this->getDoctrine()
        ->getRepository('NeagMainBundle:JokerCategory');
        if (empty($parent_id)) {
            $query = $repository->createQueryBuilder('c')
            ->where('c.parent IS NULL')
            ->orderBy('c.weight', 'ASC')
            ->getQuery();
        } else {
            $query = $repository->createQueryBuilder('c')
            ->where('c.parent = :parent')
            ->setParameter('parent', $parent_id)
            ->orderBy('c.weight', 'ASC')
            ->getQuery();
        }
        $rows = $query->getResult();
        $data = Array();
        if (empty($parent_id)) {
            $data['any'] = '-- Любой --';
            $data['none'] = '-- Без раздела --';
        }    
        foreach ($rows as $row) {
            //$row->setTitlePrefix($prefix);
            //$data[$row->getId()] = $row;
            $data[$row->getId()] = $row->getTitle();
            $prefix_next = $prefix.'-';
            $data_next = $this->getFilterJokerCategoryChoices($row->getId(), $prefix_next);
            foreach ($data_next as $key => $value) {
                $data[$key] = $value;
            }      
            //$data = array_merge($data, $this->getCategoryChoices($row->getId(), $suffix_next));
        }
        return $data;         
    }
    
    /**
     * Очищает кеш публикаци статей
     */
    public function clearCache()
    {
        $cm = $this->cacheManager();
        $cm->clear('popular_news_block');
        $cm->clear('main_news');
    }        

}