<?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['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();
	}
}
		
?>
<!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]-->
		
		
		<script src='https://www.google.com/recaptcha/api.js?hl=es' async defer></script>

			<style>
				body { 
					background: url(img/login_bg.jpg) no-repeat center center fixed; 
					-webkit-background-size: cover;
					-moz-background-size: cover;
					-o-background-size: cover;
					background-size: cover;
				  }
				  
				  .panel-default {
				  opacity: 0.9;
				  margin-top:30px;
				  }
				  .form-group.last { margin-bottom:0px; }
			
		</style>
	</head>
	<body >
		<noscript>
		  <div class="jumbotron">
		    <h2></h2>
		    
		    
		    <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="container">
			<div class="row" style="margin-top: 100px;">
				<div class="col-md-6 col-md-offset-3">
					<div class="panel panel-default">
						<div class="panel-heading">
							Wholesale Sales Login</div>
						<div class="panel-body">
							<div class="error">
								<?php
								
								if($error){
									echo $error;
								}
								?>
							</div>
							<form class="form-horizontal centerd" method="POST" action="login.php" role="form">
								<center>
									<img style="width: 50%; margin-bottom: 20px;" src="img/Logo_250.png" />	
								</center>
								
							<div class="form-group">
								<label for="username" class="col-sm-3 control-label">
									Account Number</label>
								<div class="col-sm-9">
									<input type="text" class="form-control" id="username" name="username" placeholder="Account Number" required>
								</div>
							</div>
							<div class="form-group">
								<label for="password" class="col-sm-3 control-label">
									Password</label>
								<div class="col-sm-9">
									<input type="password" class="form-control" name="password" id="password" placeholder="Password" required>
								</div>
							</div>
							<div class="form-group">
								<div class="col-sm-offset-3 col-sm-9">
									<div class="checkbox">
										<label>
											<input type="checkbox"/>
											Remember me
										</label>
									</div>
								</div>
							</div>
							<div class="form-group last">
								<div class="col-sm-offset-3 col-sm-9">
									<button type="submit" class="btn btn-success btn-sm">
										Sign in</button>
										 <button type="reset" class="btn btn-default btn-sm">
										Reset</button>
								</div>
							</div>
							</form>
						</div>
						<div class="panel-footer">
							
					</div>
				</div>
			</div>
		</div>

  
	</body>
</html>

