<?php
	session_set_cookie_params(0);
	session_start();
	require_once('../../Connections/odonto_connection1.php');

if(isset($_SESSION['inicio']))
{
	$codigo=$_SESSION['codigo'];
	//if($_SESSION['estoy_logueado']) header("Location:" . "index0.php");
	$_SESSION['voy']='negativo';
}

if(isset($_GET['regist'])) $regist = $_GET['regist'];
else $regist = 0;

if(isset($_GET['deslogueo'])) {
	session_destroy();
	header("Location:" . "./logueado.php");
}

if(isset($_SESSION['id_delivery']))	$id_delivery = $_SESSION['id_delivery'];
else $id_delivery = 0;

if(isset($_SESSION['externo'])){
	$id_delivery = $_SESSION['externo'];
	$q = "SELECT user FROM delivery WHERE id_delivery LIKE '$id_delivery'";
	$rs= mysqli_query($odonto_connection,$q) or die("Error en $q");
	$row = mysqli_fetch_assoc($rs);
	$user = $row['user'];
}

function Delivery($buscante,$salida,$password=0,$pointer='user'){
	global $odonto_connection;
	if($password == 0) $and = "";
	else $and = " AND contra LIKE '$password' AND confirmado = 1";
	$q = "SELECT id_delivery,user,apellido,nombre,celular,hash_ingreso FROM delivery WHERE $pointer LIKE '$buscante' $and ORDER BY id_delivery DESC LIMIT 1";
	$rs= mysqli_query($odonto_connection,$q) or die("Error en $q");
	$row = mysqli_fetch_assoc($rs);
	$salida = $row[$salida]; 
	return $salida;	
}

function distance($lat1, $lon1, $lat2, $lon2, $unit) {

  $theta = $lon1 - $lon2;
  $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
  $dist = acos($dist);
  $dist = rad2deg($dist);
  $miles = $dist * 60 * 1.1515;
  $unit = strtoupper($unit);

  if ($unit == "K") {
      return ($miles * 1.609344);
  } else if ($unit == "N") {
      return ($miles * 0.8684);
  } else {
      return $miles;
  }
}

if(isset($_GET['vldcode'])){ //confirma mail
			$vldcode = $_GET['vldcode'];
			$user = $_GET['user'];
			$hash_ingreso = Delivery($user,hash_ingreso);
			if($hash_ingreso != $vldcode){ //por las dudas compruebo que sean iguales
				echo "Hubo un inconveniente!!!";
				$user = "No usuario";
			}
			else{
				$q = "UPDATE delivery SET confirmado = 1 WHERE user = '$user' ORDER BY id_delivery DESC LIMIT 1";
				$rs= mysqli_query($odonto_connection,$q) or die("Error en $q");
		
				$id_delivery = Delivery($user,id_delivery);
				session_destroy();
				session_start();
				$_SESSION['id_delivery'] = $id_delivery;
				header("Location:" . "./logueado.php");				
			}
		}
		
if(isset($_POST['submit2'])){
		$user = $_POST['email2'];
		$password = $_POST['password2'];
		$user = Delivery($user,user,$password);
		$id_delivery = Delivery($user,id_delivery,$password);
		if($user) {
			$regist = 1;
			session_destroy();
			session_start();
			$_SESSION['id_delivery'] = $id_delivery;
			//header("Location:" . "./logueado.php");
			$regist = 1;
		}
		else $regist = 99;
}

