<?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\PermModoProfil;
use Cadoles\CoreBundle\Entity\PermModo;
use Cadoles\CoreBundle\Form\PermmodoprofilType;

class PermmodoprofilController extends Controller
{
    private $labelroute  = 'cadoles_core_config_permmodoprofil';
    private $labelentity = 'CadolesCoreBundle:PermModoProfil';
    private $labeldata   = 'permmodoprofil';
    private $labeldatas  = 'permmodoprofils';

    public function listAction()
    {
      	return $this->render('CadolesCoreBundle:Permmodoprofil: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');
      
        // Nombre total d'enregistrement
        $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')
                        ->where('table.name LIKE :value')
                        ->setParameter("value", "%".$search["value"]."%");
            $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');
       
        if($search["value"]!="") {
            $qb ->andwhere('table.name LIKE :value')
                ->setParameter("value", "%".$search["value"]."%");
        }
        switch($order[0]["column"]) {
            case 1 : 
            $qb->orderBy('table.name',$order[0]["dir"]);
            break;
        }

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

        foreach($datas as $data) {
            $action ="<a href='".$this->generateUrl('cadoles_core_config_permmodoprofil_update', array('id'=>$data->getId()))."'><i class='fa fa-file fa-fw fa-2x' title='Modifier'></i></a>";
            if($data->getId()>0) $action.="<a href='".$this->generateUrl('cadoles_core_config_permmodoprofil_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->getName()));
        }

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

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

        // 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();

            // Init permission
            $this->initPermModo($data);

            // Retour à la liste
            return $this->redirectToRoute($this->labelroute.'_update',["id"=>$data->getId()]);
        }
        
        // Affichage du formulaire
        return $this->render('CadolesCoreBundle:Permmodoprofil: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);

        // Récupération des permission sur la side
        $sidebars=$this->get('session')->get('sidebar');
        $perms=[];
        foreach($sidebars as $sidebar) {
            foreach($sidebar["childs"] as $child) {
                $permmod=$em->getRepository("CadolesCoreBundle:PermModo")->findOneBy(["route"=>$child["path"],"permmodoprofil"=>$id]);
                if($permmod) {
                    array_push($perms,[
                        'id' => $permmod->getId(),
                        'route' =>  $permmod->getRoute(),
                        'label'=>$sidebar['label'].' >> '.$child['label'],
                        'visible'=>$permmod->getVisible()
                    ]);
                }
            }
        }

        // Création du formulaire
        $form = $this->createForm(PermmodoprofilType::class,$data,array(
            "mode"              => "update"
        ));

        // 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('CadolesCoreBundle:Permmodoprofil:edit.html.twig', [
            'useheader'         => true,
            'usemenu'           => false,
            'usesidebar'        => true,               
            $this->labeldata    => $data,
            'mode'              => 'update',
            'form'              => $form->createView(),
            'permmodos'         => $perms
        ]);
    }

    public function deleteAction($id,Request $request)
    {
        // Récupération de l'enregistrement courant 
        $data=$this->getData($id);

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

        // 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 = $this->getDoctrine()->getManager();
            $em->remove($data);
            $em->flush();
            
            return $this->redirectToRoute($this->labelroute);
        }
        
        // Affichage du formulaire
        return $this->render('CadolesCoreBundle:Permmodoprofil:edit.html.twig', [
            'useheader'         => true,
            'usemenu'           => false,
            'usesidebar'        => true,   
            $this->labeldata    => $data,
            'mode'              => 'delete',
            'form'              => $form->createView()
        ]);                    
    }

    public function permmodoAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $sidebars=$this->get('session')->get('sidebar');
        
        $perms=[];
        foreach($sidebars as $sidebar) {
            foreach($sidebar["childs"] as $child) {
                $permmod=$em->getRepository("CadolesCoreBundle:PermModo")->findOneBy(["route"=>$child["path"],"permmodoprofil"=>$id]);
                if($permmod) {
                    array_push($perms,['id' => $permmod->getId(), 'label'=>$sidebar['label'].' >> '.$child['label'],'visible'=>$permmod->getVisible()]);
                }
            }
        }

        return $this->render('CadolesCoreBundle:Permmodoprofil:permmodo.html.twig', [
            'useheader'     => true,
            'usemenu'       => false,
            'usesidebar'    => true,
            'profil'        => $this->getData($id),
            'permmodos'     => $perms
        ]);
    }

    public function permmodoupdateAction(Request $request)
    {
        // S'assurer que c'est un appel ajax
        if (!$request->isXmlHttpRequest()) return new JsonResponse(array('message' => 'Interdit'), 400);

        $output=array();
        $id             = $request->request->get('id');

        $em = $this->getDoctrine()->getManager();
        $permmodo = $this->getDoctrine()->getRepository("CadolesCoreBundle:PermModo")->find($id);
        if (!$permmodo) throw $this->createNotFoundException('Unable to find entity.');

        $permmodo->setVisible(!$permmodo->getVisible());
        $em->persist($permmodo);
        $em->flush();        

        $response = new Response(json_encode($output));    
        $response->headers->set('Content-Type', 'application/json');        
        return $response; 
    }

    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 getErrorForm($id,$form,$request,$data,$mode) {
        if ($form->get('submit')->isClicked()&&$mode=="delete") {
            // On s'assure que le profil n'est pas rattaché à des utilisateurs
            if($data->getUsers()->count() > 0) {
                $form->addError(new FormError('Un utilisateur utilise ce profil de modération : suppression impossible'));
            }
        }

        if ($form->get('submit')->isClicked() && ($mode=="submit" || $mode=="update")) {
        }

        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());
            }
        }
    }    

    private function initPermModo($profil) {
        $this->addModeration($profil,'cadoles_core_config_commun',0);
        $this->addModeration($profil,'cadoles_core_config_theme',0);
        $this->addModeration($profil,'cadoles_core_config_datauser',0);
        $this->addModeration($profil,'cadoles_core_config_datausers',0);
        $this->addModeration($profil,'cadoles_core_config_whitelist',0);
        $this->addModeration($profil,'cadoles_core_config_niveau01',1);
        $this->addModeration($profil,'cadoles_core_config_niveau02',1);
        $this->addModeration($profil,'cadoles_core_config_group',1);
        $this->addModeration($profil,'cadoles_core_config_registration',1);
        $this->addModeration($profil,'cadoles_core_config_user',1);
        $this->addModeration($profil,'cadoles_portal_config_pagetemplate',1);
        $this->addModeration($profil,'cadoles_portal_config_page',1);
        $this->addModeration($profil,'cadoles_portal_config_item',1);
        $this->addModeration($profil,'cadoles_portal_config_alert',1);
        $this->addModeration($profil,'cadoles_portal_config_calendar',1);
        $this->addModeration($profil,'cadoles_portal_config_blog',1);
        $this->addModeration($profil,'cadoles_portal_config_project',1);
        $this->addModeration($profil,'cadoles_portal_config_flux',1);
        $this->addModeration($profil,'cadoles_portal_config_notice',1);
        $this->addModeration($profil,'cadoles_portal_config_icon',1);
        $this->addModeration($profil,'cadoles_portal_config_syncbalado',0);
        $this->addModeration($profil,'cadoles_portal_config_synccdt',0);
        $this->addModeration($profil,'cadoles_portal_config_syncgepiannu',0);
        $this->addModeration($profil,'cadoles_portal_config_syncgepisiecle',0);
        $this->addModeration($profil,'cadoles_portal_config_synclimesurvey',0);
        $this->addModeration($profil,'cadoles_portal_config_syncmoodle',0);
        $this->addModeration($profil,'cadoles_portal_config_syncnextcloud',0);
        $this->addModeration($profil,'cadoles_portal_config_syncsacoche',0);
        $this->addModeration($profil,'cadoles_portal_config_syncpiwik',0);
        $this->addModeration($profil,'cadoles_portal_config_syncwordpress',0);
        $this->addModeration($profil,'cadoles_core_config_statistic',1);
        $this->addModeration($profil,'cadoles_core_config_mailing',1);
        $this->addModeration($profil,'cadoles_core_config_importuser',0);
        $this->addModeration($profil,'cadoles_cron_config',0);
        $this->addModeration($profil,'cadoles_cron_config_log',0);
    }

    private function addModeration($profil,$route,$visible) {
        $em = $this->getDoctrine()->getManager();
        $entity=$em->getRepository('CadolesCoreBundle:PermModo')->findOneBy(["route"=>$route,"permmodoprofil"=>$profil]);
        if(!$entity) {
            $entity=new PermModo();
            $entity->setRoute($route);
            $entity->setVisible($visible);
            $entity->setPermmodoprofil($profil);
            $em->persist($entity);
            $em->flush();            
        }
    }

}
