<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Form\FormError;

use App\Form\ConfigType;
use App\Form\DatauserType;

class ConfigController extends AbstractController
{
    public function home(Request $request)
    {
      	return $this->render('Core\config.html.twig',[
            'useheader'     => true,
            'usemenu'       => false,
            'usesidebar'    => true,
        ]);
    }

    public function list(Request $request, ManagerRegistry $em)
    {
        $configs = $em->getManager()->createQueryBuilder()
                      ->select('b')
                      ->from('App\Entity\Config',  'b')
                      ->where('b.visible = :visible')
                      ->setParameter('visible', 1)
                      ->addOrderBy('b.order')
                      ->getQuery()
                      ->getResult();

        return $this->render('Config\list.html.twig', [
            'useheader'     => true,
            'usemenu'       => false,
            'usesidebar'    => true,
            'configs'       => $configs
        ]);
    }

    public function update($id,Request $request, ManagerRegistry $em)
    {
        // Récupération de l'enregistrement courant
        $config=$this->getConfig($id,$em);

        // Vérifier que cet enregistrement est modifiable
        $type=$config->getType();
        $required=$config->getRequired();
        $visible=$config->getVisible();
        $changeable=$config->getChangeable();
        if(!$visible||!$changeable) {
            return $this->redirectToRoute('app_core_config_commun');
        }

        // Création du formulaire
        $form = $this->createForm(ConfigType::class,$config,array("key" => $id, "type" => $type, "required" => $required));

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

        // Sur erreur
        $this->getErrorForm($form,$request,$config);

        // Sur validation
        if ($form->get('submit')->isClicked() && $form->isValid()) {
            $config = $form->getData();
            $em->getManager()->flush();

            // Sur type boolean
            if($type=="boolean") {
                $qb = $em->getManager()->createQueryBuilder();
                $q = $qb->update('App\Entity\Config', 'c')
                    ->set('c.visible', ':visible')
                    ->where('c.grouped = :key')
                    ->setParameter('visible', $config->getValue())
                    ->setParameter('key', $id)
                    ->getQuery();
                $q->execute();                
            }
            return $this->redirectToRoute('app_core_config_commun');
        }

        // Affichage du formulaire
        return $this->render('Config\update.html.twig', [
            'useheader'     => true,
            'usemenu'       => false,
            'usesidebar'    => true,
            'config'        => $config,
            'type'          => $type,
            'form'          => $form->createView()
        ]);
    }

    public function delete($id,Request $request, ManagerRegistry $em)
    {
        // Récupération de l'enregistrement courant
        $config=$this->getConfig($id,$em);
        if(!$config->getRequired()) {
            $config->setValue("");
            $em->getManager()->flush();            
        }
        return $this->redirectToRoute('app_core_config_commun',['usesidebar'=>true]);
    }

    public function logo()
    {
        return $this->render('Config\logo.html.twig',[
            'useheader'     => false,
            'usemenu'       => false,
            'usesidebar'    => false,
        ]);
    }

    public function header()
    {
        return $this->render('Config\header.html.twig',[
            'useheader'     => false,
            'usemenu'       => false,
            'usesidebar'    => false,
        ]);
    }

    protected function getConfig($id, ManagerRegistry $em)
    {
        $config = $em->getRepository('App\Entity\Config')->find($id);

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

        return $config;
    }

    public function datauserdefault(Request $request, ManagerRegistry $em)
    {   
        $config=$em->getRepository('App\Entity\Config')->find("datauser");
        $config->setValue("");
        $em->getManager()->flush();     
        
        return $this->redirectToRoute('app_core_config_datauser');      
    }

