<!DOCTYPE html>
<html lang="en">
                          
<?php $this->load->view("template/header"); ?>
<?php $this->load->view("template/nav"); ?>
        
<div class="content-wrapper">
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0">Roles</h1>
                </div>

                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <!-- <li class="breadcrumb-item"><a href="#" onclick="mySession()" class="nav-link">Cerrar Sesión</a></li> -->
                    </ol>
                </div>
            </div>
        </div>
    </div>

    <section class="content">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-12">
                    <div class="card card-secondary">
                        <div class="card-header">
                            <h3 class="card-title">Datos de  búsqueda </h3>
                        </div>

                        <form id="quickForm"  autocomplete="off">
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-sm-4">
                                        <div class="form-group">
                                            <label>Roles</label>
                                            <select class="form-control" id="cmb_rol">
                                                <option value="">--Seleccionar-- </option>
                                                <?php foreach($rol as $k1) { ?>
                                                    <option value="<?=$k1->IdRol?>"><?=$k1->NomRol?></option>
                                                <?php } ?>   
                                            </select>
                                        </div>
                                    </div> 

                                    <div class="col-sm-3 pt-3 row">
								        <div class="col-sm-12 p-3">
                                            <button type="button" class="btn btn-primary col-md-4" id="btn_buscar">Buscar</button>
                                        </div>
                                    </div> 
                                </div> 
                            </div>

                            <div class="card-body">
                                <div id="example1_wrapper" class="dataTables_wrapper dt-bootstrap4">
                                    <div class="row">
                                        <div class="col-sm-12">
                                            <table id="example1" class="table table-bordered table-striped dataTable dtr-inline" role="grid" aria-describedby="example1_info">
                                                <thead>
                                                    <tr role="row">
                                                        <th class="sorting sorting_asc" tabindex="0" aria-controls="example1" rowspan="1" colspan="1" aria-sort="ascending" aria-label="Rendering engine: activate to sort column descending" >Rol</th>
                                                        <th class="sorting" tabindex="0" aria-controls="example1" rowspan="1" colspan="1" aria-label="Browser: activate to sort column ascending" >Perfil</th>
                                                        <th class="sorting" tabindex="0" aria-controls="example1" rowspan="1" colspan="1" aria-label="Platform(s): activate to sort column ascending" style="">Estado Perfil</th>
                                                        <th class="sorting" tabindex="0" aria-controls="example1" rowspan="1" colspan="1" aria-label="Platform(s): activate to sort column ascending" style="">Usuario</th>
                                                        <th class="sorting" tabindex="0" aria-controls="example1" rowspan="1" colspan="1" aria-label="Platform(s): activate to sort column ascending" style="">Accion</th>
                                                </thead>
                                                <tbody>
                                                </tbody>
                                                <tfoot>
                                                    <tr>
                                                        <th rowspan="1" colspan="1" >Rol</th>
                                                        <th rowspan="1" colspan="1" >Perfil</th>
                                                        <th rowspan="1" colspan="1" >Estado Perfil</th>
                                                        <th rowspan="1" colspan="1" >Usuario</th>
                                                        <th rowspan="1" colspan="1" >Accion</th>
                                                    </tr>
                                                </tfoot>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="card-footer"></div>
                    
                            <div class="card-footer">
                    	        <button type="button" id="btn_nuevo_rol" class="btn btn-primary col-md-1 ">Nuevo</button>
                            </div>
                        </form>
                    </div> 

                    <div class="row">
                        <section class="col-lg-7 connectedSortable"></section>
                        <section class="col-lg-5 connectedSortable"></section>
                    </div>
                </div>
            </div>
        </div>        
    </section>
</div>

<?php $this->load->view("template/footer"); ?>

<aside class="control-sidebar control-sidebar-dark"></aside>

<!-- ======================================================================================================================================================================================================= -->
<div class="modal fade show" id="modal-rol-nuevo" aria-modal="true" role="dialog">
	<div class="modal-dialog modal-lg modal-rol-nuevo">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Nuevo Rol</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>

			<div class="modal-body">
                <div class="card-body">
					<dl class="row">
                        <dt class="col-sm-4">Rol</dt>
                        <dd class="col-sm-8"><input type="text" class="form-control" name="opt_rol" id="opt_rol" onkeyup="mayus(this);"></dd>
                        
						<dt class="col-sm-4">Perfil</dt>
                        <dd class="col-sm-8">
                            <select class="custom-select" id="cmb_perfil">
                                <option value="">--Seleccionar-- </option>
                                <?php foreach($perfiles as $k2) { ?>
                                    <option value="<?=$k2->IdPerfil?>"><?=$k2->Nombre?></option>
                                <?php } ?>   
                            </select>
						</dd>

                        <dt class="col-sm-4">Usuario</dt>
                        <dd class="col-sm-8">
                            <select class="custom-select" id="cmb_usuario">
                                <option value="">--Seleccionar-- </option>
                                <?php foreach($usuario as $k3) { ?>
                                    <option value="<?=$k3->IdUsuario?>"><?=$k3->Nombres?><?=" "?><?=$k3->Apellidos?></option>
                                <?php } ?>   
                            </select>
						</dd>
                    </dl>
                </div>
            </div>

            <div class="modal-footer justify-content-between">
				<button style="float: left" type="button" class="btn btn-secondary col-md-1  " id="btn_cancelar_rol" data-dismiss="modal">Cancelar </button>  
				<button style="float: right" type="button" class="btn btn-primary col-md-1 " id="btn_guardar_rol" data-dismiss="modal">Guardar </button>   
            </div>
        </div>
    </div>
