<?php 

    require_once(__DIR__."/../../config.php");
    
    $cs = new cs;

    if(!$cs->checkLog_unf()) { exit("<script>location='../../login';</script>"); }

    $info_unf             = $_SESSION['info_unf'];

	$id_unf               = $_SESSION['info_unf']['id'];

	list($info_unf)       = $cs->fetchQuery($cs->executeQuery("SELECT * from gerenciadores WHERE id='$id_unf'"));



	$_SESSION['info_unf'] = $info_unf;
 
	//var_dump($_SESSION, ' SESSAO ');
	$gerenciador_filho = $cs->fetchQuery($cs->executeQuery("SELECT * from gerenciadores WHERE gerenciador_responsavel='$id_unf' AND id!='".$_GET['id']."'"));
	//var_dump($gerenciador_filho); exit;
	$limite_gg = 0;
	
	foreach($gerenciador_filho as $value)
	{
	    $limite_gg += (int) $value['limite_usuarios'];
	}
	
	$max = max((int) $_SESSION['info_unf']['limite_users_gerenciadores'], $limite_gg);
	$min = min((int) $_SESSION['info_unf']['limite_users_gerenciadores'], $limite_gg); 
	$disponivel = $max - $min;
    
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" type="image/png" sizes="16x16" href="<?= SITE_PAINEL; ?>/plugins/images/favicon.png">
    <title>Space Code 2.0 - Editar Gerenciador</title>
    <!-- Bootstrap Core CSS -->
    <link href="../../public/assets/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="../../plugins/bower_components/bootstrap-extension/css/bootstrap-extension.css" rel="stylesheet">
    <!-- Menu CSS -->
    <link href="../../plugins/bower_components/sidebar-nav/dist/sidebar-nav.min.css" rel="stylesheet">
    <!-- toast CSS -->
    <link href="../../plugins/bower_components/toast-master/css/jquery.toast.css" rel="stylesheet">
    <!-- morris CSS -->
    <link href="../../plugins/bower_components/morrisjs/morris.css" rel="stylesheet">
    <!-- animation CSS -->
    <link href="../../public/assets/css/animate.css" rel="stylesheet">
    <!-- Custom CSS -->
    <link href="../../public/assets/css/style.css" rel="stylesheet">
    <!-- color CSS -->
    <link href="../../public/assets/css/colors/default-dark.css" id="theme" rel="stylesheet">
    <!-- dataTable CSS -->
    <!--  <link rel="stylesheet" href="<//?= BASE_URL; ?>/painel/plugins/bower_components/datatables/jquery.dataTables.min.css"> -->

    <!-- Editable CSS -->
    <link rel="stylesheet" href="../../plugins/bower_components/jquery-datatables-editable/datatables.css">
    
    <!-- SELECT 2 --> 
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
    <!-- DATAPICKER --> 
    <link href="../../plugins/bower_components/bootstrap-datepicker/bootstrap-datepicker.min.css" rel="stylesheet">
    <!-- SWEETALERT --> 
    <link href="../../plugins/bower_components/sweetalert/sweetalert.css">
    

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
    <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
    <!-- <script>
    (function(i, s, o, g, r, a, m) {
        i['GoogleAnalyticsObject'] = r;
        i[r] = i[r] || function() {
            (i[r].q = i[r].q || []).push(arguments)
        }, i[r].l = 1 * new Date();
        a = s.createElement(o), m = s.getElementsByTagName(o)[0];
        a.async = 1;
        a.src = g;
        m.parentNode.insertBefore(a, m)
    })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
    ga('create', 'UA-19175540-9', 'auto');
    ga('send', 'pageview');
    </script> -->
    
</head>
<?php
    //include_once("../layout/head.php");  
    include_once(__DIR__."/../../layout/header.php");
    include_once(__DIR__."/../../layout/left-sidebar.php"); 
    include_once(__DIR__."/../../layout/breadcrumbs.php");
