<?php

include '../config.php';

$id = trim($_GET['id']);
$lang = trim($_GET['lang']);

$stage = "PUBLISHED";

if($lang == "es"){
    $erorcaptcha = "Ingrese el captcha correctamente";
    $errorname = "Ingrese el nombre completo";
    $confirmedit = "¿Confirma cambios en el usuario?";

}

if($lang == "en"){
    $erorcaptcha = "Enter the captcha";
    $errorname = "Enter the full name";
    $confirmedit = "¿Confirm changes in the user?";

}

$correosuperior = $_COOKIE['persistPrivado'];

//echo $correo;
if(strlen($correosuperior) > 5){

    $curluser = curl_init();
    curl_setopt_array($curluser, array(
    CURLOPT_URL => $endpoint_graph_cms,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS =>'{"query":"query MyQuery {\\r\\n  usuariosSitioPrivado(where: {email: \\"'.$correosuperior.'\\"}) {\\r\\n    id\\r\\n  resetPass\\r\\n fechaCambioPassword\\r\\n nombre\\r\\n  empresa\\r\\n  permisos\\r\\n  rol\\r\\n  tycAceptados\\r\\n  }\\r\\n}\\r\\n","variables":{}}',
    CURLOPT_HTTPHEADER => array(
      'Content-Type: application/json',
      'Cookie: __cfduid=da2693cdfd39b7377a8a05e305da45b8f1613001694'
    ),
  ));

  $responseuser = curl_exec($curluser);
  $_SESSION['requestDataUser'] = $responseuser;
  curl_close($curluser);

  $jsonrespuestauser = json_decode($responseuser, true);
  $permisossuperior = $jsonrespuestauser['data']['usuariosSitioPrivado'][0]['permisos'];

}

//echo $permisossuperior;



//echo $id;

$curl = curl_init();

  curl_setopt_array($curl, array(

	CURLOPT_URL => $endpoint_graph_cms,

	CURLOPT_RETURNTRANSFER => true,

	CURLOPT_ENCODING => '',

	CURLOPT_MAXREDIRS => 10,

	CURLOPT_TIMEOUT => 0,

	CURLOPT_FOLLOWLOCATION => true,

	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,

	CURLOPT_CUSTOMREQUEST => 'POST',

	CURLOPT_POSTFIELDS =>'{"query":"query MyQuery {\\r\\n  usuarioSitioPrivado(where: {id: \\"'.$id.'\\"}, stage: '.$stage.') {\\r\\n    id\\r\\n  email\\r\\n   empresa\\r\\n  area\\r\\n   funcion\\r\\n    rol\\r\\n    nombre\\r\\n    localizations {\\r\\n      email\\r\\n  empresa\\r\\n  area\\r\\n   funcion\\r\\n   rol\\r\\n      nombre\\r\\n     permisos\\r\\n    }\\r\\n  }\\r\\n}","variables":{}}',

	CURLOPT_HTTPHEADER => array(

	  'Content-Type: application/json',

	  'Cookie: __cfduid=da2693cdfd39b7377a8a05e305da45b8f1613001694'

	),

  ));

$response = curl_exec($curl);



curl_close($curl);

//echo $response;



$jsonrespuesta = json_decode($response, true);

$id = $jsonrespuesta['data']['usuarioSitioPrivado']['id'];



$nombre = $jsonrespuesta['data']['usuarioSitioPrivado']['localizations'][0]['nombre'];



$empresa = $jsonrespuesta['data']['usuarioSitioPrivado']['localizations'][0]['empresa'];

$area = $jsonrespuesta['data']['usuarioSitioPrivado']['localizations'][0]['area'];

$funcion = $jsonrespuesta['data']['usuarioSitioPrivado']['localizations'][0]['funcion'];



$email = $jsonrespuesta['data']['usuarioSitioPrivado']['localizations'][0]['email'];



$rol = $jsonrespuesta['data']['usuarioSitioPrivado']['localizations'][0]['rol'];

//echo $rol;



$permisos = $jsonrespuesta['data']['usuarioSitioPrivado']['localizations'][0]['permisos'];

$permisos = trim($permisos);

$permisos = preg_replace('/\s+/', '', $permisos);

//echo $permisos;



?>



<?php