</div>

<!-- ======================================================================================================================================================================================================= -->

<div class="modal fade show" id="modal-rol-editar" aria-modal="true" role="dialog">
	<div class="modal-dialog modal-lg modal-rol-editar">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Editar Rol</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>

			<div class="modal-body">
                <div class="card-body">
					<dl class="row">
                        <dt class="col-sm-4">Id Rol</dt>
                        <dd class="col-sm-8"><input type="text" class="form-control" name="opt_IdRol_Editar" id="opt_IdRol_Editar" readonly="true"></dd>

                        <dt class="col-sm-4">Rol</dt>
                        <dd class="col-sm-8"><input type="text" class="form-control" name="opt_Rol_Editar" id="opt_Rol_Editar"></dd>

                        <dt class="col-sm-4">Perfil</dt>
                        <dd class="col-sm-8">
                            <select class="custom-select" id="cmb_perfil_Editar">
                                <option value="">--Seleccionar-- </option>
                                <?php foreach($perfiles as $k2) { ?>
                                    <option value="<?=$k2->IdPerfil?>"><?=$k2->Nombre?></option>
                                <?php } ?>   
                            </select>
						</dd>     

						<dt class="col-sm-4">Usuario</dt>
                        <dd class="col-sm-8">
                            <select class="custom-select" id="cmb_usuario_Editar">
                                <option value="">--Seleccionar-- </option>
                                <?php foreach($usuario as $k3) { ?>
                                    <option value="<?=$k3->IdUsuario?>"><?=$k3->Nombres?><?=" "?><?=$k3->Apellidos?></option>
                                <?php } ?>   
                            </select>
                        </dd>
                    </dl>
                </div>
            </div>

            <div class="modal-footer justify-content-between">
				<button style="float: left" type="button" class="btn btn-secondary col-md-3" id="btn_cancelar_rol" data-dismiss="modal">Cancelar </button>  
				<button style="float: right" type="button" class="btn btn-primary col-md-3" id="btn_actualizar_rol" data-dismiss="modal">Actualizar </button>   
            </div>
        </div>
    </div>
</div>

