<?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 = "ACCESS DENIED<br />Please contact your salesperson.";
			}

		else {
			$correct = false;
			$error = "The account number or password is not valid. Click <a onclick=\"$('#forgotPasswordModal').modal('toggle')\" href=\"#\">here</a> to change your password.";
		}

	} else {
		$correct = false;
		$error = "The account number or password is not valid. Click <a onclick=\"$('#forgotPasswordModal').modal('toggle')\" href=\"#\">here</a> to change your password.";
	}


	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['Username'] = $row['Username'];
		$_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), "/");
		}
		//(print_r($_SESSION,1));

		$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();
	}
}

?>
<!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">
		
		<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]-->


		<script src='https://www.google.com/recaptcha/api.js?hl=es' async defer></script>

			<style>

body {
 background-image: url("img/login-background.jpg");
 background-repeat: no-repeat;
  background-size: cover;
 background-color: #cccccc;
}
#login_form {
	opacity: .9;
	background-color: #fff;
	border-radius: 15px;
	
}
#login_form div,#login_form input, #login_form button {
	opacity: 1;

}
		</style>
	</head>
	<body>
		<noscript>
		  <div class="jumbotron">
		    <h2></h2>
		    <center>
		    <img src="img/logo.png" 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>
<div class="row" >
	<div id="LoginDiv" class="col-md-3">
	</div>
  	<div id="LoginDiv" class="col-md-6">

		<div style="text-align: center; padding-top: 100px;" >
			<img src="img/Logo_1000.png" style="width: 50%; text-align: center;" id=""><br>
			<form method="post" action="login.php" id="login_form" style="" class="form col-md-6 col-md-offset-3">

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


				<div style="text-align: center; font-family: Arial; font-size: 35px; font-weight: bold; text-decoration: none; text-transform: none; color: #000;">
					<p>Sales</p>
				</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>

				<div class="checkbox">
					<label style="color: ;">
					<input type="checkbox" name="keeplogin"> Keep me logged in.
					</label>
				</div>
				<div class="form-group">
				<button class="btn btn-primary btn-lg btn-block" onclick="toggleBulb();">Enter</button>
				<big><big><span class="pull-right"><a onclick="$('#forgotPasswordModal').modal('toggle')" href="#">Forgot your password?</a></span></big></big>
				<br>
				<br>
				
				</div>


          	</form>
		</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">
			$('#bulb_image').on('load', function(){
				if(bulb_status){
					$('#login_form').submit();
				}

			});
			$('#login_form').on('submit', function(e){
					if(!bulb_status){
						e.preventDefault();

						turnOn();
					}




			});
			var bulb_status = 0;
			function turnOn(){
				$('#bulb_image').attr('src', 'img/bulb_on.jpg');
				bulb_status = 1;
			}
			function turnOff(){
				$('#bulb_image').attr('src', 'img/bulb_off.jpg');
				bulb_status = 0;
			}
			function toggleBulb(){
				if(bulb_status){
					turnOff();
				}else{
					turnOn();
				}
			}
			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>