if(isset($_POST['submit'])){ //se manda mail
	
	$mail = $_POST['email'];
	//$mail = "adrianpeque001@gmail.com";
	$password = $_POST['password'];
	$nombre = $_POST['nombre'];
	$apellido = $_POST['apellido'];
	$telefono = $_POST['telefono'];
	$direccion = $_POST['direccion'];
	$hash_ingreso = md5($mail ."xxx");
	$q = "SELECT user FROM delivery WHERE user LIKE '$mail' AND confirmado = 1";
	$rs= mysqli_query($odonto_connection,$q) or die("Error en $q");
	$num_rows = mysqli_num_rows($rs);
	
	if($num_rows == 0){
	
		$q = "INSERT INTO delivery (id_delivery, time, user, contra, apellido, nombre, celular,direccion,hash_ingreso, confirmado) VALUES (NULL,CURRENT_TIMESTAMP,'$mail','$password','$apellido','$nombre','$telefono','$direccion','$hash_ingreso','0')";
		$rs= mysqli_query($odonto_connection,$q) or die("Error en $q");

		$link='http://ponderzone.com/warn/ajax/examples/logueado.php?regist=1&vldcode=' .$hash_ingreso .'&user=' .$mail  ;
			
		//$to = "mpiriz33@mailinator.com, maximiliano@pondercom.com";
		$to = $mail;
		$subject = "Ponderzone Pedidos Confirmacion";

		$message = "
		<html>
		<head>
		<title>HTML email</title>
		</head>
		<body>
		<div>
		<p style='background-color:#3b5998;color:#fff;font-size:18px'>Para confirmar identidad dale Click al Link de abajo y comenzá a disfrutar la experiencia de pedidos online de PonderZone!!!</p>
		<table style='background-color:#3b5998;color:#fff'>
		<tr><th>Tus Credenciales: </th></tr>
		<tr><td>Tu Usuario: $mail</td></tr>
		<tr><td>Tu contraseña: $password</td></tr>
		<tr>
		<td><a href='$link' style='color:#fff'>Link de Confirmación: $link</a></td>
		</tr>
		</table>
		</div>
		</body>
		</html>
		";

		// Always set content-type when sending HTML email
		$headers = "MIME-Version: 1.0" . "\r\n";
		$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

		// More headers
		$headers .= 'From: <pedidos@ponderzone.com>' . "\r\n";
		//$headers .= 'Cc: myboss@mailinator.com' . "\r\n";

		mail($to,$subject,$message,$headers);
	}
	else{
		$yaexiste = 1;
	}
}

?>

<!DOCTYPE html>
<html lang="es">
	<head>
		<meta charset="utf-8" />
		<title><?php echo 'Ponderzone Asistente Virtual'; ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  
<?php //require_once('../../inc/bootstrap.php');?>

<?php 
require_once($_SERVER['DOCUMENT_ROOT'] .'/warn/bootstrap/bootstrap_js_gral.php');
require_once($_SERVER['DOCUMENT_ROOT'] .'/warn/bootstrap/bootstrap_css_gral.php');
?>

  
	<script>
	function myFunction(d){
		switch(d) {
			case 1:
				window.open("http://ponderzone.com/app/ponderzone_qr.apk","_blanck");
			break;
			case 2:
				window.open("http://webqr.com","_blanck");
			break;
			default:
				window.open("./../../index.php","_parent");	
			}
	}
	$(document).ready(function(){
		$("#myBtn").click(function(){
		$("#myModal").modal();
		});
		$("#myBtn1").click(function(){
		$("#myModal1").modal();
		});
	});
	
	
function AnimaMaxi(){
	var count = 0;
	var id = setInterval(frame, 1000);
	var Estoy_casa = document.getElementById("Estoy_casa_anim");
	var Estoy_bar = document.getElementById("Estoy_bar_anim");
	var Movil = document.getElementById("Movil_anim");
	
	function frame() {
		if (count == 0) {
		  	if(Estoy_casa) document.getElementById("Estoy_casa_anim").innerHTML = "<b>Estoy en Casa</b> <i class='fas fa-home'></i>";
		  	if(Estoy_bar) document.getElementById("Estoy_bar_anim").innerHTML = "<font style='color:lightblue'><b>Estoy en Bar</b> <i class='fas fa-beer'></i></font>";
		  	if(Movil) document.getElementById("Movil_anim").innerHTML = "<h5 class='display-6 font-weight-bold text-white'><i class='fas fa-mobile-alt fa-2x' aria-hidden='true'></i>&nbsp;&nbsp;&nbsp;Creamos la WebApp para tu negocio</h5>";
		 	count++;
			} else {
				if(Estoy_casa) document.getElementById("Estoy_casa_anim").innerHTML = "<font  style='color:lightblue'><b>Estoy en Casa</b> <i class='fas fa-home'></i></font>";
				if(Estoy_bar) document.getElementById("Estoy_bar_anim").innerHTML = "<b>Estoy en Bar</b> <i class='fas fa-beer'></i>";
				if(Movil) document.getElementById("Movil_anim").innerHTML = "<h5 class='display-6 font-weight-bold text-white'><i class='fas fa-mobile fa-2x' aria-hidden='true'></i>&nbsp;&nbsp;&nbsp;Creamos la WebApp para tu negocio</h5>";
				
			count = 0;
			}
		}
	}

