<?php 
    ini_set('display_errors', 1);
    ini_set('display_startup_erros', 1);
    error_reporting(E_ALL);
    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;

    $limite_gg = 0;

    $gerenciador_responsavel = $cs->fetchQuery($cs->executeQuery(
    	"SELECT *, 
    	    (SELECT count(*) as total_users 
    	        FROM v_gerenciadores 
    	        WHERE 
    	            gerenciador_responsavel='{$id_unf}'
    	    ) as total_users
    	    
	        FROM 
	            v_gerenciadores 
	        WHERE 
	            gerenciador_responsavel='{$id_unf}'  
	        GROUP BY id")
        );
	
	$total_users = $gerenciador_responsavel[0]['total_users'] ?? 0;

	foreach($gerenciador_responsavel as $gg)
	{
	    
	    $limite_gg += (int) $gg['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;
	$profiles                = $cs->fetchQuery($cs->executeQuery("SELECT * from profiles"));
	$profiles_permitidos     = explode(";",$_SESSION['info_unf']['profiles_limitados']);
	$gerenciadoresCadastrado = 0;
	$query                   = $cs->executeQuery("SELECT count(*) as count from gerenciadores WHERE gerenciador_responsavel '{$id_unf}'");
	
	if ($cs->num_rows($query) > 0) {
	    $gerenciadoresCadastrado = $cs->fetchQuery($query)[0]['count'];
	}

	$temp_profiles = [];

	foreach($profiles as $x => $profile)
	{
	    if(in_array($profile['profile'], $profiles_permitidos))
	    {
	        array_push($temp_profiles, $profile);
	    }
	}

	if($_SESSION['info_unf']['profiles_limitados'] != "")
	{    
		$profiles = $temp_profiles;
    }

 
?>


<!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 - Cadastrar 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(__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">Cadastrar 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" id="create">
	                                	
	                                	<input name="token" value="<?= $_SESSION['tkn_log'] = $cs->setToken(); ?>" type="hidden"/>
	                                	
	                                	<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" id="login" name="login" placeholder="Login"> </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" placeholder="Senha"> </div>
	                                            <small>Senha deve ter no minimo 8 caracteres.</small>
	                                    </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" placeholder="(XX) XXXXX-XXXX"> 
	                                            
	                                        </div>
	                                        
	                                    </div>
                                        
                                        <div class="form-group">
	                                        <label class="control-label">Profiles liberados para cadastro</label>
	                                        <select class="form-control multiSelect" id="profiles" name="permitidos[]" multiple="multiple" >
											    <?php foreach($profiles as $profile):
											        
											        (empty($profile['profile_str'])) ? $p1 = $profile['profile'] : $p1 = $profile['profile_str'];   
											    ?>
											    <option class="profile" value="<?= $profile['profile']; ?>"><?= $p1; ?></option>
											<?php endforeach; ?>
											</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>

	                                    <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" value="100"> 
	                                        </div>
	                                        <input type="hidden" name="disponivel" value="<?= $disponivel; ?>"> 
	                                        <small>(Disponível: <?= (string) $disponivel; ?> usuários)</small>
	                                    </div>

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

	                                        <div class="input-group">
	                                            <div class="input-group-addon"><i class="fa fa-sitemap"></i></div>
	                                            <input type="number" class="form-control" id="limiteg" name="limiteg" min="0" placeholder="Quantidade" value="500"> 
	                                        </div>
	                                       
	                                        <small>(Disponível: <?= (string) $_SESSION['info_unf']['limite_gerenciadores']; ?> gerenciadores)</small>
	                                    </div>

                                       <!--  <input name="limiteg" type="hidden" value=" $_SESSION['info_unf']['limite_gerenciadores']; ?>"/> -->

                                        <div class="form-group">
		                                    <label for="vencimento">Vencimento</label>
		                                    <div class="input-group">
		                                        <div class="input-group-addon"><i class="ti-calendar"></i></div>
		                                        <input type="date" value="<?= date('Y-m-d'); ?>" id="vencimento" name="vencimento">
		                                    </div>
		                                </div>

		                                <div class="checkbox checkbox-success">
                                            <input id="criar_gerenciador" type="checkbox" value="1" name="criar_gerenciador">
                                            <label for="criar_gerenciador">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">
                                        	<label for="checkbox34">Pode apagar usuários</label>      
                                        <?php endif; ?>
                                        </div>  

                                        <div class="row">
		                                    <div class="col-lg-12 col-md-12 col-sm-12">
			                                    
			                                    <p class="text-muted m-b-30">Você possui no momento <b><?= $gerenciadoresCadastrado; ?></b> gerenciadores cadastrados, seu limite é de <code><?= $_SESSION['info_unf']['limite_gerenciadores']; ?></code></p>
			                                    <input type="hidden" id="total_users" name="total_users" value="<?= $total_users; ?>">
			                                </div>
		                                </div>
	             
	                                    <button type="submit" class="btn btn-success waves-effect waves-light m-r-10">Cadastrar</button>            
	                                </form>

	                                <div class="col-sm-6 col-xs-6 mx-auto message">
			                            
	                                </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>
    <!-- SELECT 2 -->   
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
    <script>

    	$(document).ready(function() {
    		
    		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
		            }
		        })()

		    var profiles = []    
    		$('.multiSelect').select2()    

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

            $('.profile').each( function(i, item) {
    
               profiles.push($(item).val())
                 	 
          	})

          	$('.multiSelect').val(profiles).trigger("change");

          	$(".btnAll").on("click", function () { 
		        $('.multiSelect').val(profiles).trigger("change");
            })  

            $(".btnClean").on("click", function () {
			    $('.multiSelect').val(null).trigger("change");
			})

			$('#create').submit( function(e) {
	            e.preventDefault()

	            let form   = $(this).serialize()
	            let action = '../ajax_create.php'
	            
	            $('.message').html('')
	            
	            $.post(action, form)
	                .done( (data) => {
	                    //console.log(data, status, im)
	                    data  = JSON.parse(data)    
	                    $('.message')
                        .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
			
			$('.phone_with_ddd').mask(SPMaskBehavior, spOptions)   

        })


        
        

    </script>
 
    
</body>

</html>