<?php

namespace TwigExtension;

use Helpers\Trad\ITrad;
use Psr\Container\ContainerInterface;
use Skeleton\Router;
use Helpers\Trad\Trad;
use Helpers\Parametres\Constante;

class FiltreAvanceExtention extends \Twig\Extension\AbstractExtension
{
    protected $router;
    
    protected $pdo;
    
    protected $contenaire;

    private ITrad $trad;
    
    public function __construct(\PDO $pdo, ContainerInterface $contenaire, Router $router)
    {
        $this->router = $router;
        $this->pdo = $pdo;
        $this->contenaire = $contenaire;
        $this->trad = $contenaire->get('translationService');
    }
    
    public function getFunctions()
    {
        return [
            new \Twig\TwigFunction('filtreAvance', [
                $this,
                'filtreAvance'
            ], [
                'is_safe' => [
                    'html'
                ]
            ]),
        ];
    }
    
    public function filtreAvance($posts, $filtre, $initFiltreAvance)
    {
        
        $html = $this->initJs($initFiltreAvance);
        $keySelects = [];
        $conteurFA = 0;
        // $keyFiltre = 0;
        
        $key = explode(';', substr($filtre, 0, -1));
        
        for ($i=0; $i < count($key); $i++) {
            $keySelects[$i] = explode('#', $key[$i]);
        }
        
        
        if (isset($posts['idFiltreAvance']) && $posts['idFiltreAvance'] == '{0}') {
            $posts['idFiltreAvance'][0] = 0;
        }
        
        if (isset($posts['idFiltreAvance'])) {
            if (\is_array($posts['idFiltreAvance'])) {
                foreach ($posts['idFiltreAvance'] as $keyFiltre) {
                    // $keyFiltre = $keyFiltre+1;
                    $keyComparaisonValue='';
                    $pathSelection='';
                    $titreSelection='';
                    $entitySelection='';
                    foreach ($keySelects as $keyComparaisonValue => $valueComparaisonValue) {
                        if ($posts['fa-'.$keyFiltre.'-1'] == $valueComparaisonValue[0].'-'.$valueComparaisonValue[1].'-'.($valueComparaisonValue[4] ?? '')) {
                            $idValueSelectedOption = $keyComparaisonValue;
                            $pathSelection = $valueComparaisonValue[4] ?? '';
                            $titreSelection = $valueComparaisonValue[2];
                            $entitySelection =  $valueComparaisonValue[5]?? '';
                        }
                    }
                    
                    $parametre =  explode('-', $posts['fa-'.$keyFiltre.'-1']);
                    
                
                    /* $_SESSION['bulleFiltre']['fa-'.$keyFiltre.'-1'] = [
                        'titre' => $titre,
                        'value' => $value
                    ];*/
                    
                    $html .=  '<script>
                    newCritereActive['.$keyFiltre.']=1;
                    choixCritere['.$keyFiltre.'] = "'.$parametre[0].'";
                    idCountFitreAvance++;
                    </script>
                    <div class="colonne2"  id="divfiltreAvance'.$keyFiltre.'">
                    <div class="colonne4">
                    <select class="form-control form-control-sm" id="filtreAvance'.$keyFiltre.'" name="fa-'.$keyFiltre.'-1" onchange="filtreAvanceNewCritere(this.value, this.id, '.$keyFiltre.',\''.addslashes($filtre).'\');">
                    
                    <option value="drop">'.$this->trad->t('Nouveau critère').'</option>';

                    $isCS = false;
                    foreach ($keySelects as $keySelect) {
                        $html .= '<option value="'.$keySelect[0].'-'.$keySelect[1].'-'.($keySelect[4] ?? '').'"';
                        
                        if ($posts['fa-'.$keyFiltre.'-1'] == $keySelect[0].'-'.$keySelect[1].'-'.($keySelect[4] ?? '')) {
                            $isCS = strpos($keySelect[0], 'CS') !== false;
                            $conteurFA++;
                            $html .=' selected ';
                            $_SESSION['bulleFiltre']['fa-'.$keyFiltre.'-1']['titre'] = $keySelect[2];
                        }
                        
                        
                        if ($keySelect[1] == 'bool' && $posts['fa-'.$keyFiltre.'-1'] == $keySelect[0].'-'.$keySelect[1].'-'.($keySelect[4] ?? '')) {
                            $conteurFA++;
                            $html .=' selected ';
                            $_SESSION['bulleFiltre']['fa-'.$keyFiltre.'-1']['titre'] = $keySelect[2];
                        }
                        $html .='>'.$keySelect[2].'</option>';
                    }
                    $html .= '           </select>
                    </div>';
                    
                    $html .= $this->getFormAvanceSpecifique($keyFiltre, $parametre[1], $posts, $pathSelection, $entitySelection, $titreSelection, $isCS);
                
                    
                    $html .= '  <span id="dropblock'.$keyFiltre.'"><span class="supprimer_filtre" id="drop-'.$keyFiltre.'" onclick="dropFiltreAvance(this.id)"></span></span>
                    </div>';
                    
                    $_SESSION['bulleFiltre']['fa-'.$keyFiltre.'-1']['suppression'] = 'dropFiltreAvance(\'drop-'.$keyFiltre.'\')';
                }
            }
        }
        
        if (!isset($keyFiltre) || $keyFiltre ==0) {
            $keyFiltre =1;
        } else {
            $keyFiltre++;
        }

        $filterJS = (string)str_replace('"', '', $filtre);
        $filterJS = (string)str_replace("'", '', $filterJS);
        
        $html .=  '<script>
        idCountFitreAvance++;
        </script>
        <div class="colonne2"  id="divfiltreAvance'.$keyFiltre.'">
        <div class="colonne4">
        <select class="form-control form-control-sm" id="filtreAvance'.$keyFiltre.'" name="fa-'.$keyFiltre.'-1" onchange="filtreAvanceNewCritere(this.value, this.id, '.$keyFiltre.',\''.$filterJS.'\');">
        
                                <option value="drop">'.$this->trad->t('Nouveau critère').'</option>';
        foreach ($keySelects as $keySelect) {
            $html .=            '<option value="'.$keySelect[0].'-'.$keySelect[1].'-'.($keySelect[4] ?? '').'">'.str_replace("", "", $keySelect[2]).'</option>';
        }
        $html .=            '</select>
                       </div>';
        
        
        $html .= '  <span id="dropblock'.$keyFiltre.'"></span>
                 </div>';

        if ($conteurFA) {
            $html .=  '<script>$("#buttonCollapseFA").click();</script>';
        }

        return $html;
    }
    
