<?php 
$seccion    = 'Usuarios';
$subseccion = 'Usuario';
$position   = '../';

require_once($position.'../switch/access.php');
require_once($position.'assets/global.php');
require_once($position.'assets/session.php');

if (isset($_GET['id'])){$tipoAccion="editar";}else{$tipoAccion="nuevo";}

/* Usuario */
if(isset($_POST['save'])== 'Ok'){
	
    if (isset($_GET['id'])){$idUsuario	= $_GET['id'];}	
    $nombre		= addslashes(strip_tags($_POST['nombre']));
    $apellidos	= addslashes(strip_tags($_POST['apellidos']));
    $puesto		= addslashes(strip_tags($_POST['puesto']));
    $email		= addslashes(strip_tags($_POST['email']));
    if (isset($_POST['estatus'])){$estatus	= addslashes(strip_tags($_POST['estatus']));}
    if (isset($_POST['password'])){$contrasenia	= $_POST['password'];}
    if (isset($_POST['npassword'])){ if($_POST['npassword'] != ""){  $nContrasenia	= $_POST['npassword'];}}
    if (isset($contrasenia)){$hashed_password 	= password_hash($contrasenia, PASSWORD_DEFAULT);}	
    
    if (isset($nContrasenia) != ""){ 
        $hashed_n_password = password_hash($nContrasenia, PASSWORD_DEFAULT); 
        $aContrasenia = "password = '$hashed_n_password',";
    }else{
        $aContrasenia = "";
    }	
            
    //Nuevo Usuario
    if($_POST['action'] == 'nuevo'){
        
        // Validación de email registrado 
        $qrEmail = "SELECT u.email FROM onecoded_SwitchPointApp.usuarios u WHERE u.email = '$email' "; 
        $rEmail  = mysqli_query($mysqli, $qrEmail);
        $emailRow = mysqli_fetch_assoc($rEmail);
        
        if(isset($emailRow['email']) != ""){
            echo '<script type="text/javascript">document.location.href="usuario.php?nombre='.$nombre.'&apellidos='.$apellidos.'&puesto='.$puesto.'&sv=2"</script>';
            
        }else{
            //Save
            $qsUsuario = "INSERT INTO onecoded_SwitchPointApp.usuarios (nombre, apellidos, puesto, email, password, bandera) VALUES ('$nombre', '$apellidos', '$puesto', '$email', '$hashed_password','1')";
            $sUsuarios = mysqli_query($mysqli, $qsUsuario);
            $idUsuario = mysqli_insert_id($mysqli);
            
            echo '<script type="text/javascript">document.location.href="usuario.php?id='.$idUsuario.'&sv=1"</script>';
        }
    }
    //END Nuevo Usuario	
        
    //Edita Usuario
    if($_POST['action'] == 'editar'){
    
        //Update
        $qeUsuario = "
        UPDATE onecoded_SwitchPointApp.usuarios SET nombre = '$nombre', apellidos = '$apellidos', puesto = '$puesto', email = '$email', $aContrasenia bandera = '$estatus' WHERE id = $idUsuario";
        $eUsuarios = mysqli_query($mysqli, $qeUsuario);
        
        echo '<script type="text/javascript">document.location.href="usuario.php?id='.$idUsuario.'&sv=1"</script>';
    }
    //END Edita Usuario	
        
}//End if save
/* END Usuario  */
    
    //Query's
    