if($lang == 'en'){

?>


<form id="formEditUser">



<div class="group">

    <input class="forminput" id="usuario_nombre_edit" type="text" value="<?php echo $nombre;?>"><span class="highlight"></span><span class="bar"></span>

    <label>Full name</label>

</div>



<div class="group">

    <input disabled class="forminput" id="usuario_email_edit" type="email" value="<?php echo $email;?>" style="color: #2b4365; border-bottom: 0; border-bottom: 1px solid #fafafa;"><span class="highlight"></span><span class="bar"></span>

    <label>Email</label>

</div>





<div class="group">

    <input class="forminput" id="usuario_area_edit" type="text" value="<?php echo $area;?>"><span class="highlight"></span><span class="bar"></span>

    <label>Area</label>

</div>



<div class="group">

    <input class="forminput" id="usuario_funcion_edit" type="text" value="<?php echo $funcion;?>"><span class="highlight"></span><span class="bar"></span>

    <label>Role in the Company</label>

</div>


<div class="group desc" data-superior ="<?php echo  $permisossuperior;?>"  data-permisos ="<?php echo  $permisos;?>"  id="permisoslistedit">
			
			<h4 >Access permissions*</h4>

			<?php

				if(strlen($_SESSION['permisosPrivedit'])>90 && strlen($_COOKIE['persistID'])<2)
				{
					$responseactionCards = $_SESSION['permisosPrivedit'];
					//echo $_SESSION['permisosPriv'];
				}
				else{
					$curl = curl_init();
					curl_setopt_array($curl, array(
					CURLOPT_URL => $endpoint_graph_cms,
					CURLOPT_RETURNTRANSFER => true,
					CURLOPT_ENCODING => '',
					CURLOPT_MAXREDIRS => 10,
					CURLOPT_TIMEOUT => 0,
					CURLOPT_FOLLOWLOCATION => true,
					CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
					CURLOPT_CUSTOMREQUEST => 'POST',
					CURLOPT_POSTFIELDS =>'{"query":"query MyQuery {\\r\\n  actionCardsCumplimiento( stage: PUBLISHED, where: {estatus_not_contains: \\"eliminado\\"AND: {privado: \\"1\\"}}) {\\r\\n    archivo\\r\\n    enlace\\r\\n   layout\\r\\n   slug\\r\\n  estatus\\r\\n    id\\r\\n    nuevaPestana\\r\\n    texto\\r\\n    textoDelBoton\\r\\n    titulo\\r\\n    localizations {\\r\\n      archivo\\r\\n      enlace\\r\\n      enviadoRevision\\r\\n      layout\\r\\n   slug\\r\\n  estatus\\r\\n      id\\r\\n      nuevaPestana\\r\\n      texto\\r\\n      textoDelBoton\\r\\n      titulo\\r\\n    }\\r\\n  }\\r\\n}\\r\\n","variables":{}}',
					CURLOPT_HTTPHEADER => array(
						'Content-Type: application/json',
						'Cookie: __cfduid=da2693cdfd39b7377a8a05e305da45b8f1613001694'
					),
					));
				$responseactionCards = curl_exec($curl);
				$_SESSION['permisosPrivedit'] = $responseactionCards;
				curl_close($curl);
				}

				//echo $responseactionCards;
				$arrayactionCards = json_decode($responseactionCards, true);

				foreach ($arrayactionCards['data']['actionCardsCumplimiento'] as $item) {


					foreach ($item['localizations'] as $subitem) {

                        $pos_permisos = strpos($permisossuperior, $item['slug']);

                        
                            
                        if ($pos_permisos === false) {
                            //echo '<input type="checkbox" name="permisos[]" value="'.$subitem['slug'].'"/>'.urldecode($subitem['titulo']).'<br>';
                        }
                        else{
                            $pos_permisos2 = strpos($permisos, $subitem['slug']);
                                
                            if ($pos_permisos2 === false) {
                                echo '<input type="checkbox" name="permisos[]" value="'.$subitem['slug'].'"/>'.urldecode($item['titulo']).'<br>';
                            }
                            else{
                                echo '<input type="checkbox" name="permisos[]" value="'.$subitem['slug'].'" checked/>'.urldecode($item['titulo']).'<br>';
                            }
                            //echo $permisos; echo $subitem['slug'];
                            //echo '<input type="checkbox" name="permisos[]" value="'.$subitem['slug'].'" checked/>'.urldecode($subitem['titulo']).'<br>';

                            
                        }

						
						
					}
				

				}
				?><br>
		</div>







<div class="group">

        <input class="forminput" type="text" name="captchaedituser" id="captchaedituser"/><span class="highlight"></span><span class="bar"></span>

        <label>Captcha</label>

        <div id="respuestacaptchaedituser"></div>

        

</div>



<div class="group">

        

        <p><img src="/assets/captcha/2.php?rand=<?php echo rand(); ?>" id='captcha_image_edituser'></p>

        <p> <a href='javascript: reloadCaptcha("edituser");'> Reload</a></p>

</div>







<div id="respuestaedituser" style="float:left;width:100%;"></div>



<button id="btnedituser" type="button" class="button buttonBlue" onclick="saveEditUser();">Save

    <div class="ripples buttonRipples"><span class="ripplesCircle"></span></div>

</button>









</form>



<?php

}

