<?php
	$Seccion      = 'Usuarios';
	$NameSec      = 'Usuarios';
	$SecLine      = array('Usuarios', 'Editar');
	$Position   = '../';
	require_once($Position.'config/config.php');
  require_once($Position.'config/conexion.php');
  require_once($Position.'config/user.php');
  require_once($Position.'funciones/acces.php');
  require_once($Position.'funciones/logout.php');
  require_once($Position.'funciones/funciones.php');
  //require_once($Position.'funciones/extras.php');

	if ( $_POST['Save'] == "Ok" ) {

		$Sucursal  = $_POST['Sucursal'];
		$Nombre    = $_POST['Nombre'];
		$Apellidos = $_POST['Apellidos'];
		$Email     = $_POST['Email'];
		// $Celular   = $_POST['Celular'];
		// $FechaAlta = CambioFechaCompleta($_POST['FechaAlta']);
		$Activo    = $_POST['Activo'];

		$UsuarioDependiente	= $_POST['UsuarioDependiente'];

		if( $_POST['Password'] == '0000000000' ){
	    $Pass     = '';
	    $PassEdit = '';
		}else{
	    $Pass     = md5(addslashes($_POST['Password']));
	    $PassEdit = "Pass  = '$Pass',";
		}
	}

	//Guardar Datos
	if ( $_POST['Save'] == "Ok" && $_POST['Action'] == "New" ) {

		//Insert Usuario
    $Query = "
			INSERT INTO KB_Usuarios
	    (
				Sucursal,
				Pass,
				Email,
				Nombre, Apellidos,
				Activo
			)VALUES(
				'$Sucursal',
				'$Pass',
				'$Email',
				'$Nombre', '$Apellidos',
				'$Activo'
			)
		";
    mysqli_query($mysqli, $Query );
    $Id = mysqli_insert_id($mysqli);

	}

	if ( $_POST['Save'] == "Ok" && $_POST['Id'] ) {

	    $Id = $_POST['Id'];
	    $Query = "
		    UPDATE KB_Usuarios SET
					Sucursal	= '$Sucursal',
			    Nombre    = '$Nombre',
			    Apellidos = '$Apellidos',
					Email			= '$Email',
					$PassEdit
			    Activo    = '$Activo'
		    WHERE Id  = '$Id'
	    ";
	    mysqli_query($mysqli, $Query );
	    $Save = 'Ok';

	}

	if( $_POST['Save'] == 'Ok' ){

		//Permisos
		$Permisos = $_POST['Permisos'];
		$Query = "
			UPDATE KB_UsuariosPermisos
	    SET
	    Borrar = '1'
	    WHERE Fk_Usuario = '$Id'
		";
    $Result = mysqli_query($mysqli, $Query);

		foreach( $Permisos AS $Permiso ){

      //Si Existe Registro
      $Query = "
	      SELECT
	      	are.Id
	      FROM KB_UsuariosPermisos are
	      WHERE are.Fk_Usuario = '$Id' AND are.Fk_Permiso = '$Permiso'
      ";
      $Result = mysqli_query($mysqli, $Query);
      $CliUsrA = mysqli_fetch_assoc($Result);
      if( $CliUsrA[Id] ){
        //Actualiza
        $Query = "
					UPDATE KB_UsuariosPermisos
	        SET
	        Borrar = '0'
	        WHERE Id = '$CliUsrA[Id]'
				";
        $Result = mysqli_query($mysqli, $Query);
      }else{
        //Inserta
        $Query = "
	        INSERT INTO KB_UsuariosPermisos
	        (
	          Fk_Usuario, Fk_Permiso
	        ) VALUES (
	          '$Id', '$Permiso'
	        )
				";
        $Result = mysqli_query($mysqli, $Query);
      }
    }
    $Query = "DELETE FROM KB_UsuariosPermisos WHERE Fk_Usuario = '$Id' AND Borrar = '1'";
    $Result = mysqli_query($mysqli, $Query);


	}

	if ( $_POST['Save'] == "Ok" && $_POST['Action'] == "New" && $Id ) {
	   echo '<script type="text/javascript">document.location.href="edit.php?Id='.$Id.'&New=Ok"</script>';
	}

	//Usuario
	$Query = "
		SELECT
			usr.Id,
			usr.Sucursal,
			usr.Email,
			usr.Nombre, usr.Apellidos,
			usr.Activo
		FROM KB_Usuarios usr
		WHERE usr.Id = '$_GET[Id]'
	";
	$Result = mysqli_query($mysqli, $Query );
	$Usr = mysqli_fetch_assoc($Result);