if(isset($_GET['id'])){
    
    //QrUsuario
    $qrUsuario = "select us.id, us.nombre, us.apellidos, us.puesto, us.email, us.bandera from onecoded_SwitchPointApp.usuarios us where us.id = $_GET[id]";
    $rUsuario  = mysqli_query($mysqli, $qrUsuario);
    $usuario   = mysqli_fetch_assoc($rUsuario);

}
?>
<!DOCTYPE html>
<html lang="es_MX">
    <head>
        <meta charset="utf-8" />
        <title>Switch Point | <?php echo $seccion; if(isset($subseccion)) { echo " > ".$subseccion;} ?> </title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <!-- App favicon -->
        <link rel="shortcut icon" href="<?php echo $position; ?>assets/images/favicon.ico">

		<!-- App css -->
		<link href="<?php echo $position; ?>assets/css/bootstrap-corporate.min.css" rel="stylesheet" type="text/css" id="bs-default-stylesheet" />
		<link href="<?php echo $position; ?>assets/css/app-corporate.min.css" rel="stylesheet" type="text/css" id="app-default-stylesheet" />

		<link href="<?php echo $position; ?>assets/css/bootstrap-corporate-dark.min.css" rel="stylesheet" type="text/css" id="bs-dark-stylesheet" />
		<link href="<?php echo $position; ?>assets/css/app-corporate-dark.min.css" rel="stylesheet" type="text/css" id="app-dark-stylesheet" />
        <link href="<?php echo $position; ?>assets/css/style.css" rel="stylesheet" type="text/css" id="app-dark-stylesheet" />

        <!-- Sweet Alert-->
        <link href="../assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
		
        <!-- icons -->
		<link href="<?php echo $position; ?>assets/css/icons.min.css" rel="stylesheet" type="text/css" />

    </head>

    <body class="loading" data-layout='{"mode": "light", "width": "fluid", "menuPosition": "fixed", "sidebar": { "color": "dark", "size": "default", "showuser": false}, "topbar": {"color": "light"}, "showRightSidebarOnPageLoad": false}'>

        <!-- Pagina de inicio -->
        <div id="wrapper">

            <!-- ========== Inicio nav-izq ========== -->
            <?php include_once($position.'assets/nav.php'); ?>
            <!-- Fin nav-izq -->

            <!-- ============================================================== -->
            <!-- Incio de Contenido -->
            <!-- ============================================================== -->

            <div class="content-page">
                <div class="content">

                    <!-- Topbar -->
                    <?php include_once($position.'assets/topbar.php'); ?>
                    <!-- /Topbar -->

                    <!-- Content-->
                    <div class="container-fluid">
                    <form method="post" enctype="multipart/form-data" class="parsley-examples" novalidate>	
                        
                        <!-- page title -->
                        <div class="row">
                            <div class="col-12">
                                <div class="page-title-box">
                                    <h4 class="page-title"><?php echo $seccion; ?></h4>
                                    <div class="page-title-right">
                                        <ol class="breadcrumb m-0">
                                            <li class="breadcrumb-item"><a href="<?php echo $dir; ?>inicio/">Inicio</a></li>
                                            <li class="breadcrumb-item"><a href="<?php echo $dir; ?>usuarios/"><?php echo $seccion; ?></a></li>
                                            <li class="breadcrumb-item active"><?php echo $subseccion; ?></li>
                                        </ol>
                                    </div>
                                </div>
                            </div>
                        </div>     
                        <!-- /page title --> 

                        <!-- secciones  -->
						<!-- Botones -->
						<div class="row">			
							<div class="col-12 text-right">
								<button type="button" class="btn btn-white btn-sm" onclick="window.location.href='./'"><i class="fe-arrow-left"></i>&nbsp; Regresar</button>
								<button type="button" class="btn btn-white btn-sm" onclick="window.location.href='usuario.php'">Nuevo <i class="fe-user-plus"></i></button>
								<button type="submit" class="btn btn-primary btn-sm">Guardar <i class="fe-check-circle"></i></button>
							</div>
							<div class="col-12" style="height: 5px;">&nbsp;</div>
						</div>
						
						<!-- usuarios -->
                        <div class="row">
                            <div class="col-md-12">
                                <div class="card">
                                    <div class="card-body">
                                        <h4 class="header-title">Información General</h4>

                                            <div class="form-row">
                                                <input type="hidden" class="form-control" name="save" value="Ok">
                                                <input type="hidden" class="form-control" name="action" value="<?php echo $tipoAccion; ?>">
                                                
                                                <div class="form-group col-md-6">
                                                    <label for="inputNo" class="col-form-label">Nombre<span class="text-danger">*</span></label>
                                                    <input type="text" class="form-control" id="inputNo" name="nombre" placeholder="Nombre(s)" value="<?php if(isset($usuario['id'])){ echo $usuario['nombre'];}else{ if(isset( $_GET['nombre'])){ echo $_GET['nombre'];}}?>" required>
                                                </div>
                                                <div class="form-group col-md-6">
                                                    <label for="inputAp" class="col-form-label">Apellidos<span class="text-danger">*</span></label>
                                                    <input type="text" class="form-control" id="inputAp" name="apellidos" placeholder="Apellidos" value="<?php if(isset($usuario['id'])){ echo $usuario['apellidos'];}else{ if(isset( $_GET['apellidos'])){ echo $_GET['apellidos'];}} ?>" required>
                                                </div>
                                                <div class="form-group col-md-6">
                                                    <label for="inputPu" class="col-form-label">Puesto<span class="text-danger">*</span></label>
                                                    <input type="text" class="form-control" id="inputPu" name="puesto" placeholder="Puesto" value="<?php if(isset($usuario['id'])){ echo $usuario['puesto'];}else{ if(isset( $_GET['puesto'])){ echo $_GET['puesto'];}} ?>" required>
                                                </div>
                                                <div class="form-group col-md-6">
                                                    <label for="inputEm" class="col-form-label">Correo Electronico<span class="text-danger">*</span></label>
                                                    <input type="email" class="form-control" id="inputEm" name="email" placeholder="Correo Electrónico" value="<?php if(isset($usuario['id'])){ echo $usuario['email'];} ?>" required>
                                                </div>																		
                                                <?php if(isset($_GET['id'])){ ?>
                                                <div class="form-group col-md-6">
                                                    <label for="pass1">Nueva Contraseña</label>
                                                    <input type="password" class="form-control" id="pass1" name="npassword" placeholder="Nueva Contraseña">
                                                </div>
                                                <div class="form-group col-md-6">
                                                    <label for="passWord2">Confirma Nueva Contraseña</label>
                                                    <input data-parsley-equalto="#pass1" type="password" placeholder="Nueva Contraseña" class="form-control" id="passWord2">
                                                </div>
                                                <div class="form-group col-md-6">
                                                    <label for="inputState" class="col-form-label">Estatus</label>
                                                    <select id="inputState" name="estatus" class="form-control" required>
                                                        <option value=""></option>
                                                        <option <?php if( $usuario['id']){ if( $usuario['bandera'] == 1 ){ echo "selected='selected'"; } } ?> value="1">Activo</option>
                                                        <option <?php if( $usuario['id']){ if( $usuario['bandera'] == 0 ){ echo "selected='selected'"; } } ?> value="0">Inactivo</option>
                                                    </select>
                                                </div>
                                                <?php }else{ ?>
                                                <div class="form-group col-md-6">
                                                    <label for="pass1">Contraseña<span class="text-danger">*</span></label>
                                                    <input type="password" class="form-control" id="pass1" name="password" placeholder="Contraseña" required>
                                                </div>
                                                <div class="form-group col-md-6">
                                                    <label for="passWord2">Confirma Contraseña <span class="text-danger">*</span></label>
                                                    <input data-parsley-equalto="#pass1" type="password" placeholder="Contraseña" class="form-control" id="passWord2" required>
                                                </div>
                                                <?php } ?>
                                            </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- /secciones -->
                        </form>
                    </div> <!-- /container -->

                </div> <!-- /content -->

                <!-- Footer -->
                <?php include_once($position.'assets/footer.php'); ?>
                <!-- /Footer -->

            </div>

            <!-- ============================================================== -->
            <!-- Fin de Contenido -->
            <!-- ============================================================== -->


        </div>
        <!--  /wrapper -->

        <!-- Vendor js -->
        <script src="../assets/js/vendor.min.js"></script>

        <!-- App js -->
        <script src="../assets/js/app.min.js"></script>

        <!-- Plugin js-->
        <script src="../assets/libs/parsleyjs/parsley.min.js"></script>
        <script src="../assets/libs/twitter-bootstrap-wizard/jquery.bootstrap.wizard.min.js"></script>

        <!-- Validation init js-->
        <script src="../assets/js/pages/form-validation.init.js"></script>
                
        <!-- Sweet Alerts js -->
        <script src="../assets/libs/sweetalert2/sweetalert2.min.js"></script>

        <!-- Sweet alert init js-->
        <script src="../assets/js/pages/sweet-alerts.init.js"></script>
        
        <!-- save -->
        <script>
        <?php if( $_GET['sv'] == 1 ){ ?>
        $( document ).ready(function(){
        Swal.fire({
            //position:"top-end",
            type:"success",
            title:"El Usuario se ha guardado correctamente.",
            showConfirmButton:!1,timer:5000
        });

        });
        <?php } ?>
        <?php if( $_GET['sv'] == 2 ){ ?>
        $( document ).ready(function(){
        Swal.fire({
            type:"error",
            title:"Oops...",
            text:"El correoelectrónico ya fue registrado con anterioridad, ingresa un nuevo correo electrónico",
            confirmButtonClass:"btn btn-confirm mt-2",
            //footer:'<a href="">Why do I have this issue?</a>'
        });
        });
        <?php } ?>	
        </script>

        
    </body>
</html>