else{ 

?>

<form id="formEditUser">



<div class="group">

    <input class="forminput" id="usuario_nombre_edit" type="text" value="<?php echo $nombre;?>"><span class="highlight"></span><span class="bar"></span>

    <label>Nombre completo</label>

</div>



<div class="group">

    <input disabled class="forminput" id="usuario_email_edit" type="email" value="<?php echo $email;?>" style="color: #2b4365; border-bottom: 0; border-bottom: 1px solid #fafafa;"><span class="highlight"></span><span class="bar"></span>

    <label>Email</label>

</div>





<div class="group">

    <input class="forminput" id="usuario_area_edit" type="text" value="<?php echo $area;?>"><span class="highlight"></span><span class="bar"></span>

    <label>Área</label>

</div>



<div class="group">

    <input class="forminput" id="usuario_funcion_edit" type="text" value="<?php echo $funcion;?>"><span class="highlight"></span><span class="bar"></span>

    <label>Función que desempeña</label>

</div>


<div class="group desc" data-superior ="<?php echo  $permisossuperior;?>"  data-permisos ="<?php echo  $permisos;?>"  id="permisoslistedit">
			
			<h4 >Permisos de acceso*</h4>

			<?php

				if(strlen($_SESSION['permisosPrivedit'])>90 && strlen($_COOKIE['persistID'])<2)
				{
					$responseactionCards = $_SESSION['permisosPrivedit'];
					//echo $_SESSION['permisosPriv'];
				}
				else{
					$curl = curl_init();
					curl_setopt_array($curl, array(
					CURLOPT_URL => $endpoint_graph_cms,
					CURLOPT_RETURNTRANSFER => true,
					CURLOPT_ENCODING => '',
					CURLOPT_MAXREDIRS => 10,
					CURLOPT_TIMEOUT => 0,
					CURLOPT_FOLLOWLOCATION => true,
					CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
					CURLOPT_CUSTOMREQUEST => 'POST',
					CURLOPT_POSTFIELDS =>'{"query":"query MyQuery {\\r\\n  actionCardsCumplimiento( stage: PUBLISHED, where: {estatus_not_contains: \\"eliminado\\"AND: {privado: \\"1\\"}}) {\\r\\n    archivo\\r\\n    enlace\\r\\n   layout\\r\\n   slug\\r\\n  estatus\\r\\n    id\\r\\n    nuevaPestana\\r\\n    texto\\r\\n    textoDelBoton\\r\\n    titulo\\r\\n    localizations {\\r\\n      archivo\\r\\n      enlace\\r\\n      enviadoRevision\\r\\n      layout\\r\\n   slug\\r\\n  estatus\\r\\n      id\\r\\n      nuevaPestana\\r\\n      texto\\r\\n      textoDelBoton\\r\\n      titulo\\r\\n    }\\r\\n  }\\r\\n}\\r\\n","variables":{}}',
					CURLOPT_HTTPHEADER => array(
						'Content-Type: application/json',
						'Cookie: __cfduid=da2693cdfd39b7377a8a05e305da45b8f1613001694'
					),
					));
				$responseactionCards = curl_exec($curl);
				$_SESSION['permisosPrivedit'] = $responseactionCards;
				curl_close($curl);
				}

				//echo $responseactionCards;
				$arrayactionCards = json_decode($responseactionCards, true);

				foreach ($arrayactionCards['data']['actionCardsCumplimiento'] as $item) {


					foreach ($item['localizations'] as $subitem) {

                        $pos_permisos = strpos($permisossuperior, $item['slug']);

                        
                            
                        if ($pos_permisos === false) {
                            //echo '<input type="checkbox" name="permisos[]" value="'.$subitem['slug'].'"/>'.urldecode($subitem['titulo']).'<br>';
                        }
                        else{
                            $pos_permisos2 = strpos($permisos, $subitem['slug']);
                                
                            if ($pos_permisos2 === false) {
                                echo '<input type="checkbox" name="permisos[]" value="'.$subitem['slug'].'"/>'.urldecode($subitem['titulo']).'<br>';
                            }
                            else{
                                echo '<input type="checkbox" name="permisos[]" value="'.$subitem['slug'].'" checked/>'.urldecode($subitem['titulo']).'<br>';
                            }
                            //echo $permisos; echo $subitem['slug'];
                            //echo '<input type="checkbox" name="permisos[]" value="'.$subitem['slug'].'" checked/>'.urldecode($subitem['titulo']).'<br>';

                            
                        }

						
						
					}
				

				}
				?><br>
		</div>







<div class="group">

        <input class="forminput" type="text" name="captchaedituser" id="captchaedituser"/><span class="highlight"></span><span class="bar"></span>

        <label>Captcha</label>

        <div id="respuestacaptchaedituser"></div>

        

</div>



<div class="group">

        

        <p><img src="/assets/captcha/2.php?rand=<?php echo rand(); ?>" id='captcha_image_edituser'></p>

        <p> <a href='javascript: reloadCaptcha("edituser");'> Recargar</a></p>

</div>







<div id="respuestaedituser" style="float:left;width:100%;"></div>



<button id="btnedituser" type="button" class="button buttonBlue" onclick="saveEditUser();">Guardar

    <div class="ripples buttonRipples"><span class="ripplesCircle"></span></div>

</button>









</form>

<?php

} 

