<?php
require_once('connect.php');
include("functions.php");
$error = "";
global $con;
if(false && !isset($_REQUEST['test'])){
	die('<center><img src="img/page_under_construction.png" style="text-align:center" ></center>');
}
$query = "SELECT COUNT(ID)>=5 as MultipleLogin FROM `LOGIN_LOG` WHERE `LoginDate` BETWEEN DATE_ADD(DATE_ADD(NOW(), INTERVAL -4 HOUR), INTERVAL -2 MINUTE) AND DATE_ADD(NOW(), INTERVAL -4 HOUR) AND IPAddress = '" . $_SERVER['REMOTE_ADDR'] .  "' AND Result = 0";
$result = mysqli_query($con, $query);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$multipleLogin = $row['MultipleLogin'];

if(isset($_POST['username']) && isset($_POST['password'])){
	
	
	
	$query = "SELECT 'C' as `Type` FROM CUSTOMER WHERE AccountNumber = '" . mysqli_real_escape_string($con, $_POST['username']) . "' UNION SELECT 'SM' as `Type` FROM SALESMAN WHERE `Username` LIKE '" . mysqli_real_escape_string($con, $_POST['username']) . "'";
	$result = mysqli_query($con, $query);
	if(mysqli_num_rows($result)){
		$row = mysqli_fetch_array($result);
		$type = $row['Type'];
	}else{
		$type = $_POST['type'];	
	}
	
	
	if($_POST['username'] == "" || $_POST['password'] == ""){
		$error = "The username or password was left blank.";
		$correct = false;
	}else{
		$correct = true;
	}
	
	////codigo para ignorar captcha a request con user '303329' o direct key '01aa02bb03'
	if(isset($_REQUEST['dk']) && $_REQUEST['dk'] == "01aa02bb03" || $_REQUEST['username'] == "303329"){
		
	}else{
		if($correct && $multipleLogin){
			$response = file_post_contents('https://www.google.com/recaptcha/api/siteverify', array("secret" => "6LdShQoUAAAAADlpJYAoImsSeiZlOHlVTii_aVT7", 'response' => $_POST['g-recaptcha-response'], 'remoteip' => $_SERVER['REMOTE_ADDR']));
			$response = json_decode($response);
			if($response->success != true){
				$error = "Captcha Error! Favor de hacer click en 'No soy un Robot' ej. <img style='width: 200px;' src='https://upload.wikimedia.org/wikipedia/en/c/cf/NoCAPTCHA_reCAPTCHA.gif' />";
				$correct = false;
			}else{
				$correct = true;
			}
		}	
	}
	
	
	$username = mysqli_real_escape_string($con, $_POST['username']);
	$password = md5(($_POST['password']));
	if($type == "C"){
		$query = "SELECT * FROM CUSTOMER WHERE AccountNumber LIKE '$username'";
	}elseif($type == "SM"){
		$query = "SELECT * FROM SALESMAN WHERE Username LIKE '$username'";
	}
	$result = mysqli_query($con, $query);
	$row = mysqli_fetch_array($result);
	
	
	
	if($row['Password'] == $password){
		if($row['Password'] == $password)
			if ($type == "C" && $row['Active']) {
				$correct = true;	
			}elseif ($type == "SM") {
				$correct = true;	
			}else {
				$correct = false;
				$error = "ACCESO DENEGADO<br />Favor de contactar a su vendedor, Gracias.";
			}
			
		else {
			$correct = false;
			$error = "El n&uacute;mero de cuenta o contrase&ntilde;a no es v&aacute;lida. Haga click <a onclick=\"$('#forgotPasswordModal').modal('toggle')\" href=\"#\">aqu&iacute;</a> para cambiar su contrase&ntilde;a.";
		}
		
	} else {
		$correct = false;
		$error = "El n&uacute;mero de cuenta o contrase&ntilde;a no es v&aacute;lida. Haga click <a onclick=\"$('#forgotPasswordModal').modal('toggle')\" href=\"#\">aqu&iacute;</a> para cambiar su contrase&ntilde;a.";
	}
	
	
	LoginLog($type, $username, $correct);
	
	if($correct && $type == "C"){
		$_SESSION['LoggedIn'] = 1;
		$_SESSION['isCustomer'] = true;
		$_SESSION['AccountNumber'] = $row['AccountNumber'];
		$_SESSION['LastLogin'] = $row['LastLogin'];
		$_SESSION['Name'] = $row['Name'];
		
		$min = mt_rand();
		$hash   = md5(mt_rand($min, $min + mt_rand()));
		if (isset($_POST['keeplogin'])) {
			setcookie("hash", $hash, time() + (86400 * 7), "/");
			setcookie("type", "customer", time() + (86400 * 7), "/");
		}
		$query = "UPDATE CUSTOMER SET LastLogin = DATE_ADD(NOW(), INTERVAL -4 HOUR), CookieHash = '$hash', CookieExpire = DATE_ADD(DATE_ADD(NOW(), INTERVAL 7 DAY), INTERVAL -4 HOUR) WHERE AccountNumber LIKE '$username'";
		
		$result = mysqli_query($con, $query);
		header("Location: index.php?splash=true");
		exit();
	}elseif($correct && $type == "SM"){
		$_SESSION['ShownCustomerActivity'] = false;
		$_SESSION['LoggedIn'] = 1;
		$_SESSION['isCustomer'] = false;
		$_SESSION['SalesmanID'] = $row['ID'];
		$_SESSION['Name'] = $row['FullName'];
		$_SESSION['LastLogin'] = $row['LastLogin'];
		$_SESSION['pricePlanMode'] = false;
		$_SESSION['AccountNumber'] = '';
		
		$min = mt_rand();
		$hash   = md5(mt_rand($min, $min + mt_rand()));
		if (isset($_POST['keeplogin'])) {
			setcookie("hash", $hash, time() + (86400 * 7), "/");
			setcookie("type", "salesman", time() + (86400 * 7), "/");
		}
		
		
		$query = "UPDATE SALESMAN SET LastLogin = DATE_ADD(NOW(), INTERVAL -4 HOUR), CookieHash = '$hash', CookieExpire = DATE_ADD(DATE_ADD(NOW(), INTERVAL 7 DAY), INTERVAL -4 HOUR) WHERE Username LIKE '$username'";
		$result = mysqli_query($con, $query);
		header("Location: index.php?splash=true");
		exit();
	}
}
		header("Location: login.php");
		exit();