    public function getFormAvanceSpecifique($id, $type, $post, $zoom = '', $entity = '', $titre = '', bool $isCs = false)
    {
        $trad = $this->trad;
        if ($type == 'text') {
            $html = '<div class="colonne4 filtreColonne4filtreAvance'.$id.'">
            <select class="form-control form-control-sm" name="fa-'.$id.'-2" id="filtreAvance'.$id.'-2">
            <option  value="egal" '.(($post['fa-'.$id.'-2'] == 'egal') ? ' selected ' : '').'>'.$trad->t('égal à').'</option>
            <option  value="contient" '.(($post['fa-'.$id.'-2'] == 'contient') ? ' selected ' : '').'>'.$trad->t('contient').'</option>
            <option value="commence" '.(($post['fa-'.$id.'-2'] == 'commence') ? ' selected ' : '').'>'.$trad->t('commence par').'</option>
            <option  value="fini" '.(($post['fa-'.$id.'-2'] == 'fini') ? ' selected ' : '').'>'.$trad->t('finit par').'</option>
                        </select>
                        <input type="hidden" name="idFiltreAvance[]" value="'.$id.'" />
                        </div>
                        <div class="colonne4 filtreColonne4filtreAvance'.$id.'">
                        <input class="form-control form-control-sm" type="text" name="fa-'.$id.'-3" value="'.$post['fa-'.$id.'-3'].'" id="filtreAvance'.$id.'-3">
                        </div>';
                        
            if ($post['fa-'.$id.'-2'] == 'egal') {
                $_SESSION['bulleFiltre']['fa-'.$id.'-1']['titre']= $_SESSION['bulleFiltre']['fa-'.$id.'-1']['titre'].' '.$trad->t('égal à').' ';
            }
            if ($post['fa-'.$id.'-2'] == 'contient') {
                $_SESSION['bulleFiltre']['fa-'.$id.'-1']['titre']= $_SESSION['bulleFiltre']['fa-'.$id.'-1']['titre'].' '.$trad->t('contient').' ';
            }
            if ($post['fa-'.$id.'-2'] == 'commence') {
                $_SESSION['bulleFiltre']['fa-'.$id.'-1']['titre']= $_SESSION['bulleFiltre']['fa-'.$id.'-1']['titre'].' '.$trad->t('commence par').' ';
            }
            if ($post['fa-'.$id.'-2'] == 'fini') {
                $_SESSION['bulleFiltre']['fa-'.$id.'-1']['titre']= $_SESSION['bulleFiltre']['fa-'.$id.'-1']['titre'].' '.$trad->t('finit par').' ';
            }
            
            
            $_SESSION['bulleFiltre']['fa-'.$id.'-1']['value']= $post['fa-'.$id.'-3'];
        }
        
        
        if ($type == 'date') {
            $html = '  <div class="colonne4 filtreColonne4filtreAvance'.$id.'">
            <select class="form-control form-control-sm" name="fa-'.$id.'-2" id="filtreAvance'.$id.'-2" onchange="entreDateFiltreAvance(this.value, \'filtreAvance'.$id.'\')">
            <option value="egal"  '.(($post['fa-'.$id.'-2'] == 'egal') ? ' selected ' : '').'>'.$trad->t('égal à').'</option>
            <option value="entre"  '.(($post['fa-'.$id.'-2'] == 'entre') ? ' selected ' : '').'>'.$trad->t('compris entre').'</option>
            <option value="superieur"  '.(($post['fa-'.$id.'-2'] == 'superieur') ? ' selected ' : '').'>'.$trad->t('superieur à').'</option>
            <option value="inferieur"  '.(($post['fa-'.$id.'-2'] == 'inferieur') ? ' selected ' : '').'>'.$trad->t('inferieur à').'</option>
            </select>
            <input type="hidden" name="idFiltreAvance[]" value="'.$id.'" />
            </div>
            <div class="colonne4 filtreColonne4filtreAvance'.$id.'">
            <input type="text" class="form-control form-control-sm datepicker" name="fa-'.$id.'-3" value="'.$post['fa-'.$id.'-3'].'" id="filtreAvance'.$id.'-3" >
            </div>
            <div class="colonne4 filtreColonne4filtreAvance'.$id.'" id="filtreAvance'.$id.'-4" style="'.(($post['fa-'.$id.'-2'] == 'entre') ? ' visibility:visible; ' : 'visibility:hidden;').'" >
            <input type="text" class="form-control form-control-sm datepicker" name="fa-'.$id.'-4" value="'.($post['fa-'.$id.'-4']?? '') .'" >
            </div>';
            
            if ($post['fa-'.$id.'-2'] == 'egal') {
                $_SESSION['bulleFiltre']['fa-'.$id.'-1']['titre']= $_SESSION['bulleFiltre']['fa-'.$id.'-1']['titre'].' '.$trad->t('égal à').' ';
            }
            if ($post['fa-'.$id.'-2'] == 'entre') {
                $_SESSION['bulleFiltre']['fa-'.$id.'-1']['titre']= $_SESSION['bulleFiltre']['fa-'.$id.'-1']['titre'].' '.$trad->t('compris entre').' ';
            }
            if ($post['fa-'.$id.'-2'] == 'superieur') {
                $_SESSION['bulleFiltre']['fa-'.$id.'-1']['titre']= $_SESSION['bulleFiltre']['fa-'.$id.'-1']['titre'].' '.$trad->t('superieur à').' ';
            }
            if ($post['fa-'.$id.'-2'] == 'inferieur') {
                $_SESSION['bulleFiltre']['fa-'.$id.'-1']['titre']= $_SESSION['bulleFiltre']['fa-'.$id.'-1']['titre'].' '.$trad->t('inferieur à').' ';
            }
            
            
            $_SESSION['bulleFiltre']['fa-'.$id.'-1']['value']= $post['fa-'.$id.'-3'];
            
            if (isset($post['fa-'.$id.'-4']) && $post['fa-'.$id.'-4'] !='') {
                $_SESSION['bulleFiltre']['fa-'.$id.'-1']['value']= $_SESSION['bulleFiltre']['fa-'.$id.'-1']['value'].' et '.$post['fa-'.$id.'-4'];
            }
        }
        
        
        if ($type == 'numeric') {
            // correction dossier 30312
            // $form = new \TwigExtension\FormExtension($this->router, $this->pdo);
            $nameJquery3 = str_replace('#', '\\\#', 'fa-'.$id.'-3');
            $nameJquery4 = str_replace('#', '\\\#', 'fa-'.$id.'-4');
            $html = '  <div class="colonne4 filtreColonne4filtreAvance'.$id.'">
                        <select class="form-control form-control-sm" name="fa-'.$id.'-2" id="filtreAvance'.$id.'-2" onchange="entreDateFiltreAvance(this.value, \'filtreAvance'.$id.'\')">
                        <option value="egal"  '.(($post['fa-'.$id.'-2'] == 'egal') ? ' selected ' : '').'>'.$trad->t('égal à').'</option>
                        <option value="entre"  '.(($post['fa-'.$id.'-2'] == 'entre') ? ' selected ' : '').'>'.$trad->t('compris entre').'</option>
                        <option value="superieur"  '.(($post['fa-'.$id.'-2'] == 'superieur') ? ' selected ' : '').'>'.$trad->t('superieur à').'</option>
                        <option value="inferieur"  '.(($post['fa-'.$id.'-2'] == 'inferieur') ? ' selected ' : '').'>inferieur à</option>
                        </select>
                        <input type="hidden" name="idFiltreAvance[]" value="'.$id.'" />
                        </div>
                        <div class="colonne4 filtreColonne4filtreAvance'.$id.'">
                        <input type="text" class="form-control form-control-sm " name="fa-'.$id.'-3" value="'.$post['fa-'.$id.'-3'].'" id="input_fa-'.$id.'-3" onchange="validatorAjax(\''.$this->router->generateUri('Ajax.validator.float').'\', {\'nomChamp\': \'\', \'format\' : \''.Constante::formatMontant.'\'},\''.$nameJquery3.'\');">
                        </div>
                        <div class="colonne4 filtreColonne4filtreAvance'.$id.'" id="filtreAvance'.$id.'-4" style="'.(($post['fa-'.$id.'-2'] == 'entre') ? ' visibility:visible; ' : 'visibility:hidden;').'" >
                        <input type="text" class="form-control form-control-sm " name="fa-'.$id.'-4" value="'.$post['fa-'.$id.'-4'].'" id="input_fa-'.$id.'-4" onchange="validatorAjax(\''.$this->router->generateUri('Ajax.validator.float').'\', {\'nomChamp\': \'\', \'format\' : \''.Constante::formatMontant.'\'},\''.$nameJquery4.'\');">
                        </div>';
            
            if ($post['fa-'.$id.'-2'] == 'egal') {
                $_SESSION['bulleFiltre']['fa-'.$id.'-1']['titre']= $_SESSION['bulleFiltre']['fa-'.$id.'-1']['titre'].' '.$trad->t('égal à').' ';
            }
            if ($post['fa-'.$id.'-2'] == 'entre') {
                $_SESSION['bulleFiltre']['fa-'.$id.'-1']['titre']= $_SESSION['bulleFiltre']['fa-'.$id.'-1']['titre'].' '.$trad->t('compris entre').' ';
            }
            if ($post['fa-'.$id.'-2'] == 'superieur') {
                $_SESSION['bulleFiltre']['fa-'.$id.'-1']['titre']= $_SESSION['bulleFiltre']['fa-'.$id.'-1']['titre'].' '.$trad->t('superieur à').' ';
            }
            if ($post['fa-'.$id.'-2'] == 'inferieur') {
                $_SESSION['bulleFiltre']['fa-'.$id.'-1']['titre']= $_SESSION['bulleFiltre']['fa-'.$id.'-1']['titre'].' '.$trad->t('inferieur à').' ';
            }
            
            
            $_SESSION['bulleFiltre']['fa-'.$id.'-1']['value']= $post['fa-'.$id.'-3'];
            
            if (isset($post['fa-'.$id.'-4']) && $post['fa-'.$id.'-4'] !='') {
                $_SESSION['bulleFiltre']['fa-'.$id.'-1']['value']= $_SESSION['bulleFiltre']['fa-'.$id.'-1']['value'].' et '.$post['fa-'.$id.'-4'];
            }
        }
        
        
        if ($type == 'bool') {
            $html = ' <div class="colonne4 filtreColonne4filtreAvance'.$id.'">
                        <select class="form-control form-control-sm" name="fa-'.$id.'-2" id="filtreAvance'.$id.'-2" onchange="entreDateFiltreAvance(this.value, \'filtreAvance'.$id.'\')">
                        <option value="egal">'.$trad->t('égal à').'</option>
                        </select>
                        <input type="hidden" name="idFiltreAvance[]" value="'.$id.'" />
                        </div>
                        <div class="colonne4 filtreColonne4filtreAvance'.$id.'">
                        <select class="form-control form-control-sm" name="fa-'.$id.'-3" id="filtreAvance'.$id.'-2" onchange="entreDateFiltreAvance(this.value, \'filtreAvance'.$id.'\')">
                        <option value="1" '.(($post['fa-'.$id.'-3'] == 1) ? ' selected ' : '').'>'.$trad->t('Oui').'</option>
                        <option value="0" '.(($post['fa-'.$id.'-3'] == 0) ? ' selected ' : '').'>'.$trad->t('Non').'</option>
                        </select>
                        </div>';
            
            $_SESSION['bulleFiltre']['fa-'.$id.'-1']['titre']= $_SESSION['bulleFiltre']['fa-'.$id.'-1']['titre'].' égal à ';
            
            
            if ($post['fa-'.$id.'-3'] == 1) {
                $_SESSION['bulleFiltre']['fa-'.$id.'-1']['value']= $trad->t('Oui');
            } else {
                $_SESSION['bulleFiltre']['fa-'.$id.'-1']['value']= $trad->t('Non');
            }
        }
        
   
        if ($type == 'liste') {
            $repository = false;
            $explodeRepository = explode('-', $post['fa-'.$id.'-1'])[0] ;
            if (strpos($explodeRepository, 'repository') ===0) {
                $repository = true;
                $explodeRepository = str_replace('repository', '', $explodeRepository);
            }
            $form = new \TwigExtension\FormExtension($this->router, $this->pdo, $this->contenaire);
            $postcondition = ($repository) ? $post[$explodeRepository.'Cond'] : $post['fa-'.$id.'-2'];
            $html = '<div class="colonne4 filtreColonne4filtreAvance'.$id.'">
                        <select class="form-control form-control-sm" name="'.( ($repository) ? $explodeRepository.'Cond' : 'fa-'.$id.'-2').'" id="filtreAvance'.$id.'-2" onchange="entreDateFiltreAvance(this.value, \'filtreAvance'.$id.'\')">
                        <option value="egal"  '.(($postcondition == 'egal') ? ' selected ' : '').'>'.$trad->t('égal à').'</option>
                        <option value="different"  '.(($postcondition == 'different') ? ' selected ' : '').'>'.$trad->t('différent de').'</option>
                        </select>
                        <input type="hidden" name="idFiltreAvance[]" value="'.$id.'" />
                        </div>
                        <div class="colonne4 filtreColonne4filtreAvance'.$id.'">';
       
                  

            $arrayPath = [];

            if (strpos($zoom, 'separatorPath') !== false) {
                $tmpExplode = explode('separatorPath', $zoom);
                
                $namePath = $tmpExplode[0];
                
                
                foreach (explode('separatorParams', $tmpExplode[1]) as $valueSeparator) {
                    $valueTmpInsert = explode('separatorValue', $valueSeparator);

                    $arrayPath[$valueTmpInsert[0]] = $valueTmpInsert[1];
                }
            } else {
                $namePath = $zoom;
            }


            $html .= $form->inputZoom(
                '',
                ( ($repository) ? $explodeRepository : 'fa-'.$id.'-3'),
                $this->router->generateUri($namePath, $arrayPath),
                $titre,
                '',
                (($repository) ? $post[$explodeRepository] : $post['fa-'.$id.'-3']),
                '',
                $this->router->generateUri('Ajax.validator.zoom'),
                "{'entity' : '".$entity."','nomChamp' : '".$titre."'}"
            );
            $html .= '</div>';
            
            // a tester en cas réél
            $resultatInput2 = (($repository) ? $post[$explodeRepository.'Cond'] : $post['fa-'.$id.'-2']);
            
            if ($resultatInput2 == 'egal') {
                $_SESSION['bulleFiltre']['fa-'.$id.'-1']['titre']= $_SESSION['bulleFiltre']['fa-'.$id.'-1']['titre'].' '.$trad->t('égal à').' ';
            }
            if ($resultatInput2 == 'different') {
                $_SESSION['bulleFiltre']['fa-'.$id.'-1']['titre']= $_SESSION['bulleFiltre']['fa-'.$id.'-1']['titre'].' '.$trad->t('différent de').' ';
            }
           
             $_SESSION['bulleFiltre']['fa-'.$id.'-1']['value']=   (($repository) ? $post[$explodeRepository] : $post['fa-'.$id.'-3']);
          
            
             $repository = false;
        }
        
        return $html;
    }
    