</script>

<style>
	.footer {
   position: fixed;
   left: 0;
   bottom: 0;
   width: 100%;
   background-color: black;
   color: white;
   text-align: center;
}

</style>
	
	</head>
	<body <?php echo "onload = AnimaMaxi()";
	if(!isset($_GET['latitud']) && $id_delivery){echo ";geoloc()";} ?>>


<?php if(!$id_delivery){require_once('../../inc/cabecera.php');}?>

<div class="container-fluid" style="color:#5d82a6">
  <!-- Trigger the modal with a button -->
  <?php 
  if($regist != 2 && !$id_delivery){
		echo "
		<div class='row text-center'>
			<div class='col-md-4 pt-2 pl-2 pb-2'>
				<button type='button' class='btn btn-dark btn-lg btn-logueado btn-xl shadow' id='myBtn'><div id='Estoy_casa_anim'></div></button>
			<br>
			</div>
			<div class='col-md-4 pt-2 pl-2 pb-2'>
				<button type='button' class='btn btn-secondary btn-lg btn-logueado btn-xl shadow' id='myBtn1'><div id='Estoy_bar_anim'></div></button>
				<br>
			</div>
			<div class='col-md-4 pt-2 pl-2 pb-2'>
				<button type='button' class='btn btn-light btn-lg btn-logueado btn-xl shadow' onclick='myFunction()' id='myBtn2'><i class='fas fa-archway'></i> Tengo un Bar</button>
				<br>
			</div>";
		echo "</div>";
		
		if(!isset($_GET['mailenviado']) && !isset($_GET['regist']) && !isset($_GET['tenesqueestar'])) require_once('carousell.php');

	}
	else {
		if($id_delivery){
			$nombre = Delivery($id_delivery,nombre,0,id_delivery);
			echo "<div class='row text-center'>";
			echo "<div class='col-md-6' style='background-color:white'><h5><i class='fas fa-store-alt'></i> Locales cerca tuyo $nombre</h5></div>";
			echo "<div class='col-md-6'><a href='logueado.php?deslogueo=1' type='button' class='btn btn-secondary btn-block btn-lg shadow degrade'><span class='iconify' data-icon='oi:account-logout' data-inline='false'></span> Desloguearse</a></div>";
			echo "</div>";
			}
		}
  ?>
  
  <!-- The Modal -->
  <div class="modal fade" id="myModal">
    <div class="modal-dialog">
      <div class="modal-content">
      
        <!-- Modal Header -->
        <div class="modal-header">
          <h4 class="modal-title">Pedidos Online Ponderzone</h4>
          <button type="button" class="close" data-dismiss="modal">×</button>
        </div>
        
        <!-- Modal body -->
        <div class="modal-body">
			<div class='container' style='background-color:#5d82a6;color:#fff'>
				<h3>Si estás en tu casa:</h3>	
				<label for="email2">(y ya tenés una cuenta)</label>
				<h6>Podrás hacer el pedido bajo la forma de delivery o Take Away</h6>	
				
				<form role="form" action="logueado.php" method="POST" id="contactForm">
						<div class="form-group">
						<label for="email2">Usuario:</label>
						<input type="email" class="form-control" id="email2" name="email2" placeholder=mimail@example.com pattern='^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$' required>
						</div>
						<div class="form-group">
						<label for="password2">Contraseña</label>
						<input type="password" class="form-control" pattern="(?=.*\d)(?=.*[a-z]).{4,}" id="password2" name="password2" placeholder="Password" required>
						</div>
						<p>
						<button type="submit" id="submit2" name="submit2" class="btn btn-success">Ingresa</button>
						<a href='./logueado.php?regist=2' class='btn btn-info' role='button'>Registrate</a>
						<br><label></label>					  
				</form>
				</div>
		</div>
        
        <!-- Modal footer -->
        <div class="modal-footer">
          <button type="button" class="btn btn-danger" data-dismiss="modal">Cerrar</button>
        </div>
        
      </div>
    </div>
  </div>
  <!-- The Modal -->
  <div class="modal fade" id="myModal1">
    <div class="modal-dialog">
      <div class="modal-content">
      
        <!-- Modal Header -->
        <div class="modal-header">
          <h4 class="modal-title">Pedidos Online Ponderzone</h4>
          <button type="button" class="close" data-dismiss="modal">×</button>
        </div>
        
        <!-- Modal body -->
        <div class="modal-body">
			<div class='container' style='background-color:#5d82a6;color:#fff'>
			<div class="col">
			<h3>Si estás en el bar</h3>
			<p>Lee el Codigo QR de tu mesa con tu Celular y podrás interactuar con el staff del bar sin contacto alguno con la carta de papel.</p>
			<p>Si no tenés lector de QR instalado tenés estas dos opciones<span class='iconify' data-icon='bx:bx-down-arrow-circle' data-inline='false'></span></p>
			<button type="button" class="btn btn-primary btn-lg btn-block" style="background-color:#82a4c4;border-color:#82a4c4" name="read" onclick="myFunction(2)"><span class="iconify" data-icon="jam:qr-code" data-inline="false"></span> <b>Leer Codigo QR Online<br></b></button>
			<button type="button" class="btn btn-info btn-lg btn-block" style="background-color:#34495E;border-color:#fff" name="servicio" onclick="myFunction(1)"><span class="iconify" data-icon="oi:cloud-download" data-inline="false"></span> <b>Descargá la App</b></button>
			<br>
		</div>
		
			</div>
		</div>
        
        <!-- Modal footer -->
        <div class="modal-footer">
          <button type="button" class="btn btn-danger" data-dismiss="modal">Cerrar</button>
        </div>
        
      </div>
    </div>
  </div>
  
  <header>
			<h3><?php 
			if(isset($_GET['tenesqueestar']) || $regist == 99) {
				
			echo '<div class="alert alert-warning alert-dismissible">
    <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
    <strong>Atención!</strong> Tienes que estar logueado!
  </div>';
				
			}
			if(isset($_GET['mailenviado'])) {
				if($yaexiste) {
					echo '<div class="alert alert-danger alert-dismissible">
						<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
						<strong>Atención!</strong> Ya existe un usuario con ese correo! Intenta con otro!
						</div>';
				}
				else {
					
					echo '<div class="alert alert-danger alert-dismissible">
						<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
						<strong>Atención!</strong> Se ha enviado un correo de confirmación! Revisa tu correo por favor. Puede ser que se encuentre en la bandeja de Span
						</div>';
					
				}	
			}
			
			if ($id_delivery) {
				echo "<script>";
				echo 'function geoloc() {
				d=document.getElementById("demo");
				if (navigator.geolocation){
					d.innerHTML="Buscando bares cercanos...<div class=spinner-border></div>";
					navigator.geolocation.getCurrentPosition(showPosition);
				   }
				else {
				   d.innerHTML="<p>Lo sentimos, tu dispositivo no admite la geolocalización.</p>";
				   }
				}
				function showPosition(position){
				  latitud=position.coords.latitude;
				  longitud=position.coords.longitude;
				  //d.innerHTML+="<p>Latitud: "+latitud+"</p>";
				  //d.innerHTML+="<p>Longitud: "+longitud+"</p>";
					window.location="logueado.php?latitud="+latitud+"&longitud="+longitud;
				}
				function showError(error){
				  switch(error.code) {
					case error.PERMISSION_DENIED:
					  d.innerHTML+="<p>.....</p>"
					  break;
					case error.POSITION_UNAVAILABLE:
					  d.innerHTML+="<p>La información de la localización no está disponible.</p>"
					  break;
					case error.TIMEOUT:
					  d.innerHTML+="<p>El tiempo de espera para buscar la localización ha expirado.</p>"
					  break;
					case error.UNKNOWN_ERROR:
					  d.innerHTML+="<p>Ha ocurrido un error desconocido.</p>"
					  break;
					}
				  }';
				echo "</script>";