<!-- ======================================================================================================================================================================================================= -->
     <!-- jQuery -->
    <script src="<?php echo base_url() ?>assets/plugins/jquery/jquery.js"></script>
    <script src="<?php echo base_url() ?>assets/plugins/jquery/jquery.min.js"></script>
    <!-- jQuery UI 1.11.4 -->
    <script src="<?php echo base_url() ?>assets/plugins/jquery-ui/jquery-ui.min.js"></script>
    <!-- jQuery Mask -->
    <script src="<?php echo base_url() ?>assets/plugins/jquery-Mask/jquery.mask.min.js"></script>
    <!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip -->
    <script>
        $.widget.bridge('uibutton', $.ui.button)
    </script>
    <!-- Bootstrap 4 -->
    <script src="<?php echo base_url() ?>assets/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
    <!-- ChartJS -->
    <script src="<?php echo base_url() ?>assets/plugins/chart.js/Chart.min.js"></script>
    <!-- Sparkline -->
    <!-- <script src="<?php echo base_url() ?>assets/plugins/sparklines/sparkline.js"></script> -->
    <!-- JQVMap  -->
    <script src="<?php echo base_url() ?>assets/plugins/jqvmap/jquery.vmap.min.js"></script>
    <script src="<?php echo base_url() ?>assets/plugins/jqvmap/maps/jquery.vmap.usa.js"></script>
    <!-- jQuery Knob Chart -->
    <script src="<?php echo base_url() ?>assets/plugins/jquery-knob/jquery.knob.min.js"></script>
    <!-- daterangepicker -->
    <script src="<?php echo base_url() ?>assets/plugins/moment/moment.min.js"></script>
    <script src="<?php echo base_url() ?>assets/plugins/daterangepicker/daterangepicker.js"></script>
    <!-- Tempusdominus Bootstrap 4 -->
    <script src="<?php echo base_url() ?>assets/plugins/tempusdominus-bootstrap-4/js/tempusdominus-bootstrap-4.min.js"></script>
    <!-- Summernote -->
    <script src="<?php echo base_url() ?>assets/plugins/summernote/summernote-bs4.min.js"></script>
    <!-- overlayScrollbars -->
    <script src="<?php echo base_url() ?>assets/plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
    <!-- AdminLTE App -->
    <script src="<?php echo base_url() ?>assets/dist/js/adminlte.js"></script>
    <!-- AdminLTE for demo purposes -->
    <script src="<?php echo base_url() ?>assets/dist/js/demo.js"></script>
    <!-- AdminLTE dashboard demo (This is only for demo purposes) -->
     <!-- <script src="<?php echo base_url() ?>assets/dist/js/pages/dashboard.js"></script> -->
	<!-- SweetAlert -->
	<script src="<?php echo base_url() ?>assets/plugins/sweetalert2/sweetalert2.all.min.js"></script>
    <!-- AdminLTE Datatable components -->
    <script src="<?php echo base_url() ?>assets/plugins/datatables/jquery.dataTables.min.js"></script>
    <script src="<?php echo base_url() ?>assets/plugins/datatables-bs4/js/dataTables.bootstrap4.min.js"></script>
    <script src="<?php echo base_url() ?>assets/plugins/datatables-responsive/js/dataTables.responsive.min.js"></script>
    <script src="<?php echo base_url() ?>assets/plugins/datatables-responsive/js/responsive.bootstrap4.min.js"></script>
    <script src="<?php echo base_url() ?>assets/plugins/datatables-buttons/js/dataTables.buttons.min.js"></script>
    <script src="<?php echo base_url() ?>assets/plugins/datatables-buttons/js/buttons.bootstrap4.min.js"></script>
    <script src="<?php echo base_url() ?>assets/plugins/jszip/jszip.min.js"></script>
    <script src="<?php echo base_url() ?>assets/plugins/pdfmake/pdfmake.min.js"></script>
    <script src="<?php echo base_url() ?>assets/plugins/pdfmake/vfs_fonts.js"></script>
    <script src="<?php echo base_url() ?>assets/plugins/datatables-buttons/js/buttons.html5.min.js"></script>
    <script src="<?php echo base_url() ?>assets/plugins/datatables-buttons/js/buttons.print.min.js"></script>
    <script src="<?php echo base_url() ?>assets/plugins/datatables-buttons/js/buttons.colVis.min.js"></script>