?>
<!DOCTYPE html>
<html lang="en">
	<head>
		<meta http-equiv="content-type" content="text/html; charset=UTF-8">
		<meta charset="utf-8">
		<title><?= $config['CompanyName'] ?></title>
		<meta name="generator" content="Bootply" />
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
		<!-- script references -->
			<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
			<script src="js/bootstrap.min.js"></script>
		<link href="css/bootstrap.min.css" rel="stylesheet">
		
		<!-- Icons -->
		<link rel="apple-touch-icon" sizes="57x57" href="img/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="img/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="img/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="img/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="img/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="img/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="img/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="img/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="img/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192"  href="img/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="img/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="img/favicon-16x16.png">
<link rel="manifest" href="img/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
		
		<!--[if lt IE 9]>
			<script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>
		<![endif]-->
		<link href="css/styles.css" rel="stylesheet">
		
		<script src='https://www.google.com/recaptcha/api.js?hl=es' async defer></script>

			<style>
				
			
		</style>
	</head>
	<body>
		<noscript>
		  <div class="jumbotron">
		    <h2></h2>
		    <center>
		    <img src="img/<?= $config['Logo'] ?>" class="img-responsive" style="width: auto;" alt="" />
		    
		    <p>This page needs JavaScript activated to work. <br />
		    Please change your browser settings to enable Javascript</p>
		    
		    </center>
		  </div>
		
		  
		  <style>.modal-dialog { display:none; }</style>
		</noscript>
		