echo "<div id='demo' style='background-color:white'></div>";
			}
					?></h3>
			
			<!-- <nav>El men&uacute; si procediese</nav> --> <!-- Etiqueta comentada al no tener men&uacute; -->
		</header>
		
		
  
    
<?php if($regist != 1 && !isset($_GET['mailenviado'])){
	echo "<div class=\"row\">";
		if($regist == 2){// $regist = 2 (se va a registrar)
			echo '<div class="col-sm-4">';
			echo "<div class='container' style='background-color:#5d82a6;color:#fff'>
				<h3>Registrate:</h3>
				<form role=\"form\" action=\"logueado.php?mailenviado=1\" method=\"POST\" id=\"contactForm\">
					<div class=\"form-group\">
					<label for=\"email\">email</label>
					<input type=\"email\" class=\"form-control\" id=\"email\" name=\"email\" placeholder=\"mimail@example.com\" pattern='^(([^<>()\[\]\\.,;:\s@\"]+(\.[^<>()\[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$' required>
					</div>
					<div class=\"form-group\">
					<label for=\"password\">Pass (min 4 carat,1 Mayus,1 num)</label>
					<input type=\"password\" class=\"form-control\" pattern=\"(?=.*\d)(?=.*[a-z]).{4,}\" id=\"password\" name=\"password\" placeholder=\"Password\" required>
					</div>
					<div class=\"form-group\">
					<label for=\"nombre\">Tu Nombre</label>
					<input type=\"text\" class=\"form-control\" pattern=\"^.{3,25}$\" id=\"nombre\" name=\"nombre\" placeholder=\"Tu Nombre\" required>
					</div> 
					<div class=\"form-group\">
					<label for=\"apellido\">Tu Apellido</label>
					<input type=\"text\" class=\"form-control\" pattern=\"^.{3,25}$\" id=\"apellido\" name=\"apellido\" placeholder=\"Tu Apellido\" required>
					</div>
					<div class=\"form-group\">
					<label for=\"telefono\">Tu Teléfono</label>
					<input type=\"text\" class=\"form-control\" pattern=\"^.{3,25}$\" id=\"telefono\" name=\"telefono\" placeholder=\"Tu Telefono\" required>
					</div>
					<div class=\"form-group\">
					<label for=\"telefono\">Dirección</label>
					<input type=\"text\" class=\"form-control\" pattern=\"^.{3,25}$\" id=\"direccion\" name=\"direccion\" placeholder=\"Tu Direccion\" required>
					</div>
					<p>
					<button type=\"submit\" id=\"submit\" name=\"submit\" class=\"btn btn-primary\">Registrate</button>
					<button type='button' class='btn btn-warning shadow' id='myBtn'>Ya tengo cuenta</div>
					<br><label></label></form>
				</div>
		";
	}
	
	/*echo "<div class=\"col-sm-4\">
				<img src='pagina/celu_1.jpg' style='height:200px'> <img src='pagina/celu_2.jpg' style='height:200px'> <img src='pagina/celu_3.jpg' style='height:200px'>
			</div>"; */
					
}
echo "</div>";//cierra la fila
echo "<div class='container-fluid' style='background-color:white'>";
	
	//$q = "SELECT id_datos,nombre,negocio,direccion,abre_maniana,cierra_maniana,instagram,facebook,twiter,latitud,longitud FROM datos";
	$q = "SELECT id_datos,latitud,longitud FROM datos WHERE no_delivery = 0";
	$rs= mysqli_query($odonto_connection,$q) or die("Error en $q");
	if(!$rs)
	echo ("Error:" .mysqli_error($odonto_connection));
	$num=mysqli_num_rows($rs);
	
	$contador = 0;
	$orden = array();
	$reorden = array();
	
	if(isset($_GET['latitud'])){
		$latitud = $_GET['latitud'];
		$longitud = $_GET['longitud'];
		//if($latitud) $distancia = distance($latitud,$longitud,-32.944017,-60.665057,"K");
		while ($num){
			$row = mysqli_fetch_assoc($rs);
			$orden[$row['id_datos']] = distance($latitud,$longitud,$row['latitud'],$row['longitud'],"K");
			$num--;
		}
	}  //fin if
	else{
		while ($num){
			$row = mysqli_fetch_assoc($rs);
			$orden[$row['id_datos']] = $row['id_datos'];
			$num--;
		}
	}
		
	asort($orden);
	
	foreach($orden as $x => $x_value) {
		//echo "Key=" . $x . ", Value=" . $x_value;
		$reorden[] = $x;
	}