?>





<style>

    #formEditUser {

        width: 100%;

        margin: 10px auto;

        padding: 3em 2em 2em 2em;

        background: #fafafa;

        /* min-width: 1500px; */

        border-radius: 10px;

        font-size: 12px;

        font-family: "Montserrat";

    }

    #formEditUser .group {

        position: relative;

        margin-bottom: 35px;

        width: 50%;

        float: left;

        padding: 15PX;

    }



    #formEditUser input, #formEditUser textarea  {

        font-size: 18px;

        padding: 10px 10px 10px 5px;

        -webkit-appearance: none;

        display: block;

        background: #fafafa;

        color: #636363;

        width: 100%;

        border: none;

        border-radius: 0;

        border-bottom: 1px solid #757575;

    }



    #formEditUser input:focus { outline: none; }





    /* Label */



    #formEditUser label {

        color: #999;

        font-size: 12px;

        font-weight: normal;

        position: absolute;

        pointer-events: none;

        left: 5px;

        top: 0px;

        transition: all 0.2s ease;

    }





    /* active */



    #formEditUser input:focus ~ label, #formEditUser input.used ~ label, #formEditUser textarea:focus ~ label, #formEditUser textarea.used ~ label  {

        top: -20px;

    transform: scale(.75); left: -2px;

        /* font-size: 14px; */

        color: #2b4365;

    }





    /* Underline */



    #formEditUser .bar {

        position: relative;

        display: block;

        width: 100%;

    }



    #formEditUser .bar:before, #formEditUser .bar:after {

        content: '';

        height: 2px; 

        width: 0;

        bottom: 1px; 

        position: absolute;

        background: #2b4365; 

        transition: all 0.2s ease;

    }



    #formEditUser .bar:before { left: 50%; }



    #formEditUser .bar:after { right: 50%; }





    /* active */



    #formEditUser input:focus ~ .bar:before, #formEditUser input:focus ~ .bar:after { width: 50%; }





    /* Highlight */



    #formEditUser .highlight {

        position: absolute;

        height: 60%; 

        width: 100px; 

        top: 25%; 

        left: 0;

        pointer-events: none;

        opacity: 0.5;

    }





    /* active */



    #formEditUser input:focus ~ .highlight {

        animation: inputHighlighter 0.3s ease;

    }





    /* Animations */



    @keyframes inputHighlighter {

        from { background: #2b4365; }

        to 	{ width: 0; background: transparent; }

    }





    /* Button */



    #formEditUser .button {

    position: relative;

    display: inline-block;

    padding: 12px 24px;

    margin: .3em 0 1em 0;

    width: 100%;

    vertical-align: middle;

    color: #fff;

    font-size: 16px;

    line-height: 20px;

    -webkit-font-smoothing: antialiased;

    text-align: center;

    letter-spacing: 1px;

    background: transparent;

    border: 0;

    border-bottom: 2px solid #48aa42;

    cursor: pointer;

    transition: all 0.15s ease;

    }

    #formEditUser .button:focus { outline: 0; }





    /* Button modifiers */



    #formEditUser .buttonBlue {

    background: #2b4365;

    text-shadow: 1px 1px 0 #48aa42;

    }



    #formEditUser .buttonBlue:hover { background: #48aa42; }





    /* Ripples container */



    #formEditUser .ripples {

    position: absolute;

    top: 0;

    left: 0;

    width: 100%;

    height: 100%;

    overflow: hidden;

    background: transparent;

    }





    /* Ripples circle */



    #formEditUser .ripplesCircle {

    position: absolute;

    top: 50%;

    left: 50%;

    transform: translate(-50%, -50%);

    opacity: 0;

    width: 0;

    height: 0;

    border-radius: 50%;

    background: rgba(255, 255, 255, 0.25);

    }



    #formEditUser .ripples.is-active .ripplesCircle {

    animation: ripples .4s ease-in;

    }

    #formEditUser input[type="checkbox"] {
        width: 30px;
        padding: 0;
        border: 1px solid #222;
        -webkit-appearance: auto;
        display: inline-block;
    }

    #permisoslistedit h4 {
        font-size: 15px;
        margin-bottom: 10px;
        display: inline-block;
        width: 100%;
    }



    @media(max-width:600px){

        #formEditUser .group {

            width: 100%;

            padding: 0;

        }

    }