<!-- ======================================================================================================================================================================================================= -->

    <script>
        //Definir Variables
        var Modulo = 'ROLES';

        //aca ya carga la data no necesito enviar nuevamente    
		var permisos = <?php echo json_encode($permisos) ?>;
		var rol      = <?php echo json_encode($rol) ?>;
        var perfiles = <?php echo json_encode($perfiles) ?>;

		//inicio de carga
        $(document).ready (function() {
            
            $("#example1").DataTable({
                data: rol,
                destroy: true,
				searching: false,
                columns:
                [
                    {data : 'NomRol'},
                    {data : 'NomPerfil'},
                    {"data" : function (row, type,val, meta) {
						if(type==='display'){
							switch (row.Estado) {
								case "A":
									return 'ACTIVO';
									break;
								case "I":
									return 'INACTIVO';
									break;
							}
						}else{
							return null;
						}                             
					}},  
                    {data : 'NomUsuario'},
                    {"data" : function (row, type,val, meta) {
						var IdRol=row.IdRol;
						if(type==='display'){
							return '<a href="#" onclick="EditarRol('+ row.IdRol +')" data-id="' + row.IdRol + '" class="table-edit">Editar</a>';
						}else{
							return null;
						}
					}}					
                ],
                responsive: true, "lengthChange": false, "autoWidth": false,
                buttons: ["copy", "csv", "excel", "pdf", "print"]
            }).buttons().container().appendTo('#example1_wrapper .col-md-6:eq(0)');
        });

        $("#btn_buscar").click(function () 
		{             
			//Captura de valores 
			var IdRol = '';
			IdRol   = $('#cmb_rol').val();
			

			//llamada a micro servicio de validacion
			$.ajax({

				url: '<?php echo base_url() ?>RolesHotel/searchRolesHotel',//controlador
				type: "POST",//tipo de peticion POST o GET
				headers: {'X-Requested-With': 'XMLHttpRequest'},//Encabezados
				data: { 'IdRol': IdRol}//formato json Data
								
					
			}).done(function(dato) 
			{
				//convierto la respuesta json
				var rol_bus = JSON.parse(dato);

                $("#example1").DataTable({
                data: rol_bus,
                destroy: true,
				searching: false,
                columns:
                [
                    {data : 'NomRol'},
                    {data : 'NomPerfil'},
                    {"data" : function (row, type,val, meta) {
						if(type==='display'){
							switch (row.Estado) {
								case "A":
									return 'ACTIVO';
									break;
								case "I":
									return 'INACTIVO';
									break;
							}
						}else{
							return null;
						}                             
					}},  
                    {data : 'NomUsuario'},
                    {"data" : function (row, type,val, meta) {
						var IdRol=row.IdRol;
						if(type==='display'){
							return '<a href="#" onclick="EditarRol('+ row.IdRol +')" data-id="' + row.IdRol + '" class="table-edit">Editar</a>';
						}else{
							return null;
						}
					}}					
                ],
                responsive: true, "lengthChange": false, "autoWidth": false,
                buttons: ["copy", "csv", "excel", "pdf", "print"]
            }).buttons().container().appendTo('#example1_wrapper .col-md-6:eq(0)');
				
			});	

            $('#cmb_rol').val("");
		});
	

		//Crear Rol
		$("#btn_nuevo_rol").click(function ()
		{ 
			for(i=0; i<permisos.length; i++){
				if (permisos[i].Nombre == Modulo)
				{ 
                    if(permisos[i].Registrar == 'A')
					{
						$("#modal-rol-nuevo").modal("show");
						break;
					
					}else{

						MsgAlerta(); 
					}
				}
			} 
        });
        
		//Guadar Rol
        $("#btn_guardar_rol").click(function () 
		{ 
			//Capturar Variables
			var Rol = $('#opt_rol').val(); 
			var IdPerfil = $('#cmb_perfil').val(); 
			var IdUsuario = $('#cmb_usuario').val(); 
           
            //Validaciones de front end
            
			//llamada a micro servicio de validacion
            $.ajax({
                url: '<?php echo base_url() ?>RolesHotel/insertRoles',//controlador
                type: "POST",//tipo de peticion POST o GET
                headers: {'X-Requested-With': 'XMLHttpRequest'},//Encabezados
                data: {'Rol'       : Rol, 
					   'IdPerfil'  : IdPerfil, 
					   'IdUsuario' : IdUsuario}//formato json Data   
                        
            }).done(function(dato) 
            {
                if (dato.trim() == 'ok') {
                    //Swal.fire("Informacion",obj.msg, "success");  
                    window.location.href="<?php echo base_url() ?>RolesHotel/listRolesHotel";
                }else{
                    Swal.fire("error",obj.msg, "error");  
                }
            });
      
        });

        //Actualizar Rol
        $("#btn_actualizar_rol").click(function () 
		{ 
			//Capturar Variables
			var IdRol     = $('#opt_IdRol_Editar').val();
			var Rol       = $('#opt_Rol_Editar').val();
			var IdPerfil  = $('#cmb_perfil_Editar').val();
			var IdUsu     = $('#cmb_usuario_Editar').val();

			//llamada a micro servicio de validacion
            $.ajax({
                url: '<?php echo base_url() ?>RolesHotel/updateRoles',//controlador
                type: "POST",//tipo de peticion POST o GET
                headers: {'X-Requested-With': 'XMLHttpRequest'},//Encabezados
                data: {'IdRol'     : IdRol, 
					   'Rol'       : Rol, 
					   'IdPerfil'  : IdPerfil, 
					   'IdUsu'     : IdUsu}//formato json Data   
                        
            }).done(function(dato) 
            {
                //convierto la respuesta json
                var obj = JSON.parse(dato); 
                if (obj.res == 'ok') {
					//Swal.fire("Informacion",obj.msg, "success");  
                    window.location.href="<?php echo base_url() ?>RolesHotel/listRolesHotel";
                }else{
                    Swal.fire("error",obj.msg, "error");  
                }
            });
      
        });

		//Editar Rol
        function EditarRol(IdRol)
		{
			//validar permisos de acceso
			for(i=0; i<permisos.length; i++){
				if (permisos[i].Nombre == Modulo)
				{ 
                    if(permisos[i].Actualizar == 'A')
					{
						for(i=0;i<=rol.length;i++)
						{
							if(rol[i].IdRol == IdRol){
								
								$('#opt_IdRol_Editar').val(IdRol);
								$('#opt_Rol_Editar').val(rol[i].NomRol)
								$('#cmb_perfil_Editar').val(rol[i].IdPerfil);
								$('#cmb_usuario_Editar').val(rol[i].IdUsuario);
								
								$("#modal-rol-editar").modal("show");
								
								return; 
							}   
						}
						break;
					
					}else{

						MsgAlerta(); 
					}
				}
			}
        };

        function mayus(e) {
			e.value = e.value.toUpperCase();
		};

		//Funcion para mensajes
		function MsgAlerta()
		{
			Swal.fire({
                title: "Información",
                html:" <p>No tiene permisos para esta acción. <br> Comunicate con el administrador.</p>",
                icon: "info"
			})
		};
     
 
    </script>

</body>

</html>
