<?php
	$seccion      = 'Tiendas';
	$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');
	require_once($position.'assets/paginador1.php');

  //Buscador
  $Where = "
    WHERE
      tn.id != 0
  ";

  if( $_GET['buscar'] == 'Ok' ){

    $Bus = "&buscar=Ok";

    //Nombre
    if( $_GET['nom'] ){
      $fil_nom = $_GET['nom'];
      $Where .= "
        AND tn.nombre LIKE '%$fil_nom%'
      ";
      $Bus .= "&nom=".$fil_nom;
    }
    //End Nombre

		//Tendero
    if( $_GET['ten'] ){
      $fil_ten = $_GET['ten'];
      $Where .= "
        AND  ut.fk_usuario = '$fil_ten'
      ";
      $Bus .= "&ten=".$fil_ten;
    }
    //End Tendero

    //Estado
    if( $_GET['est'] ){
      $fil_est = $_GET['est'];
      $Where .= "
        AND tn.fk_estado = '$fil_est'
      ";
      $Bus .= "&est=".$fil_est;
    }
    //End Estado

		//Municipio
    if( $_GET['mun'] ){
      $fil_mun = $_GET['mun'];
      $Where .= "
        AND tn.fk_municipio = '$fil_mun'
      ";
      $Bus .= "&mun=".$fil_mun;
    }
    //End Municipio

  }

	//Paginación
  if (isset($_GET['pgn']))
  {
    $pgn =  $_GET['pgn']; // $pg es la pagina actual
  }
  else{
    $pgn = 0;
  }
  $cantidad = 20; // cantidad de resultados por página
  $PagerLap = $cantidad / 10;
  $inicial = $pgn * $cantidad;

  //Total Tiendas
  $Query = "
		SELECT
			COUNT(tn.Id) AS Total
		FROM
			onecoded_SwitchPointApp.tiendas tn
		LEFT JOIN usuarios_tiendas ut ON ut.fk_tienda = tn.id
		LEFT JOIN usuarios_app ua ON ua.id = ut.fk_usuario
		LEFT JOIN cat_estados ce ON ce.id = tn.fk_estado
		LEFT JOIN cat_municipios cm ON cm.id = tn.fk_municipio AND cm.fk_estado = tn.fk_estado
		$Where
  ";
  $Result = mysqli_query($mysqli, $Query);
  $ArtTotal = mysqli_fetch_assoc($Result);
  $total_records = $ArtTotal[Total];
  $pages = intval($total_records / $cantidad);

  //Tiendas
  $Query = "
		SELECT
			 tn.id,
	     ut.fk_usuario,
	     tn.nombre,
	     concat_ws(' ', ua.nombre, ua.apellido_paterno, ua.apellido_materno) as tendero,
	     tn.fk_pais,
	     tn.fk_estado,
	     ce.estado,
	     tn.fk_municipio,
	     cm.municipio,
	     tn.codigo_postal,
	     tn.colonia,
	     tn.calle,
	     tn.no_exterior,
	     tn.no_interior,
	     tn.referencia,
	     tn.lat,
	     tn.lng,
	     tn.fk_clasificacion,
	     tn.status
		FROM
			onecoded_SwitchPointApp.tiendas tn
		LEFT JOIN usuarios_tiendas ut ON ut.fk_tienda = tn.id
		LEFT JOIN usuarios_app ua ON ua.id = ut.fk_usuario
		LEFT JOIN cat_estados ce ON ce.id = tn.fk_estado
		LEFT JOIN cat_municipios cm ON cm.id = tn.fk_municipio AND cm.fk_estado = tn.fk_estado
		$Where
		ORDER BY tn.nombre ASC
		LIMIT $inicial, $cantidad
  ";
  $Tiendas = mysqli_query($mysqli, $Query);

