<?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;

	if(!isset($_SESSION['token_validar'])) {
	    $_SESSION['token_validar'] = md5(rand());
	}
	$total_users = (string) $cs->num_rows($cs->executeQuery("SELECT * from usuarios WHERE id_gerenciador='$id_unf'"));


	$profiles = $cs->fetchQuery($cs->executeQuery("SELECT * from profiles"));
	$profiles_permitidos = explode(";",$_SESSION['info_unf']['profiles_limitados']);
	$temp_profiles=array();
	foreach($profiles as $x=>$profile)
	{
	    if(in_array($profile['profile'],$profiles_permitidos))
	    {
	        $temp_profiles[]=$profile;
	    }
	}
  
	if($_SESSION['info_unf']['profiles_limitados'] != "") {
	    $profiles = $temp_profiles;
	}
?>

<!DOCTYPE html>
<html lang="pt-BR">

<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; ?>/beta/plugins/images/favicon.png">
    <title>Space Code 2.0 - Cadastrar Usuario</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 usuario</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 class="stdform" id="create" method="post">
	                                	<input type="hidden" name="profile_id" id="profile_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" placeholder="Clique em GERAR LOGIN e SENHA" 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" placeholder="Clique em GERAR LOGIN e SENHA" readonly="readonly"> 
	                                        </div>
	                                    </div>
	                                    <button type="button" id="createLg" class="btn btn-success waves-effect waves-light m-r-10 m-b-20">Gerar Login e Senha</button>
	                                    
	                                    <div class="form-group">
	                                        <label for="nome">Nome</label>
	                                        <div class="input-group">
	                                            <div class="input-group-addon"><i class="ti-user"></i></div>
	                                            <input type="text" class="form-control" name="nome" id="nome" placeholder="Nome"> </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"  placeholder="(XX) XXXXX-XXXX" > 

	                                        </div>

	                                    </div>

	                                    
	                                    <div class="form-group" id="selectOption">
	                                        <label class="control-label">Profile</label>
	                                        <select class="form-control select" name="profile" id="profile">
	                                        <?php foreach($profiles as $profile): ?>
	                                        	<option data-bouq="<?= $profile['id_bouq']; ?>" value="<?= $profile['profile'];?>">
	                                            <?php 
	                                                if(empty($profile['profile_str'])) {
	                                        		    echo $profile['profile']; 
                                                    } else {
                                                    	echo $profile['profile_str']; 
                                                    } ?>
                                                </option>    
                                            <?php endforeach;  ?>
	                                            
	                                        </select>
	                                    </div>

	                                    <div class="form-group" id="selectVencimento" style="display:none"> 
											<label for="vencimento" class="control-label">Valido Até:</label>
											<input type="datetime" class="form-control vencimento" name="vencimento" id="vencimento" value="<?= date('Ymd H:i:s', strtotime('+1 month')); ?>">
	                                    </div>   
	                                    <div class="form-group">
	                                        <label class="control-label">Situação do login</label>
	                                        <select name="status" id="status" class="form-control">
	                                            <option value="teste" >Teste (8 horas)</option>
	                                            <option value="normal">Ativado</option>
	                                            <option value="desativado">Desativado</option>
	                                        </select>
	                                    </div>
                                        <?php if (cs::isAdmin()): ?>
	                                    <div class="form-group">
	                                        <label for="max_connections">Maximo de Pontos</label>
	                                        <div class="input-group">
	                                            <div class="input-group-addon"><i class="fa fa-server fa-lg"></i></div>
	                                            <input min="1" type="number" class="form-control" id="max_connections" name="max_connections" value="1"> 
	                                        </div>

	                                    </div>
	                                    <?php else: ?>
	                                    	<input min="1" type="hidden" class="form-control" id="max_connections" name="max_connections" value ="1"> 
	                                    <?php endif; ?>

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

		                                

		                                <div class="col-lg-12 col-md-12 col-sm-12">
		                                    
		                                    <p class="text-muted m-b-30">Você possui no momento <b><?= (string) $total_users;?></b> usuários cadastrados, seu limite é de <code><?= $_SESSION['info_unf']['limite_usuarios']; ?></code> usuários.</p>
		                                    
		                                </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>
    <!--Sweet Alert -->
    <script src="../../plugins/bower_components/sweetalert/sweetalert.min.js"></script>
      
    <!--Functions Js -->
    <script src="../../public/assets/js/functions.js"></script>
    
    <script>
        var nowDate    = new Date() 
        var Normal     = nowDate.setMonth(new Date().getMonth() + 1)
        var Teste      = nowDate.getHours() + 2
        Teste          = nowDate.setHours(Teste)
       
        
    	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 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)
			    }
			} 
			
		$('.phone_with_ddd').mask(SPMaskBehavior, spOptions)       

		$(document).ready(function () {
			
			
            
            let status     = $('#status option:selected').val()
            let profile_id = $('#profile option:selected').data('bouq');
            $('#profile_id').val(profile_id)
            $('#status').val(status)

         
            $('#profile').change( () => {
                $('#profile_id').val($(this))
            	$('#profile_id').val( $(this).find('option:selected').data('bouq') )
            })

            function makeid() {        
	            var text     = "";
	            var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

			    for (var i=0; i < 6; i++) {
			        text += possible.charAt(Math.floor(Math.random() * possible.length));
			    }

			    return text.toLowerCase();
			}
            

			// $('#selectOption').on('option:select', function (e) {
			    
			//     let id = $(e.params.data.element).data('bouq')
			//     $('#profile_id').val(id)
			//     console.log(id)
			// })

			$('#createLg').click( () => {
                $('#login').val(makeid())
			    $('#senha').val(makeid())
			})		

            // $('#status').on('change', function () {
                
                
            //     // if($(this).val() != 'teste' && $(this).val() != '') {
            //     //    //console.log(Normal, Teste)
            //     //    //$('#datepicker').attr('readonly', false);
                  
            //     //    document.getElementById('datepicker').value = new Date(Normal).toISOString().slice(0,10).toString()
                   
            //     //    //$('#selectVencimento').show('slow');   
                
            //     // } else {
            //     //     //$('#datepicker').attr('readonly', true);
            //     //      document.getElementById('datepicker').value = Teste
                   
            //     //    //$('#selectVencimento').hide('slow');   
            //     // }
            // })

            $('#create').submit( function(e) {
	            e.preventDefault()
                
	            let form   = $('#create').serialize()

	            let action = '../ajax_store.php'
	            
	            $('.message').html('')
	            
	        
	            $.post(action, form)
	                .done( (res) => {
	                    
	                    $('#login').val(makeid())
			            $('#senha').val(makeid())
	                    
	                    res  = JSON.parse(res) 
	                    //console.log(res)
	                    $('.message').html(`<div id="alertMessage" class="alert ${res.class} alert-dismissable text-center">
	                            <button type="button " class="close" data-dismiss="alert" aria-hidden="true">×</button><p>${res.text}</p> 
	                        </div>`)
	                    
	                    //console.log(res)
	                    
	                    if (res.success == true && res.data != undefined) {
	                    
	                        location = `../visualizar/index.php?id=${res.data.id}` 
	                    }
	                    
	                })
	            
	        }) // End Form Submit             
		})
		
    </script>

    
</body>

</html>