<?php

namespace Cadoles\CoreBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Form\FormError;

use Cadoles\CoreBundle\Entity\Niveau02;
use Cadoles\CoreBundle\Form\Niveau02Type;

class Niveau02Controller extends Controller
{
    private $labelroute  = 'cadoles_core_config_niveau02';
    private $labelentity = 'CadolesCoreBundle:Niveau02';
    private $labeldata   = 'niveau02';
    private $labeldatas  = 'niveau02s';

    public function listAction()
    {
      	return $this->render('CadolesCoreBundle:Niveau02:list.html.twig',[
            'useheader'         => true,
            'usemenu'           => false,
            'usesidebar'        => true,               
        ]);
    }

    public function ajaxlistAction(Request $request)
    {
        // S'assurer que c'est un appel ajax
        if (!$request->isXmlHttpRequest()) {
            return new JsonResponse(array('message' => 'Interdit'), 400);
        }
        
        $em = $this->getDoctrine()->getManager();
        
        $start=$request->query->get('start');
        $length= $request->query->get('length');
        $search= $request->query->get('search');
        $draw= $request->query->get('draw');
        $order= $request->query->get('order');
      
        // Modo ?
        $ismodo=false;
        if($this->getUser()->getRole()=="ROLE_MODO") {
            $ismodo=true;
        }


        // Nombre total d'enregistrement
        if($ismodo) {
            $total = $em->createQueryBuilder()->select('COUNT(table)')
                        ->from($this->labelentity,'table')
                        ->from("CadolesCoreBundle:UserModo","usermodo")
                        ->Where("table.niveau01=usermodo.niveau01")
                        ->andWhere("usermodo.user=:user")
                        ->setParameter("user",$this->getUser())
                        ->getQuery()->getSingleScalarResult();
        }
        else
            $total = $em->createQueryBuilder()->select('COUNT(table)')->from($this->labelentity,'table')->getQuery()->getSingleScalarResult();

        // Nombre d'enregistrement filtré
        if($search["value"]=="")
            $totalf = $total;
        else {
            $qb = $em   ->createQueryBuilder()
                        ->select('COUNT(table)')
                        ->from($this->labelentity,'table')
                        ->from("CadolesCoreBundle:Niveau01",'nv1')
                        ->where('table.niveau01=nv1.id')
                        ->andwhere('table.label LIKE :value or nv1.label LIKE :value')
                        ->setParameter("value", "%".$search["value"]."%");
            if($ismodo) {
                $qb ->from("CadolesCoreBundle:UserModo","usermodo")
                    ->andwhere("table.niveau01=usermodo.niveau01")
                    ->andWhere("usermodo.user=:user")
                    ->setParameter("user",$this->getUser());
            }
            
            $totalf = $qb->getQuery()->getSingleScalarResult();
        }

        // Construction du tableau de retour
        $output = array(
            'draw' => $draw,
            'recordsFiltered' => $totalf,
            'recordsTotal' => $total,
            'data' => array(),
        );

        // Parcours des Enregistrement
        $qb = $em->createQueryBuilder();
        $qb->select('table')
           ->from($this->labelentity,'table')
           ->from("CadolesCoreBundle:Niveau01",'nv1')
           ->where('table.niveau01=nv1.id');           
        if($search["value"]!="") {
            $qb ->andwhere('table.label LIKE :value or nv1.label LIKE :value')
                ->setParameter("value", "%".$search["value"]."%");
        }
        if($ismodo) {
            $qb->from("CadolesCoreBundle:UserModo","usermodo")
                ->andWhere("table.niveau01=usermodo.niveau01")
                ->andWhere("usermodo.user=:user")
                ->setParameter("user",$this->getUser());
        }

        switch($order[0]["column"]) {
            case 1 : 
            $qb->orderBy('nv1.label',$order[0]["dir"]);
            break;
            case 2 : 
            $qb->orderBy('table.label',$order[0]["dir"]);
            break;
        }

        $datas=$qb->setFirstResult($start)->setMaxResults($length)->getQuery()->getResult();

        foreach($datas as $data) {
            //dump($data);
            $action ="<a href='".$this->generateUrl('cadoles_core_config_niveau02_update', array('id'=>$data->getId()))."' title='Modifier'><i class='fa fa-file fa-fw fa-2x'></i></a>";
            if($data->getId()>0) $action.="<a href='".$this->generateUrl('cadoles_core_config_niveau02_delete', array('id'=>$data->getId()))."' title='Supprimer'><i class='fa fa-trash fa-fw fa-2x'></i></a>";
            array_push($output["data"],array($action,$data->getNiveau01()->getLabel(),$data->getLabel()));
        }

        // Retour
        return new Response(json_encode($output), 200);
    }    

    public function submitAction(Request $request)
    {
        // Initialisation de l'enregistrement
        $data = new Niveau02();
        
        // Création du formulaire
        $form = $this->createForm(Niveau02Type::class,$data,array("mode"=>"submit","user"=>$this->getUser()));

        // Récupération des data du formulaire
        $form->handleRequest($request);
        
        // Sur erreur
        $this->getErrorForm(null,$form,$request,$data,"submit");
        
        // Sur validation
        if ($form->get('submit')->isClicked() && $form->isValid()) {  
            $data = $form->getData();  
            $em = $this->getDoctrine()->getManager();
            
            // Sauvegarde
            $em->persist($data);
            $em->flush();

            // Retour à la liste
            return $this->redirectToRoute($this->labelroute);
        }

        // Affichage du formulaire
        return $this->render($this->labelentity.':edit.html.twig', [
            'useheader'         => true,
            'usemenu'           => false,
            'usesidebar'        => true,   
            $this->labeldata    => $data,
            'mode'              => 'submit',
            'form'              => $form->createView()
        ]);
    }  