    public function datauser(Request $request, ManagerRegistry $em)
    {      
        $session=$request->getSession();
        $config=$em->getRepository('App\Entity\Config')->find("datauser");
        $fields=$config->getValue();
        $fields=json_decode($fields,true);
        if(!is_array($fields)) $fields=[];

        // Valeur par défaut 0=caché / 1=falcultatif / 2=obligatoire
        if(!array_key_exists("firstname",$fields)) {
            $fields["firstname"]["perm"]=1;
            $fields["firstname"]["label"]="Prénom";
        }            

        if(!array_key_exists("visible",$fields)) {
            $fields["visible"]["perm"]=2;
            $fields["visible"]["label"]="Visible";
        }   

        if(!array_key_exists("authlevel",$fields)) {
            $fields["authlevel"]["perm"]=2;
            $fields["authlevel"]["label"]="Niveau d'authentification";
        }   

        if(!array_key_exists("belongingpopulation",$fields)) {
            $fields["belongingpopulation"]["perm"]=2;
            $fields["belongingpopulation"]["label"]="Population d'appartenance";
        }   

        if(!array_key_exists("job",$fields)) {
            $fields["job"]["perm"]=1;
            $fields["job"]["label"]="Métier";
        }   

        if(!array_key_exists("position",$fields)) {
            $fields["position"]["perm"]=1;
            $fields["position"]["label"]="Fonction";
        }   

        if(!array_key_exists("niveau02",$fields)) {
            $fields["niveau02"]["perm"]=1;
            $fields["niveau02"]["label"]=$session->get('labelniveau02');
        }   

        if(!array_key_exists("usualname",$fields)) {
            $fields["usualname"]["perm"]=1;
            $fields["usualname"]["label"]="Nom d'Usage";
        }   

        if(!array_key_exists("gender",$fields)) {
            $fields["gender"]["perm"]=1;
            $fields["gender"]["label"]="Sexe";
        }   

        if(!array_key_exists("givensname",$fields)) {
            $fields["givensname"]["perm"]=1;
            $fields["givensname"]["label"]="Autre Prénom";
        }   

        if(!array_key_exists("telephonenumber",$fields)) {
            $fields["telephonenumber"]["perm"]=1;
            $fields["telephonenumber"]["label"]="Téléphone";
        }   

        if(!array_key_exists("postaladress",$fields)) {
            $fields["postaladress"]["perm"]=1;
            $fields["postaladress"]["label"]="Adresse";
        }   

        if(!array_key_exists("birthdate",$fields)) {
            $fields["birthdate"]["perm"]=1;
            $fields["birthdate"]["label"]="Date de Naissance";
        }   

        if(!array_key_exists("birthcountry",$fields)) {
            $fields["birthcountry"]["perm"]=1;
            $fields["birthcountry"]["label"]="Pays de Naissance";
        }   

        if(!array_key_exists("birthplace",$fields)) {
            $fields["birthplace"]["perm"]=1;
            $fields["birthplace"]["label"]="Ville de Naissance";
        }   
        
        if(!array_key_exists("visite",$fields)) {
            $fields["visite"]["perm"]=1;
            $fields["visite"]["label"]="Visite";
        }   

        if(!$session->get('viewniveau02'))
            unset($fields["niveau02"]);

       

        
        $form = $this->createForm(DatauserType::class,$config,array("mode"=>"datauser","fields" => $fields));

        // Récupération des data du formulaire
        $form->handleRequest($request);
        
        if ($form->get('submit')->isClicked() && $form->isValid()) {
          
            foreach($fields as $key => $value) {
                $perm = $form->get($key)->getData();
                $fields[$key]["perm"]=$perm;
            }
            
            $json=json_encode($fields);
            $config->setValue($json);
            $em->getManager()->flush();     
        }


        return $this->render('Config\datauser.html.twig',[
            'useheader'     => true,
            'usemenu'       => false,
            'usesidebar'    => true,
            'form'          => $form->createView(),
            'mode'          => "datauser"
        ]);
    }

    public function datausersdefault(Request $request, ManagerRegistry $em)
    {   
        $config=$em->getRepository('App\Entity\Config')->find("datausers");
        $config->setValue("");
        $em->getManager()->flush();     
        
        return $this->redirectToRoute('app_core_config_datausers');      
    }

