<?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" ) {

		$Nombre    = $_POST['Nombre'];
		$Apellidos = $_POST['Apellidos'];
		$Email     = $_POST['Email'];
		$Usuario   = $_POST['Usuario'];
		$Activo    = $_POST['Activo'];

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

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

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

	}

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

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

	}

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

		//Permisos
		$Permisos = $_POST['Permisos'];

		//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);
      }
    }

		//Delete Permisos
    $Query = "
			DELETE FROM KB_UsuariosPermisos
			WHERE Fk_Usuario = '$Id' AND Borrar = '1'
		";
    $Result = mysqli_query($mysqli, $Query);

	}

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

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

	//KB_UsuariosPermisos
	$Query = "
		SELECT
			sta.Id, sta.Nombre
		FROM KB_UsuariosStatus sta
		ORDER BY sta.Nombre ASC";
	$Status = mysqli_query($mysqli, $Query );

?>

<!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">
                  <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>
									<?php if( $Perms[42] ){ ?>
                  	<button type="button" class="btn btn-sm btn-secondary" onclick="window.location.href='edit.php'">Nuevo<i class="fa fa-plus m-l-10"></i></button>
									<?php } ?>
									<button type="submit" class="btn btn-sm btn-success">Guardar<i class="fa fa-check m-l-10"></i></button>
                  <input type="hidden" name="Save" value="Ok">
                  <?php if( $Administrador['Id'] ){ ?>
					<input name="Id" type="hidden" id="Id" value="<?php echo $Administrador['Id']; ?>">
				<?php }else{ ?>
				<input name="New" type="hidden" id="New" value="Ok">
				<?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">
								<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>
								<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>
							</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( $Administrador['Id'] ){ echo "Editar"; }else{ echo "Alta de"; } ?> Administrador</h4>
									<hr />
									<div class="row">

										<!-- Nombre -->
										<div class="form-group col-sm-6">
											<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 $Administrador['Nombre'];?>" autocomplete="off" parsley-trigger="change" required>
											</div>
										</div>
										<!-- End Nombre -->

										<!-- Apellidos -->
										<div class="form-group col-sm-6">
											<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 $Administrador['Apellidos'];?>" autocomplete="off" parsley-trigger="change" required >
											</div>
										</div>
										<!-- End Apellidos -->

										<!-- 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 $Administrador['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( $Administrador[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( $Administrador[Id]) { echo '0000000000';} else { } ?>" autocomplete="off" data-parsley-equalto="#pass1" type="password" required id="passWord2">
											</div>
										</div>
										<!-- End Repeat Pass -->

										<!-- 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"
												>
													<option
														value="1"
														<?php if( $Administrador['Activo'] == '1' ){ echo "selected='selected'"; } ?>
													>
														Activo
													</option>
													<option
														value="0"
														<?php if( $Administrador['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
										  ";
										  $AppSecciones = $mysqli->query($Query);
											$BgColorTop = 0;
											mysqli_data_seek($AppSecciones, 0);
											while($AppSec = mysqli_fetch_array($AppSecciones)) {
												$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 = '$Administrador[Id]'
																	WHERE
																		per.Fk_Seccion = '$AppSec[Id]'
																		AND per.Activo = '1'
																	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[Permiso]; ?>
																			<span style="color:#fff;"><?php echo $SecPerm[Id]; ?></span>
																		</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
															  ";
															  $AppSeccionesA = $mysqli->query($Query);
																$rowcount = mysqli_num_rows($AppSeccionesA);
																if( $rowcount >= 1 ){ echo "<div class='col-sm-12'><hr style='margin-top: 10px;'></div>"; }
																mysqli_data_seek($AppSeccionesA, 0);
																while($AppSecA = mysqli_fetch_array($AppSeccionesA)) {
															?>
																<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 = '$Administrador[Id]'
																						WHERE
																							per.Fk_Seccion = '$AppSecA[Id]'
																							AND per.Activo = '1'
																						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[Permiso]; ?>
																								<span style="color:#fff;"><?php echo $SecPerm[Id]; ?></span>
																							</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
																				  ";
																				  $AppSeccionesB = $mysqli->query($Query);
																					$rowcount = mysqli_num_rows($AppSeccionesB);
																					if( $rowcount >= 1 ){ echo "<div class='col-sm-12'><hr style='margin-top: 10px;'></div>"; }
																					mysqli_data_seek($AppSeccionesB, 0);
																					while($AppSecB = mysqli_fetch_array($AppSeccionesB)) {
																				?>
																					<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 = '$Administrador[Id]'
																											WHERE
																												per.Fk_Seccion = '$AppSecB[Id]'
																												AND per.Activo = '1'
																											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[Permiso]; ?>
																													<span style="color:#fff;"><?php echo $SecPermB[Id]; ?></span>
																												</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>