</style>



<script>

    function saveEditUser(){


        id = "<?php echo $id;?>";

        $('#respuestaedituser').html('');

        $('#formEditUser input').css("border-color", "none");



        var data=new FormData($("#formEditUser")[0]);



        $("#btnedituser").css("pointer-events", "none");

        $("#btnedituser").css("opacity", ".5");

        var nombre = encodeURIComponent($("#usuario_nombre_edit").val());

        var area = encodeURIComponent($("#usuario_area_edit").val());

        var funcion = encodeURIComponent($("#usuario_funcion_edit").val());

        var captchaedituser = $("#captchaedituser").val();

        var permisosedit = new Array();
        $("#permisoslistedit input:checked").each(function() {
            permisosedit.push($(this).val());
        });



        var errors = false;



        if(nombre.length <4){

            errors = true;

            $('#respuestaedituser').append('<p class="errormsg"><?php echo $errorname;?></p>');

            $("#usuario_nombre").css("border-color", "#fa5555");

        }



        if(captchaedituser.length <4){

            errors = true;

            $('#respuestaedituser').append('<p class="errormsg"><?php echo $erorcaptcha;?></p>');

            $("#captcha3").css("border-color", "#fa5555");

        }



        if(errors == true){

            setTimeout(() => {

                $("#btnedituser").css("pointer-events", "inherit");

                $("#btnedituser").css("opacity", "1");

            }, 2000);

        }



        else{

            if(confirm("<?php echo $confirmedit;?>")){
                $.ajax({

                    url: "/include/updateUsuario.php?nombre="+nombre+"&area="+area+"&funcion="+funcion+"&id="+id+"&permisos="+permisosedit+"&lang=<?php echo $lang;?>",

                    type:"POST",

                    data:data,

                    processData: false,

                    contentType: false,

                    success:function(data){

                        $('#respuestaedituser').html(data);

                        setTimeout(() => {

                            $("#btnedituser").css("pointer-events", "inherit");

                            $("#btnedituser").css("opacity", "1");

                        }, 2000);

                    }



                });
            }
            else{
                return false;
            }



        } 



    }

</script>