<?php
	$seccion    = 'Fuerza de ventas';
	$subseccion = 'Usuario';
	$position   = '../../';

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

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


	/* Usuario */
	if(isset($_POST['save'])== 'Ok'){

	   if (isset($_GET['id'])){$idUsuario	= $_GET['id'];}

		if(isset($_POST['nombre'])){
			$nombre = addslashes(strip_tags($_POST['nombre']));
		}
		if(isset($_POST['apellidoPaterno'])){
			$apellidoPaterno = addslashes(strip_tags($_POST['apellidoPaterno']));
		}
		if(isset($_POST['apellidoMaterno'])){
			$apellidoMaterno = addslashes(strip_tags($_POST['apellidoMaterno']));
		}
		if(isset($_POST['celular'])){
			$celular = str_replace("-","",$_POST['celular']);
		}
		if(isset($_POST['email'])){
			$email = addslashes(strip_tags($_POST['email']));
		}
	  if(isset($_POST['password'])){
			// $hashed	= md5($_POST['password']);
			$hashed				= $_POST['password'];
			$aContrasenia = "pass = '$hashed',";
		}
		if (isset($_POST['estatus'])){
			$estatus	= addslashes(strip_tags($_POST['estatus']));
		}
		if (isset($_POST['tipo'])){
			$tipo	= addslashes(strip_tags($_POST['tipo']));
		}

		$now = now();

    //-->Nuevo Usuario
    if($_POST['action'] == 'nuevo'){

      // Validación de email registrado
      $qrCelular = "
				SELECT
					u.celular
				FROM usuarios_app u
				WHERE
					u.celular = '$celular'
			";
      $rCelular  = mysqli_query($mysqli, $qrCelular);
      $celularRow = mysqli_fetch_assoc($rCelular);

      if(isset($celularRow['celular']) != ""){
        echo '<script type="text/javascript">document.location.href="usuario.php?nombre='.$nombre.'&apellido_paterno='.$apellidoPaterno.'&apellido_materno='.$apellidoMaterno.'&email='.$email.'&sv=2"</script>';

      }else{
        //Save
        $qsUsuario = "
					INSERT INTO usuarios_app (
						nombre, apellido_paterno, apellido_materno,
						celular, email, pass,
						fk_usuario_tipo, activo, fecha_alta
					) VALUES (
						'$nombre', '$apellidoPaterno', '$apellidoMaterno',
						'$celular', '$email', '$hashed',
						'1', '1', '$now'
					)
				";
        $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 usuarios_app
				SET
					nombre = '$nombre',
					apellido_paterno = '$apellidoPaterno',
					apellido_materno = '$apellidoMaterno',
					celular = '$celular',
					email = '$email',
					$aContrasenia
					activo = '$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.apellido_paterno, us.apellido_materno, us.celular, us.email, us.activo FROM onecoded_SwitchPointApp.usuarios_app 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="<?php echo $position; ?>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; ?>tenderos/usuarios/"><?php echo $seccion; ?></a></li>
                                    <li class="breadcrumb-item active"><?php echo $subseccion; ?></li>
                                </ol>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- /page title -->

								<!-- 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>
								<!-- End Botones -->

								<!-- usuarios -->
                <div class="row">
                  <div class="col-md-12">

										<!-- Card Información -->
                    <div class="card">
                      <div class="card-body">
												<div class="row">

													<div class="col-sm-12">
														<h4 class="header-title">Información</h4>
													</div>


                          <input type="hidden" class="form-control" name="save" value="Ok">
                          <input type="hidden" class="form-control" name="action" value="<?php echo $tipoAccion; ?>">

													<!-- Tipo de Usuario --
                          <div class="form-group col-md-6">
                            <label for="inputState" class="col-form-label">Tipo de Usuario</label>
                            <select id="inputState" name="estatus" class="form-control" required>
                              <option <?php if( $usuario['id']){ if( $usuario['activo'] == 1 ){ echo "selected='selected'"; } } ?> value="1">Activo</option>
															<option <?php if( $usuario['id']){ if( $usuario['activo'] == 1 ){ echo "selected='selected'"; } } ?> value="1">Activo</option>
                              <option <?php if( $usuario['id']){ if( $usuario['activo'] == 0 ){ echo "selected='selected'"; } } ?> value="0">Inactivo</option>
                            </select>
                          </div>
													<!-- End Tipo de Usuario -->

													<!-- Nombre -->
                          <div class="form-group col-md-4">
                            <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>
													<!-- End Nombre -->

													<!-- Apellido Paterno -->
													<div class="form-group col-md-4">
                            <label for="inputAp" class="col-form-label">Apellido Paterno<span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="inputAp" name="apellidoPaterno" placeholder="Apellido Paterno" value="<?php if(isset($usuario['id'])){ echo $usuario['apellido_paterno'];}else{ if(isset( $_GET['apellido_paterno'])){ echo $_GET['apellido_paterno'];}} ?>" required>
                          </div>
													<!-- End Apellido Paterno -->

													<!-- Apellido Materno -->
													<div class="form-group col-md-4">
		                        <label for="inputAm" class="col-form-label">Apellido Materno</label>
		                        <input type="text" class="form-control" id="inputAm" name="apellidoMaterno" placeholder="Apellido Materno" value="<?php if(isset($usuario['id'])){ echo $usuario['apellido_materno'];}else{ if(isset( $_GET['apellido_materno'])){ echo $_GET['apellido_materno'];}} ?>" >
                        	</div>
													<!-- End Apellido Materno -->

												</div>
											</div>
										</div>
										<!-- End Card Información -->

										<!-- Card Contacto -->
                    <div class="card">
                      <div class="card-body">
												<div class="row">

													<div class="col-sm-12">
                        		<h4 class="header-title">Contacto</h4>
													</div>

													<!-- Telefono Celular -->
													<div class="form-group col-md-12">
		                        <label for="inputCel" class="col-form-label">Telefono Celular<span class="text-danger">*</span></label>
		                        <input type="text" class="form-control" data-toggle="input-mask" data-mask-format="00-0000-0000" id="inputCel" name="celular" placeholder="Celular" value="<?php if(isset($usuario['id'])){ echo $usuario['celular'];}else{ if(isset( $_GET['celular'])){ echo $_GET['celular'];}} ?>" required>
	                    		</div>
													<!-- End Telefono Celular -->

												</div>
											</div>
                    </div>
										<!-- End Card Contacto -->

										<!-- Card Cuenta -->
                    <div class="card">
                      <div class="card-body">
												<div class="row">

													<div class="col-sm-12">
                        		<h4 class="header-title">Cuenta</h4>
													</div>

													<!-- Correo Electronico -->
						              <div class="form-group col-md-12">
	                          <label for="inputEm" class="col-form-label">Correo Electronico</label>
	                          <input type="email" class="form-control" id="inputEm" name="email" placeholder="Correo Electrónico" value="<?php if(isset($usuario['id'])){ echo $usuario['email'];}else{ if(isset( $_GET['email'])){ echo $_GET['email'];}} ?>" >
	                        </div>
													<!-- End Correo Electronico -->

													<!-- Contraseña -->
	                        <div class="form-group col-md-6">
	                          <label for="pass1">Contraseña</label>
	                          <input type="password" class="form-control" id="pass1" name="password" placeholder="Nueva Contraseña">
	                        </div>
													<!-- End Contraseña -->

													<!--  Confirma Contraseña -->
	                        <div class="form-group col-md-6">
	                          <label for="passWord2">Confirma Contraseña</label>
	                          <input data-parsley-equalto="#pass1" type="password" placeholder="Nueva Contraseña" class="form-control" id="passWord2">
	                        </div>
													<!--  Emd Confirma Contraseña -->

													<!-- Estatus -->
	                        <div class="form-group col-md-12">
	                          <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['activo'] == 1 ){ echo "selected='selected'"; } } ?> value="1">Activo</option>
	                              <option <?php if( $usuario['id']){ if( $usuario['activo'] == 0 ){ echo "selected='selected'"; } } ?> value="0">Inactivo</option>
	                          </select>
	                        </div>
													<!-- End Estatus -->

												</div>
                      </div>
                    </div>
										<!-- End Card -->


                  </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="<?php echo $position; ?>assets/js/vendor.min.js"></script>

        <!-- App js -->
        <script src="<?php echo $position; ?>assets/js/app.min.js"></script>

        <!-- Plugin js-->
        <script src="<?php echo $position; ?>assets/libs/parsleyjs/parsley.min.js"></script>
        <script src="<?php echo $position; ?>assets/libs/twitter-bootstrap-wizard/jquery.bootstrap.wizard.min.js"></script>

        <!-- Validation init js-->
        <script src="<?php echo $position; ?>assets/js/pages/form-validation.init.js"></script>

        <!-- Sweet Alerts js -->
        <script src="<?php echo $position; ?>assets/libs/sweetalert2/sweetalert2.min.js"></script>

        <!-- Sweet alert init js-->
        <script src="<?php echo $position; ?>assets/js/pages/sweet-alerts.init.js"></script>

        <!-- Plugins js mask -->
        <script src="<?php echo $position; ?>assets/libs/jquery-mask-plugin/jquery.mask.min.js"></script>
        <script src="<?php echo $position; ?>assets/libs/autonumeric/autoNumeric-min.js"></script>

        <!-- Init js mask-->
        <script src="<?php echo $position; ?>assets/js/pages/form-masks.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 No. Telefónico ya fue registrado con anterioridad, ingresa un nuevo teléfono de contacto",
            confirmButtonClass:"btn btn-confirm mt-2",
            //footer:'<a href="">Why do I have this issue?</a>'
        });
        });
        <?php } ?>
        </script>


    </body>
</html>