    public function datausers(Request $request, ManagerRegistry $em)
    {      
        $session=$request->getSession();
        $config=$em->getRepository('App\Entity\Config')->find("datausers");
        $fields=$config->getValue();

        $fields=json_decode($fields, true);
        if(!is_array($fields)) $fields=[];
        
        // Valeur par défaut 0=caché / 3=visible
        if(!array_key_exists("avatar",$fields)) {
            $fields["avatar"]["perm"]=1;
            $fields["avatar"]["label"]="Avatar";
        }
        if(!array_key_exists("login",$fields)) {
            $fields["login"]["perm"]=1;
            $fields["login"]["label"]="Login";
        }
        if(!array_key_exists("lastname",$fields)) {
            $fields["lastname"]["perm"]=1;
            $fields["lastname"]["label"]="Nom";
        }
        if(!array_key_exists("firstname",$fields)) {
            $fields["firstname"]["perm"]=1;
            $fields["firstname"]["label"]="Prenom";
        }
        if(!array_key_exists("email",$fields)) {
            $fields["email"]["perm"]=1;
            $fields["email"]["label"]="Email";
        }
        if(!array_key_exists("niveau01",$fields)) {
            $fields["niveau01"]["perm"]=1;
            $fields["niveau01"]["label"]=$session->get('labelniveau01');
        }   
        if(!array_key_exists("niveau02",$fields)) {
            $fields["niveau02"]["perm"]=1;
            $fields["niveau02"]["label"]=$session->get('labelniveau02');
        }
        if(!array_key_exists("group",$fields)) $fields["group"]["perm"]=1;
        $fields["group"]["label"]="Groupes (caché uniquement pour le rôle Utilisateur) ";

        if(!array_key_exists("job",$fields)) {
            $fields["job"]["perm"]=1;
            $fields["job"]["label"]="Métier";
        }
        if(!array_key_exists("position",$fields)) {
            $fields["position"]["perm"]=1;
            $fields["position"]["label"]="Fonction";
        }   
        if(!array_key_exists("role",$fields)) {
            $fields["role"]["perm"]=1;
            $fields["role"]["label"]="Rôles";
        }
        if(!array_key_exists("telephonenumber",$fields)) {
            $fields["telephonenumber"]["perm"]=1;
            $fields["telephonenumber"]["label"]="Téléphone";            
        }
        if(!array_key_exists("visitedate",$fields)) $fields["visitedate"]["perm"]=1;
        $fields["visitedate"]["label"]="Visite (caché uniquement pour les rôles Animateur et Utilisateur) ";

        if(!$session->get('viewniveau02'))
            unset($fields["niveau02"]);

        $form = $this->createForm(DatauserType::class,$config,array("mode"=>"datausers","fields" => $fields));

        // Récupération des data du formulaire
        $form->handleRequest($request);
        
        if ($form->get('submit')->isClicked()) {
            $onevisible=false;
            foreach($fields as $key => $value) {
                $perm = $form->get($key)->getData();
                $fields[$key]["perm"]=$perm;
                if($perm==1) $onevisible=true;
            }
            
            if(!$onevisible)
                $form->addError(new FormError('Au moins une colonne doit être visible'));

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

        if ($form->get('submit')->isClicked() && $form->isValid()) {
            $json=json_encode($fields);
            $config->setValue($json);
            $em->getManager()->flush();     
        }


        return $this->render('Config\datauser.html.twig',[
            'useheader'     => true,
            'usemenu'       => false,
            'usesidebar'    => true,
            'form'          => $form->createView(),
            'mode'          => "datausers"
        ]);
    }

    protected function getErrorForm($form,$request,$data) {
        if ($form->get('submit')->isClicked() && !$form->isValid()) {
            $errors = $form->getErrors();
            foreach( $errors as $error ) {
                $request->getSession()->getFlashBag()->add("error", $error->getMessage());
            }
        }
    }
}