<!--login modal-->
<div id="loginModal" class="modal show" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog">
  <div class="modal-content">
      <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
          <center>
          <img src="img/<?= $config['Logo'] ?>" class="img-responsive" style="width: auto;" alt="" />
          </center>
      </div>
      <div class="modal-body">
		  <div class="alert alert-dismissable alert-danger" style="<?php if($error == ""){ echo "display: none;"; } ?>">
		    <button type="button" class="close" data-dismiss="alert">&times;</button>
		    <span id="errorMessage"><b>Error! </b><?= $error ?></span>
		  </div>
          <form method="post" action="" class="form col-md-12 center-block">
			<div style="text-align: center; font-family: Arial; font-size: 35px; font-style: italic; font-weight: bold; text-decoration: none; text-transform: none; color: #000000; background-color: #ffffff;">
				<p>Sales</p>
			</div>
			<!--<div class="form-group">
              <select style="border-color: black;" name="type" class="form-control input-lg">
				<option value="C">Cliente</option>
				<option value="SM">Vendedor</option>
			  </select>
            </div>-->
            <div class="form-group">
              <input type="text" class="form-control input-lg" style="border-color: black;" name="username" placeholder="Account Number">
            </div>
            <div class="form-group">
              <input type="password" style="border-color: black;" class="form-control input-lg" name="password" placeholder="Password">
            </div>
			<?php
			
				if($multipleLogin){
			?>
			<div class="g-recaptcha" data-sitekey="6LdShQoUAAAAAFWf-_1FzvNS3HdvCwmxrsc1TZ52"></div>
			<?php
				}
			?>
			<div style="float: right;">
				<big><big><a target="_blank" href="https://showmypc.com/">Help</a></big></big>
			</div>
            <div class="checkbox">
                <label>
                  <input type="checkbox" name="keeplogin"> Keep me logged in.
                </label>
            </div>
            <div class="form-group">
              <button class="btn btn-primary btn-lg btn-block">Enter</button>
              <big><big><span class="pull-right"><a onclick="$('#forgotPasswordModal').modal('toggle')" href="#">¿Olvidó su contraseña?</a></span></big></big>
            </div>
            
          </form>
		  
      </div>
      <div class="modal-footer">
          <div class="col-md-12">
          
		  </div>	
      </div>
  </div>
  </div>
</div>

<div id="forgotPasswordModal" class="modal fade">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">Forgot Password?</h4>
      </div>
      <div class="modal-body">
        <p>Entre su numero de cuenta para recibir via Email las instrucciones para cambiar su password.<br />
		<label for="email">Account Number:</label>
		<input type="text" style="border-color: black;" id="AccountNumber" name="AccountNumber" value="" class="form-control" placeholder="Account Number"/>
        </p>
      </div>
      <div class="modal-footer">
        <button type="button" id="" class="btn btn-default" data-dismiss="modal">Cancel</button>
        <button type="button" id="submitButton" onclick="forgotPassword();" class="btn btn-primary">Reset</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

	
		<script type="text/javascript">
			function forgotPassword() {
				var account = $("#AccountNumber").val();
				var request = $.post( "functions.php", { 	
									action: "sendPasswordReset",
					 	 			accountNumber: account 
					 	 		}).done(function( data ) {
									data = JSON.parse(data);
					 	 		    if (data.result == true) {
					 	 		    	$('#forgotPasswordModal').modal('toggle');
					 	 		    	alert("Email enviado a " + data.email + ", recuerde verificar en la carpeta de Correo No Deseado o 'Spam'");
					 	 		    }else {
					 	 		    	alert(data.error);
					 	 		    }
					 	 		});
					request.fail(function() {
						alert( "There was an error, please check your internet connection" );
					});
			}
			/*
			function autoSelectType(userType){
				//$('[name=type]').val(userType);
			}
			function getUserType(){
				$('#AccountNumber').focus();
				
				$.get('getUserType.php?input=' + $('#AccountNumber').val(), function(data){
					return data;	
				}, false);
			}
			$('#AccountNumber').on('change', function(e){
				var type = getUserType();
				if(type !== "" && typeof(type) === undefined){
						autoSelectType(type);
					}else{
						autoSelectType("C");
					}
			});
			*/
			$(document).ready(function(){
					
			});
		</script>
	</body>
</html>