    public function updateAction($id,Request $request)
    {
        $em = $this->getDoctrine()->getManager();

        // Récupération de l'enregistrement courant 
        $data=$this->getData($id);
        
        // Suppression modo que si niveau modéré 
        if($this->getUser()->getRole()=="ROLE_MODO") {
            $usermodo=$em->getRepository("CadolesCoreBundle:UserModo")->findOneBy(["user"=>$this->getUser(),"niveau01"=>$data->getNiveau01()]);
            if(!$usermodo) throw $this->createNotFoundException('Permission denied');
        }
                                    
        // Création du formulaire
        $form = $this->createForm(Niveau02Type::class,$data,array("mode"=>"update","user"=>$this->getUser()));

        // Récupération des data du formulaire
        $form->handleRequest($request);
    
        // Sur erreur
        $this->getErrorForm($id,$form,$request,$data,"update");
        
        // Sur validation
        if ($form->get('submit')->isClicked() && $form->isValid()) {
            $data = $form->getData();
            
            // Sauvegarde
            $em->persist($data);
            $em->flush();

            // Retour à la liste
            return $this->redirectToRoute($this->labelroute);
        }
        
       
        // Affichage du formulaire
        return $this->render($this->labelentity.':edit.html.twig', [
            'useheader'         => true,
            'usemenu'           => false,
            'usesidebar'        => true,               
            $this->labeldata    => $data,
            'mode'              => 'update',
            'form'              => $form->createView(),
        ]);
    }

    public function deleteAction($id,Request $request)
    {
        $em = $this->getDoctrine()->getManager();

        // Récupération de l'enregistrement courant 
        $data=$this->getData($id);

        // Suppression modo que si niveau modéré 
        if($this->getUser()->getRole()=="ROLE_MODO") {
            $usermodo=$em->getRepository("CadolesCoreBundle:UserModo")->findOneBy(["user"=>$this->getUser(),"niveau01"=>$data->getNiveau01()]);
            if(!$usermodo) throw $this->createNotFoundException('Permission denied');
        }

        // Création du formulaire
        $form = $this->createForm(Niveau02Type::class,$data,array("mode"=>"delete","user"=>$this->getUser()));

        // Récupération des data du formulaire
        $form->handleRequest($request);        

        // Sur erreur
        $this->getErrorForm($id,$form,$request,$data,"delete");
                
        // Sur validation
        if ($form->get('submit')->isClicked() && $form->isValid()) {
            $em->remove($data);
            $em->flush();
            
            return $this->redirectToRoute($this->labelroute);
        }
        
        // Affichage du formulaire
        return $this->render($this->labelentity.':edit.html.twig', [
            'useheader'         => true,
            'usemenu'           => false,
            'usesidebar'        => true,               
            $this->labeldata    => $data,
            'mode'              => 'delete',
            'form'              => $form->createView(),
        ]);                    
    }

    protected function getDatas()
    {
        $em = $this->getDoctrine()->getManager();
        $datas = $em->getRepository($this->labelentity)->findAll();
        return $datas;
    } 
            
    protected function getData($id)
    {
        $em = $this->getDoctrine()->getManager();
        $data = $em->getRepository($this->labelentity)->find($id);

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

        return $data;
    } 

    protected function getEntityBy($entity,$key,$value)
    {
        $em = $this->getDoctrine()->getManager();
        $datas = $em->createQueryBuilder()
                      ->select('u')
                      ->from($entity,  'u')
                      ->where('u.'.$key.'=:value')
                      ->getQuery()->setParameter("value", $value)
                      ->getResult();
        if (!$datas) return false;
        else return true;
    }

    protected function getErrorForm($id,$form,$request,$data,$mode) {
        if ($form->get('submit')->isClicked()&&$mode=="delete") {
            // On s'assure que le Niveau02 n'est pas rattaché à des utilisateurs
            if($data->getUsers()->count() > 0) {
                $form->addError(new FormError('Un utilisateur utilise ce niveau de rang 02 : suppression impossible'));
            }

            if($data->getRegistrations()->count() > 0) {
                $form->addError(new FormError('Une inscription utilise ce niveau de rang 02 : suppression impossible'));
            }
            
        }

        if ($form->get('submit')->isClicked() && ($mode=="submit" || $mode=="update")) {
            $tmp=$this->getEntityBy("CadolesCoreBundle:Group","label",$data->getLabel());
            if($tmp) $form->addError(new FormError('Un groupe utilise déjà ce label'));

            $tmp=$this->getEntityBy("CadolesCoreBundle:Niveau01","label",$data->getLabel());
            if($tmp) $form->addError(new FormError('Un niveau de rang 01 utilise déjà ce label'));

            // On s'assure que le label ne contient pas des caractères speciaux
            $string = preg_replace('~[^ éèêôöàïî\'@a-zA-Z0-9._-]~', '', $data->getLabel());
            if($string!=$data->getLabel())
            {
                $form->addError(new FormError('Caractères interdit dans ce label'));
            }             
        }

        if ($form->get('submit')->isClicked() && !$form->isValid()) {
            $this->get('session')->getFlashBag()->clear();
            $validator = $this->get('validator');
            $errors = $validator->validate($data);
            foreach( $errors as $error ) {
                $request->getSession()->getFlashBag()->add("error", $error->getMessage());
            }

            $errors = $form->getErrors();
            foreach( $errors as $error ) {
                $request->getSession()->getFlashBag()->add("error", $error->getMessage());
            }
        }
    }    
}