echo "<div class='row text-center' style='font-size:12px'>";
		
	foreach($reorden as $x => $x_value) {
		//echo "Key=" . $x . ", Value=" . $x_value;
		
		$q = "SELECT id_datos,nombre,negocio,direccion,telefono,abre_maniana,cierra_maniana,latitud,longitud FROM datos WHERE id_datos = '$x_value' LIMIT 1";
		$rs= mysqli_query($odonto_connection,$q) or die("Error en $q");
		if(!$rs)
		echo ("Error:" .mysqli_error($odonto_connection));
		$num=mysqli_num_rows($rs);
		$row = mysqli_fetch_assoc($rs);

			echo "<div class='col-sm-2'>";
					echo $row['nombre'];
					echo "<br>";
					$link_imagen = "fondos/".$row['negocio']."/almacen_deluca.jpg";
					$link_logueo = "logueado_analiza_codigos.php?negocio=".$row['negocio'];
					if(!$id_delivery) $link_logueo = "logueado.php?tenesqueestar=1";
					if (file_exists($link_imagen))echo "<a href=\"$link_logueo\"><img src=$link_imagen style='width:210px;height:180px'></a>";
					echo "<p>".$row['direccion'];
					echo " | ".$row['telefono'];
					//echo "<br>";
					date_default_timezone_set("America/Buenos_aires");
					$timer=date("Y-m-d H:i:s");
					$horaAhora = new DateTime($timer);
					$abre_maniana=$row['abre_maniana'];
					$abre_maniana = new DateTime($abre_maniana);
					$cierra_maniana=$row['cierra_maniana'];
					$cierra_maniana = new DateTime($cierra_maniana);
					$horaAhora = $horaAhora->format('H');
					$abre_maniana = $abre_maniana->format('H');
					$cierra_maniana = $cierra_maniana->format('H');
					//$interval = $horaInicio->diff($horaTermino);
					if( $horaAhora >= $abre_maniana && $horaAhora <= $cierra_maniana) {
						echo " <font style='color:#00bb2d'><b>Abierto</b></font>";
					} else {
						echo " <font style='color:red'><b>Cerrado</b></font>";
					} 
					echo "<br>";
					echo "<HR>";
				echo "</div>";//cierra col
			
			}//termina foreach
echo "</div>";		
echo "<br><br>";
?>
        
		
</div>

<div class="footer">
  <p> Contacto: 3416656878 / 3416755827 - contacto@ponderzone.com - By Ponderzone Systems - © 2020 All Rights Reserved&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='https://www.facebook.com/Ponderzone-100493088401968' target='blank'><i class='fab fa-facebook-square'></i></a> <a href='https://twitter.com/Ponderzone1' target='blank'><i class='fab fa-twitter-square' style='color:lightblue'></i></a> <a href='https://www.youtube.com/embed/z1EWie2VVzI\' target='blank'><i class='fab fa-youtube-square' style='color:red' ></i></a></p>
</div>
</body>
</html>