?>

<!DOCTYPE html>
<html lang="en">

<?php require_once($Position.'head.php'); ?>

<body class="fix-sidebar fix-header card-no-border">

  <div class="preloader">
    <svg class="circular" viewBox="25 25 50 50">
    <circle class="path" cx="50" cy="50" r="20" fill="none" stroke-width="2" stroke-miterlimit="10" /> </svg>
  </div>

  <div id="main-wrapper">

    <?php require_once($Position.'header.php'); ?>
    <?php require_once($Position.'menu.php'); ?>

    <div class="page-wrapper">

      <div class="container-fluid">

        <form method="post" enctype="multipart/form-data" data-validate="parsley" role="form" id="FormPer">

          <div class="row page-titles page-titles-fixed">

              <?php require_once($Position.'title.php'); ?>

              <!-- Botones -->
              <div class="col-md-7 align-self-center text-right">
                <div class="btn-group" role="group" aria-label="Basic example">

									<!-- Btn Regresar -->
									<button
										type="button"
										class="btn btn-sm btn-secondary"
										onclick="window.location.href='index.php'"
									>
										Regresar
										<i class="fa fa-arrow-left m-l-10"></i>
									</button>
									<!-- End Btn Regresar -->

									<!-- Btn Guardar -->
									<button
										type="submit"
										class="btn btn-sm btn-success"
									>
										Guardar
										<i class="fa fa-check m-l-10"></i>
									</button>
									<!-- End Btn Guardar -->

                  <input type="hidden" name="Save" value="Ok">

                  <?php if( $Usr['Id'] ){ ?>
										<input name="Id" type="hidden" id="Id" value="<?php echo $Usr['Id']; ?>">
										<input name="Action" type="hidden" value="Edit">
									<?php }else{ ?>
										<input name="Action" type="hidden" value="New">
									<?php } ?>
                </div>
              </div>
              <!-- End Botones -->

          </div>

          <div class="row inner-fixed-content">
            <div class="col-12">

							<!-- Nav tabs -->
							<ul class="nav nav-tabs tabcontent-border" role="tablist">

								<!-- Información -->
								<li class="nav-item">
									<a class="nav-link active" data-toggle="tab" href="#Informacion" role="tab">
										<span class="hidden-sm-up"><i class="ti-user"></i></span>
										<span class="hidden-xs-down">Información</span>
									</a>
								</li>
								<!-- End Información -->

								<!-- Permisos -->
								<li class="nav-item">
									<a class="nav-link" data-toggle="tab" href="#Permisos" role="tab">
										<span class="hidden-sm-up"><i class="ti-user"></i></span>
										<span class="hidden-xs-down">Permisos</span>
									</a>
								</li>
								<!-- End Permisos -->

							</ul>
							<!-- End Nav tabs -->

							<!-- Tabs Content -->
							<div class="tab-content tabcontent-border">

								<!-- Tab Información -->
								<div class="tab-pane card-body active" id="Informacion" role="tabpanel">
									<h4 class="card-title"><?php if( $Usr['Id'] ){ echo "Editar"; }else{ echo "Alta de"; } ?> Usuario</h4>
									<hr />
									<div class="row">

										<!-- Sucursal -->
										<div class="col-sm-12 form-group">
											<label>Sucursal</label>
											<select
												name="Sucursal"
												class="demo-default chosen-select"
												data-required="true"
											>
												<option value=""></option>
												<?php
													//Productos
													$Query = "
														SELECT
															suc.Id,
															suc.Sucursal
														FROM KB_Sucursales suc
														WHERE
															suc.Id != '0'
													";
													$Sucs = $mysqli->query($Query);
													mysqli_data_seek($Sucs, 0);
													while($Suc = mysqli_fetch_array($Sucs)) {
												?>
													<option
														value="<?php echo $Suc['Sucursal']; ?>"
														<?php if( $Usr['Sucursal'] == $Suc['Sucursal'] ){ ?>
															selected="selected"
														<?php } ?>
													><?php echo $Suc['Sucursal']; ?></option>
												<?php } ?>
											</select>
										</div>
										<!-- End Sucursal -->

										<!-- Nombre -->
										<div class="form-group col-sm-12">
											<label class="col-form-label">Nombre(s)<span class="text-danger">*</span></label>
											<div class="">
												<input
													name="Nombre"
													type="text"
													class="form-control"
													value="<?php echo $Usr['Nombre']; ?>"
													autocomplete="off"
													required="true"
												>
											</div>
										</div>
										<!-- End Nombre -->

										<!-- Apellidos -->
										<div class="form-group col-sm-12">
											<label class="col-form-label">Apellido(s)<span class="text-danger">*</span></label>
											<div class="">
												<input
													name="Apellidos"
													type="text"
													class="form-control"
													value="<?php echo $Usr['Apellidos'];?>"
													autocomplete="off"
													required="true"
												>
											</div>
										</div>
										<!-- End Apellidos -->

										<!-- Celular --
										<div class="form-group col-sm-12">
											<label class="col-form-label">Teléfonos Celular<span class="text-danger">*</span></label>
											<div class="">
												<input class="form-control" id="Celular" name="Celular" placeholder="Enter valid e-mail address" value="<?php echo $Usr['Celular'];?>" autocomplete="off" parsley-trigger="change" required>
											</div>
										</div>
										<!-- End Celular -->

										<!-- Email -->
										<div class="form-group col-sm-12">
											<label class="col-form-label">Correo Electrónico<span class="text-danger">*</span></label>
											<div class="">
												<input type="email" class="form-control" id="email" name="Email" placeholder="Enter valid e-mail address" value="<?php echo $Usr['Email'];?>" autocomplete="off" parsley-trigger="change" required>
											</div>
										</div>
										<!-- End Email -->

										<!-- Pass -->
										<div class="form-group col-sm-6">
											<label class="col-form-label">Contraseña <span class="text-danger">*</span></label>
											<div class="">
												<input type="password" class="form-control" id="pass1" name="Password" placeholder="Password input" value="<?php if( $Usr[Id]) { echo '0000000000';} else { } ?>" autocomplete="off">
											</div>
										</div>
										<!-- End Pass -->

										<!-- Repeat Pass -->
										<div class="form-group col-sm-6">
											<label class="col-form-label">Confirma Contraseña <span class="text-danger">*</span></label>
											<div class="">
												<input type="password" class="form-control" name="repeat-password" placeholder="Repeat Password" value="<?php if( $Usr[Id]) { echo '0000000000';} else { } ?>" autocomplete="off" data-parsley-equalto="#pass1" type="password" required id="passWord2">
											</div>
										</div>
										<!-- End Repeat Pass -->

										<!-- Fecha Alta --
										<div class="form-group col-sm-12">
											<label class="col-form-label">Fecha de Alta</label>
											<div class="">
												<input
													name="FechaAlta"
													type="text"
													class="form-control datepicker"
													value="<?php
														if( $Usr[FechaAlta] ){
															echo CambioFechaInversa(date("Y-m-d", strtotime($Usr[FechaAlta])));
														}else{
															echo CambioFechaInversa(date('Y-m-d'));
														}
													?>"
													autocomplete="off"
												>
											</div>
										</div>
										<!-- End Fecha Alta -->

										<!-- Status -->
										<div class="form-group col-sm-12">
											<label class="col-form-label">Status<span class="text-danger">*</span></label>
											<div class="">
												<select
													class="chosen-select"
													name="Activo"
													required
													data-validation-required-message="This field is required"
												>
													<option
														value="1"
														<?php
															if(
																( $Sta[Id] && $Usr[Activo] == 1 )
																||
																( !$Usr[Id] )
															){
														 		echo "selected='selected'";
															}
														?>
													>
														Activo
													</option>
													<option
														value="0"
														<?php
															if(
																$Sta[Id] && $Usr[Activo] == 0
															){
														 		echo "selected='selected'";
															}
														?>
													>
														Inactivo
													</option>
												</select>
											</div>
										</div>
										<!-- End Status -->

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

								<!-- Tab Permisos -->
								<div class="tab-pane card-body" id="Permisos" role="tabpanel">
									<h4 class="card-title">Permisos</h4>
									<hr />
									<div class="row">
										<?php
											//Secciones
											$Query = "
											  SELECT
											  	sec.Id, sec.Nombre
											  FROM KB_Secciones sec
												WHERE sec.Posicion = '1'
												ORDER BY sec.Orden ASC, sec.Nombre ASC
										  ";
										  $KB_Secciones = $mysqli->query($Query);
											$BgColorTop = 0;
											mysqli_data_seek($KB_Secciones, 0);
											while($AppSec = mysqli_fetch_array($KB_Secciones)) {
												$BgColorTop = $BgColorTop + 1;
												if( $BgColorTop == 7){ $BgColorTop = 1; }
										?>
											<div class="col-sm-12">
												<div class="card" style="border-top: 4px solid <?php echo $ColCons[$BgColorTop]; ?>; border-radius: 4px;">
													<div class="card-body">
														<h5><?php /*echo $AppSec[Id].' - ';*/ echo $AppSec[Nombre]; ?></h5>
														<hr />
														<div class="row">
															<?php
																//Permisos
																$Query = "
																  SELECT
																	  per.Id, per.Permiso,
																		perm.Fk_Permiso
																  FROM KB_Permisos per
																	LEFT JOIN KB_UsuariosPermisos perm ON perm.Fk_Permiso = per.Id AND perm.Fk_Usuario = '$Usr[Id]'
																	WHERE per.Fk_Seccion = '$AppSec[Id]'
																	ORDER BY per.Permiso
															  ";
															  $SecPermisos = $mysqli->query($Query);
																mysqli_data_seek($SecPermisos, 0);
																while($SecPerm = mysqli_fetch_array($SecPermisos)) {
															?>
																<!-- Permisos -->
																<fieldset class="col-sm-12">
																	<label class="custom-control custom-checkbox">
																		<input name="Permisos[]" value="<?php echo $SecPerm[Id]; ?>" <?php if( $SecPerm[Id] == $SecPerm[Fk_Permiso] ){ echo "checked"; } ?> type="checkbox" name="styled_single_checkbox" class="custom-control-input">
																		<span style="cursor: pointer;" class="custom-control-indicator"></span> <span class="custom-control-description"><?php //echo $SecPerm[Id].'-'; ?><?php echo $SecPerm[Permiso]; ?></span>
																	</label>
																</fieldset>
																<!-- End Permisos -->
															<?php } ?>
														</div>

														<!-- SubSecciones Pos2 -->
														<div class="row">
															<?php
																//Secciones
																$Query = "
																  SELECT
																  sec.Id, sec.Nombre
																  FROM KB_Secciones sec
																	WHERE sec.Posicion = '2' AND sec.Fk_Seccion = '$AppSec[Id]'
																	ORDER BY sec.Nombre
															  ";
															  $KB_SeccionesA = $mysqli->query($Query);
																$rowcount = mysqli_num_rows($KB_SeccionesA);
																if( $rowcount >= 1 ){ echo "<div class='col-sm-12'><hr style='margin-top: 10px;'></div>"; }
																mysqli_data_seek($KB_SeccionesA, 0);
																while($AppSecA = mysqli_fetch_array($KB_SeccionesA)) {
															?>
																<div class="col-sm-4">
																	<div class="card" style="border-top: 4px solid <?php echo $ColCons[$BgColorTop]; ?>; border-radius: 4px;">
																		<div class="card-body">
																			<h5><?php /*echo $AppSecA[Id].' - ';*/ echo $AppSecA[Nombre]; ?></h5>
																			<hr />
																			<div class="row">
																				<?php
																					//Permisos
																					$Query = "
																					  SELECT
																						  per.Id, per.Permiso,
																							perm.Fk_Permiso
																					  FROM KB_Permisos per
																						LEFT JOIN KB_UsuariosPermisos perm ON perm.Fk_Permiso = per.Id AND perm.Fk_Usuario = '$Usr[Id]'
																						WHERE per.Fk_Seccion = '$AppSecA[Id]'
																						ORDER BY per.Permiso
																				  ";
																				  $SecPermisos = $mysqli->query($Query);
																					mysqli_data_seek($SecPermisos, 0);
																					while($SecPerm = mysqli_fetch_array($SecPermisos)) {
																				?>
																					<!-- Permisos -->
																					<fieldset class="col-sm-12">
																						<label class="custom-control custom-checkbox">
																							<input name="Permisos[]" value="<?php echo $SecPerm[Id]; ?>" <?php if( $SecPerm[Id] == $SecPerm[Fk_Permiso] ){ echo "checked"; } ?> type="checkbox" name="styled_single_checkbox" class="custom-control-input">
																							<span style="cursor: pointer;" class="custom-control-indicator"></span>
																							<span class="custom-control-description">
																								<?php echo $SecPerm[Id].'-'; ?>
																								<?php echo $SecPerm[Permiso]; ?>
																							</span>
																						</label>
																					</fieldset>
																					<!-- End Permisos -->
																				<?php } ?>
																			</div>

																			<!-- SubSecciones Pos3 -->
																			<div class="row">
																				<?php
																					//Secciones
																					$Query = "
																					  SELECT
																					  	sec.Id, sec.Nombre
																					  FROM KB_Secciones sec
																						WHERE sec.Posicion = '3' AND sec.Fk_Seccion = '$AppSecA[Id]'
																						ORDER BY sec.Nombre
																				  ";
																				  $KB_SeccionesB = $mysqli->query($Query);
																					$rowcount = mysqli_num_rows($KB_SeccionesB);
																					if( $rowcount >= 1 ){ echo "<div class='col-sm-12'><hr style='margin-top: 10px;'></div>"; }
																					mysqli_data_seek($KB_SeccionesB, 0);
																					while($AppSecB = mysqli_fetch_array($KB_SeccionesB)) {
																				?>
																					<div class="col-sm-12">
																						<div class="card" style="border-top: 4px solid <?php echo $ColCons[$BgColorTop]; ?>; border-radius: 4px;">
																							<div class="card-body">
																								<h5><?php /*echo $AppSecB[Id].' - ';*/ echo $AppSecB[Nombre]; ?></h5>
																								<hr />
																								<div class="row">
																									<?php
																										//Permisos
																										$Query = "
																										  SELECT
																											  per.Id, per.Permiso,
																												perm.Fk_Permiso
																											  FROM KB_Permisos per
																											LEFT JOIN KB_UsuariosPermisos perm ON perm.Fk_Permiso = per.Id AND perm.Fk_Usuario = '$Usr[Id]'
																											WHERE per.Fk_Seccion = '$AppSecB[Id]'
																											ORDER BY per.Permiso
																									  ";
																									  $SecPermisosB = $mysqli->query($Query);
																										mysqli_data_seek($SecPermisosB, 0);
																										while($SecPermB = mysqli_fetch_array($SecPermisosB)) {
																									?>
																										<!-- Permisos -->
																										<fieldset class="col-sm-12">
																											<label class="custom-control custom-checkbox">
																												<input name="Permisos[]" value="<?php echo $SecPermB[Id]; ?>" <?php if( $SecPermB[Id] == $SecPermB[Fk_Permiso] ){ echo "checked"; } ?> type="checkbox" name="styled_single_checkbox" class="custom-control-input">
																												<span style="cursor: pointer;" class="custom-control-indicator"></span>
																												<span class="custom-control-description">
																													<?php echo $SecPermB[Id].'-'; ?>
																													<?php echo $SecPermB[Permiso]; ?>
																												</span>
																											</label>
																										</fieldset>
																										<!-- End Permisos -->
																									<?php } ?>
																								</div>
																							</div>
																						</div>
																					</div>
																				<?php } ?>
																			</div>
																			<!-- End SubSecciones Pos3 -->

																		</div>
																	</div>
																</div>
															<?php } ?>
														</div>
														<!-- End SubSecciones Pos2 -->

													</div>
												</div>
											</div>
										<?php } ?>
									</div>
								</div>
								<!-- End Tab Permisos -->

							</div>
							<!-- End Tabs Content -->

            </div>
          </div>

        </form>
      </div>

      <?php //require_once($Position.'footer.php'); ?>

    </div>

  </div>

  <?php require_once($Position.'scripts.php'); ?>
  <script>

  </script>
</body>

</html>