    public function initJs($initFiltreAvance)
    {
        $html ="<script>
                           
                    newCritereActive = [];
                    choixCritere = [];
                    idCountFitreAvance=".$initFiltreAvance.";
               
					function filtreAvanceNewCritere(value, id, idNude, key)
					{
						
						if(value == 'drop')
						{
							$('#div'+id).remove();
							choixCritere[idNude] ='';
							return true;
						}
						if(!value)
						{
				  			$('#'+id+'-2').remove();
				  			$('#'+id+'-3').remove();
				  			$('#'+id+'-4').remove();
				  			$('.filtreColonne4'+id).remove();
				  			return true;
						}

						value = value.split('-');
							
					  	$.ajax({
						  	dataType : 'html',
					  		url: '".$this->router->generateUri('Ajax.facture.nouveauCritere')."',
					  		data: {'id' : id, 'idNude' : idNude, 'type' : value[1], 'nom' : value[0], 'key' : key},
					  		type: 'POST',
					  		success: function(result){
					  			$('#'+id+'-2').remove();
					  			$('#'+id+'-3').remove();
					  			$('#'+id+'-4').remove();
					  			$('.filtreColonne4'+id).remove();
					  			
					  			$('#div'+id).append(result);	
					  			$('#dropblock'+idNude).html('<span class=\"supprimer_filtre\" id=\"drop-'+idNude+'\" onclick=\"dropFiltreAvance(this.id)\"></span>');

								if(newCritereActive[idNude] != 1)
								{
									idCountFitreAvance++;
									$.ajax({
									  	dataType : 'html',
								  		url: '".$this->router->generateUri('Ajax.facture.nouveauTupleform')."',
								  		data: {'id' : idCountFitreAvance, 'key' : key},
								  		type: 'POST',
								  		success: function(result){
								  			$('#div'+id).after(result);

								  		}
									});
								}
					  				
								newCritereActive[idNude] = 1; 
								choixCritere[idNude] = value[0];
					  		}
					  	});
					}

					function entreDateFiltreAvance(value, id)
					{
						if(value == 'entre')
						{
							$('#'+id+'-4').css( 'visibility', 'visible');	
						}else
						{
							$('#'+id+'-4').css( 'visibility', 'hidden');
						}
					}

					function dropFiltreAvance(id)
					{
						id = id.split('-');
						$('#divfiltreAvance'+id[1]).remove();
					}   

            </script>";
        
        return $html;
    }
}