?>   
	    <!-- Page Content -->
	    <div id="page-wrapper">
	        <div class="container-fluid">
	            <div class="row bg-title">
	                <div class="col-lg-3 col-md-4 col-sm-4 col-xs-12">
	                    <h4 class="page-title">Editar Gerenciador</h4></div>
	                <div class="col-lg-9 col-sm-8 col-md-8 col-xs-12"> 
	                    <?php echo breadcrumbs(); ?>
	                </div>
	                <!-- /.col-lg-12 -->
	            </div>

				<div class="row">
				    <div class="col-md-12">
	                    <div class="white-box">
	                        
	                        <div class="row">
	                            <div class="col-sm-12 col-xs-12">
                                
	                                <form method="post" enctype="multipart/form-data">	                                	
	                                    <input id="token" name="token" value="<?= $_SESSION['tkn_log'] = $cs->setToken(); ?>" type="hidden"/>
	                                	<input type="hidden" name="id" value="<?= $_GET['id']; ?>">	
	                                	<div class="form-group">
	                                        <label for="login">Login</label>
	                                        <div class="input-group">
	                                            <div class="input-group-addon"><i class="ti-id-badge" ></i></div>
	                                            <input type="text" class="form-control" name="login" id="login" readonly="readonly"> 
	                                        </div>
	                                    </div>

	                                	<div class="form-group">
	                                        <label for="senha">Senha</label>
	                                        <div class="input-group">
	                                            <div class="input-group-addon"><i class="ti-lock"></i></div>
	                                            <input type="text" class="form-control" id="senha" name="senha" > 
	                                        </div>
	                                    </div>
	                                    
	                                    <div class="form-group">
	                                        <label for="email">Email</label>
	                                        <div class="input-group">
	                                            <div class="input-group-addon"><i class="ti-email"></i></div>
	                                            <input type="email" class="form-control" id="email" name="email" placeholder="Email"> </div>
	                                    </div>

	                                    <div class="form-group">
	                                        <label for="celular">Celular</label>
	                                        <div class="input-group">
	                                            <div class="input-group-addon"><i class="fa fa-phone fa-lg"></i></div>
	                                            <input type="text" class="form-control phone_with_ddd" id="celular" name="celular" > 
                                                
	                                        </div>
	                                        

	                                    </div>

	                                    
	                                    <div class="form-group">
	                                        <label class="control-label">Profiles liberados para cadastro</label>
	                                        <select class="form-control multiSelect" id="profilesPermitidos" name="profilesPermitidos[]" multiple="multiple" >
											    
											</select>
											<button type="button" class="btn btn-sm btn-default btnClean m-t-10" aria-label="Limpe a selecao">Limpar</button>
											<button type="button" class="btn btn-sm btn-default btnAll m-t-10" aria-label="Selecione todos">Selecionar todos</button>
	                                    </div>
                                        <?php if (cs::isAdmin()): ?> 
	                                    <div class="form-group" > 
											<label class="control-label">Vencimento do gerenciador:</label>
											<input type="date" class="form-control" name="vencimento" id="vencimento" >
	                                    </div>
	                                    <?php endif ?>  

	                                    <div class="form-group">
	                                        
	                                        <label for="limite">Limite de Usuários: </label>

	                                        <div class="input-group">
	                                            <div class="input-group-addon"><i class="ti-user"></i></div>
	                                            <input type="number" class="form-control" id="limite" name="limite" min="0" placeholder="Quantidade"> 
	                                        </div>
	                                        <small>(Disponível: <?= (string) $disponivel; ?> usuários)</small>
	                                    </div>

	                                    <div class="form-group">
	                                        
	                                        <label for="limiteg">Limite de Gerenciadores: </label>

	                                        <div class="input-group">
	                                            <div class="input-group-addon"><i class="ti-user"></i></div>
	                                            <input type="number" class="form-control" id="limiteg" name="limiteg" min="0" placeholder="Quantidade"> 
	                                        </div>
	                                        <small>(Disponível: <?= (string) $limite_gg; ?> gerenciadores)</small>
	                                    </div>

	                                    <div class="form-group">
	                                        <label class="control-label">Status</label>
	                                        <select name="status" id="status" class="form-control">
	                                            <option value="normal">Ativado</option>
	                                            <option value="desativado">Desativado</option>
	                                        </select>
	                                    </div>

	                                    <div class="form-group">

		                                    <label class="control-label">Observações</label>
		                                   
		                                    <textarea class="form-control" id="obs" name="obs" cols="100" rows="8"></textarea>		                                    
		                                </div>

	                                    <div class="checkbox checkbox-success">
                                            <input id="criar_gerenciador" type="checkbox" name="criar_gerenciador" value="sim">
                                            <label for="checkbox34">Pode criar gerenciadores</label>

                                        
                                        </div>

                                        <div class="checkbox checkbox-success">
                                        <?php if($_SESSION['info_unf']['apagar_usuarios'] == '1'): ?>
                                        	<input type="checkbox" value='sim' name="apagar_usr" id="apagar_usr">
                                        	<label for="checkbox34">Pode apagar usuários</label>
                                        <?php endif; ?>
                                        </div>
	                                    
	                                    <button id="manageEdit" type="submit" class="btn btn-success waves-effect waves-light m-r-10">Atualizar</button>  
	                                    <button id="manageDelete" type="button" class="btn btn-danger waves-effect waves-light m-r-10">Apagar gerenciador</button>  
	                                    <button type="button" onclick="window.history.back()" class="btn btn-info waves-effect waves-light m-r-10">Voltar</button>        
	                                </form>
	                                    
	                                       
                                        
	                                <div class="col-sm-6 col-xs-6 mx-auto alertmsg" style="margin-top: 20px;">
			                            <div id="alertMessage" class="alert alert-dismissable text-center" style="display: none;">
		                                    <button type="button " class="close" data-dismiss="alert" aria-hidden="true">×</button><p></p> 
		                                </div>
	                                </div> 
	                                
	                            </div>
	                            
	                        </div>
	                    </div>
	                </div>
				</div>
	        <?php include_once(__DIR__.'/../../layout/right-sidebar.php');?>
	        </div>
	        <!-- /.container-fluid -->
	        <?php include_once(__DIR__.'/../../layout/footer.php');?>
	    </div>
	    <!-- /#page-wrapper -->
    </div>
    <!-- /#wrapper -->
    <!-- jQuery -->
    <script src="../../plugins/bower_components/jquery/dist/jquery.min.js"></script>
    <!-- Bootstrap Core JavaScript -->
    <script src="../../public/assets/bootstrap/dist/js/tether.min.js"></script>
    <script src="../../public/assets/bootstrap/dist/js/bootstrap.min.js"></script>
    
    <script src="../../plugins/bower_components/bootstrap-extension/js/bootstrap-extension.min.js"></script>
    <!-- Menu Plugin JavaScript -->
    <script src="../../plugins/bower_components/sidebar-nav/dist/sidebar-nav.min.js"></script>
    <!--slimscroll JavaScript -->
    <script src="../../public/assets/js/jquery.slimscroll.js"></script>
    <!--Wave Effects -->
    <script src="../../public/assets/js/waves.js"></script>
    <!-- Custom Theme JavaScript -->
    <script src="../../public/assets/js/custom.min.js"></script>
    <!-- jQuery Mask -->
    <script src="../../plugins/bower_components/jquery-mask/dist/jquery.mask.min.js"></script>
    <!--Style Switcher -->
    <script src="../../plugins/bower_components/styleswitcher/jQuery.style.switcher.js"></script>
    <!--Sweet Alert -->
    <script src="../../plugins/bower_components/sweetalert/sweetalert.min.js"></script>
      
    <!--Functions Js -->
    <script src="../../public/assets/js/functions.js"></script>
     <!-- SELECT 2 -->   
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
    
    <script>
        
    	jQuery.browser = {};
        (function () {
            jQuery.browser.msie = false
            jQuery.browser.version = 0
            if (navigator.userAgent.match(/MSIE ([0-9]+)\./)) {
                jQuery.browser.msie = true
                jQuery.browser.version = RegExp.$1
            }
        })()
            


		$(document).ready( function() {
			
			try {

				$('.multiSelect').select2()
				var url = (window.location).href
				var id  = url.substring(url.lastIndexOf('=') + 1)

				function confirmar(texto, callback1, callback2){
				    var confirmacao = confirm(texto);
				    if (confirmacao) callback1(); // executa a primeira função de "OK"
				    else callback2(); // executa a segunda função se "Cancelar"
				}

				function apagar(){
					confirmar(
					    "Deseja excluir?",
					    function(){
					      manageDelete()
					      alert("Excluido!");
					    },
					    function(){
					      alert("Não excluido!"); 
					    }
					)  
				}
	            
	             	
				$.get("../ajax_search.php?id="+id, function(data) {
						  			    
					
				    data = JSON.parse(data)

				    

		               
		    	    var profilesLimitados  = data[0].profiles_limitados
		    	    
			    	var profilesPermitidos = profilesLimitados.split(";")
                   
                    if (parseInt(data[0].criar_gerenciador) == 1) { 
                    	$('#criar_gerenciador').attr('checked', true) 
                    } else {
                    	$('#criar_gerenciador').attr('checked', false) 
                    }

                    if (parseInt(data[0].apagar_usuarios) == 1) { 
                    	$('#apagar_usr').attr('checked', true) 
                    } else {
                    	$('#apagar_usr').attr('checked', false) 
                    }

                    //console.log(data[0])
				    	   
				    $('#login').val(data[0].login)
				    $('#senha').val(data[0].senha)
				    $('#email').val(data[0].email)
				    $('#celular').val(data[0].celular)
				    $('#limite').val(parseInt(data[0].limite_usuarios))
				    $('#vencimento').val(new Date(data[0].vencimento).toISOString().slice(0,10))
				    $('#profilesPermitidos').val(data[0].profile)
				    $('#limiteg').val(data[0].limite_gerenciadores)
				    $('#status').val(data[0].status)
				    $('#obs').val(data[0].observacoes)

                    $(profilesPermitidos).each( function(i, item) {
		                
		                $(".btnAll").on("click", function () { 
					        $('.multiSelect').val(profilesPermitidos).trigger("change");
			            })    	

		                $("#profilesPermitidos").append( $('<option>', { 
		              	        value: item.profile,
		              	        text : item,
		              	        selected: true    
	                         
		              	    }
		              	    
		              	)) 
	              	})

	              	$('.phone_with_ddd').mask(SPMaskBehavior, spOptions)
				}) // End GET REQUEST
			
			
			
				var allProfiles = getProfiles()
				
				var form = $('form').serializeArray()			      
				
				function getProfiles() {
		            return $.ajax({
		            	url: "../../getProfiles.php"  
					})
				}
	        
			    allProfiles.success( (data) => {
			        $(JSON.parse(data)).each( function( index, value ) {

		                $("#profile" ).append( $('<option>', { 
		              	    value: value.profile,
		              	    text: 
		              	        (value.profile_str !== '') ? 
		              	        value.profile_str : 
		              	        value.profile 

		              	}))        
					})		
			    })

				
				
	            var SPMaskBehavior = function (val) {
				  return val.replace(/\D/g, '').length === 10 ? '(00) 0000-00000' : '(00) 00000-0009'
				},
				spOptions = {
				  onKeyPress: function(val, e, field, options) {
				      field.mask(SPMaskBehavior.apply({}, arguments), options)
				    }
				}

				$('#manageEdit').click( function(e) {
	                e.preventDefault()
	                
	                $.post('../ajax_edit.php', $('form').serializeArray())
	                .done( (data) => {
	                    $('.alertmsg').html('')
	                    data = JSON.parse(data)
	                    $('.alertmsg')
                        .html(`<div id="alertMessage" class="alert ${data.class} alert-dismissable text-center">
                                <button type="button " class="close" data-dismiss="alert" aria-hidden="true">×</button><p>${data.text}</p> 
                            </div>`)
		            }) 
		            
		        }) // End Form Submit
	            
	            $('#manageDelete').click( function () {
 
				    apagar()
	            }) 

	            function manageDelete() {

	             	form.push({name: 'login_us', value: $('#login').val()})
	            	
	            	$.post('../ajax_delete.php', form)
	                .done( (data) => {
	                    
	                    window.history.back()
	                })  
	            }

		        $(".btnClean").on("click", function () {
				    $('.multiSelect').val(null).trigger("change")
				}) 
		    } catch(e) {
		        $('.alertmsg').html(`<div id="alertMessage" class="alert alert-danger alert-dismissable text-center">
		            <button type="button " class="close" data-dismiss="alert" aria-hidden="true">×</button><p>${e.message} - ${e.name}</p></div>`)  
		    }     
	    })	
    </script>

    
</body>

</html>