?>
<!DOCTYPE html>
<html lang="es_MX">
  <?php require_once($position.'head.php'); ?>

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

                    <!-- 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/">Tenderos</a></li>
                              <li class="breadcrumb-item active"><?php echo $seccion; ?></li>
                            </ol>
                          </div>
                        </div>
                      </div>
                    </div>
                    <!-- /page title -->

                    <!-- secciones  -->

										<!-- Botones -->
										<div class="row">
											<div class="col-12 text-right">

												<!-- Btn Nueva -->
												<button
													type="button" class="btn btn-secondary btn-sm"
													onclick="window.location.href='tienda'"
												>
													<i class="ri-store-2-line"></i>
													&nbsp; Nueva Tienda
												</button>
												<!-- End Btn Nueva -->

											</div>
											<div class="col-12" style="height: 5px;">&nbsp;</div>
										</div>

										<!-- Tiendas -->
                    <div class="row">

											<!-- Buscador -->
											<div class="col-12">

												<div class="card">
													<div class="card-body">
														<form method="get">
															<div class="row">

																<!-- Tienda -->
																<div class="col-sm-5">
																	<div class="form-group">
																		<label class="control-label">Tienda</label>
																		<input name="nom" value="<?php echo $fil_nom; ?>" type="text"
																			autocomplete="off"
																			class="form-control form-control-sm"
																		>
																	</div>
																</div>
																<!-- End Tienda -->

																<!-- Tendero -->
																<div class="col-sm-7">
																	<div class="form-group">
																		<label class="control-label">Tendero</label>
																		<div class="controls">
																			<select
																				class="form-control form-control-sm"
																				name="ten"
																				data-toggle="select2"
																			>
																				<option></option>
																			 	<?php
																					//Tenderos
																					$Query = "
																						SELECT
																							us.id,
																							concat(us.nombre,' ',us.apellido_paterno,' ',us.apellido_materno) as tendero
																						FROM onecoded_SwitchPointApp.usuarios_app us
																						WHERE
																							us.fk_usuario_tipo = 2
																							AND us.activo = 1
																						ORDER BY tendero ASC
																					";
																					$Tenderos = $mysqli->query($Query);
																			 		mysqli_data_seek($Tenderos, 0);
																					while($Ten = mysqli_fetch_array($Tenderos)) {
																				?>
																			 	<option
																					<?php if( $Ten['id'] == $fil_ten ){ echo 'selected="selected"'; } ?>
																					value="<?php echo $Ten['id']; ?>"
																				><?php echo $Ten['tendero']; ?></option>
																			 <?php } ?>
																		 </select>
																		</div>
																	</div>
																</div>
																<!-- End Tendero -->

																<!-- Estado -->
																<div class="col-sm-3">
																	<div class="form-group">
																		<label class="control-label">Estado</label>
																		<div class="controls">
																			<select
																				class="form-control form-control-sm"
																				name="est"
																				data-toggle="select2"
																			>
																				<option value="">Todos</option>
																				<?php
																					//Estados
																					$Query = "
																						SELECT
																							est.id, est.estado
																						FROM cat_estados est
																						ORDER BY est.estado ASC
																					";
																					$Ests = $mysqli->query($Query);
																					mysqli_data_seek($Ests, 0);
																					while($Est = mysqli_fetch_array($Ests)) {
																				?>
																					<option
																						<?php if( $Est['id'] == $fil_est ){ echo 'selected="selected"'; } ?>
																						value="<?php echo $Est['id']; ?>"
																					>
																						<?php echo $Est['estado']; ?>
																					</option>
																				<?php } ?>
																			</select>
																		</div>
																	</div>
																</div>
																<!-- End Estado -->

																<!-- Municipio -->
																<div class="col-sm-3">
																	<div class="form-group">
																		<label class="control-label">Municipio</label>
																		<div class="controls">
																			<select
																				class="form-control form-control-sm"
																				name="mun"
																				data-toggle="select2"
																			>
																				<option value="">Todos</option>
																				<?php
																					//Municipio
																					$Query = "
																						SELECT
																							mun.id, mun.municipio
																						FROM cat_municipios mun
																						WHERE mun.fk_estado = '$fil_est'
																						ORDER BY mun.municipio ASC
																					";
																					$Muns = $mysqli->query($Query);
																					mysqli_data_seek($Muns, 0);
																					while($Mun = mysqli_fetch_array($Muns)) {
																				?>
																					<option
																						<?php if( $Mun['id'] == $fil_mun ){ echo 'selected="selected"'; } ?>
																						value="<?php echo $Mun['id']; ?>"
																					>
																						<?php echo $Mun['municipio']; ?>
																					</option>
																				<?php } ?>
																			</select>
																		</div>
																	</div>
																</div>
																<!-- End Municipio -->

																<!-- Filtrar -->
																<div class="col-sm-3">
																	<div class="form-group">
																		<label class="control-label">.</label>
																		<button class="btn btn-success btn-sm btn-block" type="submit" name="button">Filtrar <i class="fa fa-search mar-l-5"></i></button>
																		<input type="hidden" name="buscar" value="Ok" />
																	</div>
																</div>
																<!-- End Filtrar -->

																<!-- Total -->
																<div class="col-sm-3">
																	<div class="form-group">
																		<label class="control-label">Total Tiendas</label>
																		<input
																			readonly
																			type="text"
																			class="form-control form-control-sm"
																			autocomplete="off"
																			placeholder=""
																			value="<?php echo $total_records; ?>"
																		>
																	</div>
																</div>
																<!-- End Total -->

															</div>
														</form>
													</div>
												</div>

											</div>
											<!-- End Buscador -->

                      <div class="col-12">
                        <div class="card">
                          <div class="card-body">
                            <h4 class="header-title">Lista de <?php echo $seccion; ?></h4>
                            <p class="text-muted font-13 mb-4">
                                Registro de tiendas de Switch Point app.
                            </p>

														<!-- Tabla -->
                            <table class="table dt-responsive nowrap w-100">
                              <thead>
                                <tr>
                                  <th style="width:300px;">Tienda</th>
                                  <th>Ubicación</th>
																	<th style="width:120px;">Estatus</th>
																	<th style="width:120px;">&nbsp;</th>
                                  <th style="width:20px;">&nbsp;</th>
                                </tr>
                              </thead>
                              <tbody>
																<?php
																	mysqli_data_seek($Tiendas, 0);
																	while($Tie = mysqli_fetch_array($Tiendas)) {
																?>
                                  <tr>

																		<!-- Tienda -->
                                    <td>
																			<div>
																				<i class="fa fa-home m-r-5"></i>
																				<?php echo $Tie['nombre']; ?>
																			</div>
																			<div>
																				<i class="fa fa-user m-r-8"></i>
																				<?php echo $Tie['tendero']; ?>
																			</div>
																		</td>
																		<!-- End Tienda -->

																		<!-- Ubicación -->
                                    <td>
																			<div>
																				<?php echo $Tie['estado']; ?>
																			</div>
																			<div>
																				<?php echo $Tie['municipio']; ?>
																			</div>
																			<div>
																				<?php echo $Tie['codigo_postal']; ?>
																			</div>
																		</td>
																		<!-- End Ubicación -->

																		<!-- Estatus -->
																		<td class="text-center">
																			<?php if ($Tie['status'] == 1){$btnClass = "btn-success"; $btnStatus = "Activo";}else{$btnClass = "btn-primary"; $btnStatus = "Inactivo";} ?>
																			<button class="btn <?php echo $btnClass ?> btn-xs"><?php echo $btnStatus ?></button>
																		</td>
																		<!-- End Estatus -->

																		<!-- Editar -->
																		<td>
																			<!-- Btn Editar -->
																			<a
																				class="btn btn-outline-secondary waves-effect btn-xs"
																				href="tienda?id=<?php echo $Tie['id'];?>"
																			>
																				<i class="fe-edit-1"></i>
																				Editar
																			</a>
																			<!-- End Btn Editar -->
																		</td>
																		<!-- End Editar -->

																		<!-- Eliminar -->
																		<td>
																			<a
                                        class="btn btn-danger waves-effect waves-light btn-xs"
                                        href="#">
                                        <i class="fa fa-times"></i>
                                      </a>
																		</td>
																		<!-- End Eliminar -->

                                  </tr>
																<?php } ?>
                              </tbody>
                            </table>
														<!-- Edn Tabla -->

														<!-- Paginador -->
														<div class="m-t-40 text-center">
															<!-- <button class="btn btn-secondary">< Primera</button> -->

															<?php
																$cantRegistros  = $total_records / $PagerLap;
																$pgnActual      = $_GET['pgn'];
																$pag            = new Paginador();
																$datos          = $pag->paginar($pgnActual, $cantRegistros);
																if ($datos) {
																	'Pagina: ' . ($_GET['pgn'] + 1) . ' de ' . $pag->getCantidadPaginas() . '<br />';
															?>
																<?php
																	foreach( $datos as $enlace ) {
																?>
																	<a
																		href="?pgn=<?php
																			echo $enlace['numero'];
																			echo $Bus;
																		?>"
																	>
																		<button type="button" class="btn btn-secondary"><?php echo $enlace['vista']; ?></button>
																	</a>
																<?php } ?>
															<?php } ?>

														</div>
														<!-- End Paginador -->

                          </div> <!-- end card body-->
                        </div> <!-- end card -->
                      </div><!-- end col-->
                    </div>
                    <!-- End Tiendas -->

                  </div> <!-- /container -->

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

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

          </div>

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


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

      <?php require_once($position.'scripts.php') ?>

    </body>
</html>
