<?php
	$Seccion      = 'Administradores';
	$NameSec      = 'Administradores';
	$SecLine      = array('Administradores', '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 CMS_Admins
	    (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 CMS_Admins SET
			    Nombre    = '$Nombre',
			    Apellidos = '$Apellidos',
			    Activo    = '$Activo',
			    $PassEdit
			    Email     = '$Email'
		    WHERE Id  = '$Id'
	    ";
	    mysqli_query($mysqli, $Query );
	    $Save = 'Ok';

	}

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

		//Sitios
		$Query = "
			UPDATE CMS_AdminsSitios SET
			Borrar   = '1'
			WHERE Fk_Administrador  = '$Id'
		";
		mysqli_query($mysqli, $Query );

		$Sucs	= $_POST['Sitios'];
		foreach( $Sucs AS $Suc ){

			//Verifica existencia
			$Query = "
				SELECT
					adm.Id
				FROM CMS_AdminsSitios adm
				WHERE adm.Fk_Administrador = '$Id' AND adm.Fk_Sitio = '$Suc'
				GROUP BY user.Id
			";
		  $Result = mysqli_query($mysqli, $Query);
		  $VerSuc = mysqli_fetch_assoc($Result);

			if( $VerSuc[Id] ){

				$Query = "
					UPDATE CMS_AdminsSitios SET
					Borrar   = '0'
					WHERE Fk_Administrador  = '$Id' AND Fk_Sitio = '$Suc'
				";
				mysqli_query($mysqli, $Query );

			}else{

				$Query = "
					INSERT INTO CMS_AdminsSitios
			    (Fk_Administrador, Fk_Sitio)
			    VALUES
			    ('$Id', '$Suc')
				";
		    mysqli_query($mysqli, $Query );

			}

		}
		$Query = "
			DELETE FROM CMS_AdminsSitios
			WHERE
				Fk_Administrador = '$Id'
				AND Borrar = '1'
		";
    $Result = mysqli_query($mysqli, $Query);

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

		//Permisos
		$Query = "
			UPDATE CMS_AdminsPermisos
	    SET
	    Borrar = '1'
	    WHERE Fk_Administrador = '$Id'
		";
    $Result = mysqli_query($mysqli, $Query);

		foreach( $Permisos AS $Permiso ){

      //Si Existe Registro
      $Query = "
	      SELECT
	      	are.Id
	      FROM CMS_AdminsPermisos are
	      WHERE are.Fk_Administrador = '$Id' AND are.Fk_Permiso = '$Permiso'
      ";
      $Result = mysqli_query($mysqli, $Query);
      $CliUsrA = mysqli_fetch_assoc($Result);
      if( $CliUsrA[Id] ){
        //Actualiza
        $Query = "
					UPDATE CMS_AdminsPermisos
	        SET
	        Borrar = '0'
	        WHERE Id = '$CliUsrA[Id]'
				";
        $Result = mysqli_query($mysqli, $Query);
      }else{
        //Inserta
        $Query = "
	        INSERT INTO CMS_AdminsPermisos
	        (
	          Fk_Administrador, Fk_Permiso
	        ) VALUES (
	          '$Id', '$Permiso'
	        )
				";
        $Result = mysqli_query($mysqli, $Query);
      }
    }
    $Query = "DELETE FROM CMS_AdminsPermisos WHERE Fk_Administrador = '$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 CMS_Admins admi
		WHERE admi.Id = '$_GET[Id]'
	";
	$Result = mysqli_query($mysqli, $Query );
	$Administrador = mysqli_fetch_assoc($Result);

	//CMS_AdminsPermisos
	$Query = "
		SELECT
			sta.Id, sta.Nombre
		FROM CMS_AdminsStatus 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>
								<li class="nav-item">
									<a class="nav-link" data-toggle="tab" href="#Sitios" role="tab">
										<span class="hidden-sm-up"><i class="ti-user"></i></span>
										<span class="hidden-xs-down">Sitios</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="">Seleccione Una Opción</option> -->
													<?php while($Sta=mysqli_fetch_array($Status)) { ?>
														<option
															value="<?php echo $Sta['Id']; ?>"
															<?php if( $Sta['Id'] == $Administrador['Activo'] ){ echo "selected='selected'"; } ?>
														>
															<?php echo $Sta['Nombre']; ?>
														</option>
													<?php } ?>
												</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 CMS_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 CMS_Permisos per
																	LEFT JOIN CMS_AdminsPermisos perm ON perm.Fk_Permiso = per.Id AND perm.Fk_Administrador = '$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[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 CMS_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 CMS_Permisos per
																						LEFT JOIN CMS_AdminsPermisos perm ON perm.Fk_Permiso = per.Id AND perm.Fk_Administrador = '$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[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 CMS_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 CMS_Permisos per
																											LEFT JOIN CMS_AdminsPermisos perm ON perm.Fk_Permiso = per.Id AND perm.Fk_Administrador = '$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[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 -->

								<!-- Tab Sitios -->
								<div class="tab-pane card-body" id="Sitios" role="tabpanel">
									<h4 class="card-title">Sitios</h4>
									<hr />
									<div class="row">

										<?php
											//Sitios
											$Query = "
											  SELECT
												  sit.Id, sit.Nombre, sit.Url, sit.Activo,
													adm.Fk_Administrador
											  FROM CMS_Sitios sit
												LEFT JOIN CMS_AdminsSitios adm ON adm.Fk_Sitio = sit.Id
												AND adm.Fk_Administrador = '$Administrador[Id]'
												ORDER BY sit.Nombre
										  ";
										  $Sitios = $mysqli->query($Query);
											while($Sitio = mysqli_fetch_array($Sitios)) {
										?>
											<!-- Sitios -->
											<fieldset class="col-sm-12" style="cursor:pointer;">
												<label class="custom-control custom-checkbox">
													<input
														name="Sitios[]" value="<?php echo $Sitio[Id]; ?>"
														<?php if( $Administrador[Id] == $Sitio[Fk_Administrador] ){ 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 $Sitio[Nombre]; ?>
														<?php if( $Sitio[Activo] == 1 ){ ?>
															<span class="label label-success">
																Activo
															</span>
														<?php } ?>
													</span>
												</label>
											</fieldset>
											<!-- End Sitios -->
										<?php } ?>

									</div>
								</div>
								<!-- End Tab Sitios -->

							</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>
