<?php	include ('config.php');
date_default_timezone_set('Asia/Kolkata'); 
$date = date("Y-m-d", time());
?>
<!doctype html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, viewport-fit=cover" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>BroRiser AMS Login</title>
    <meta name="description" content="BroRiser Attendance Management System">
    <meta name="keywords" content="BroRiser Attendance Management System" />
    <link rel="icon" type="image/png" href="assets/img/logo.png" sizes="32x32">
    <link rel="apple-touch-icon" sizes="180x180" href="assets/img/icon/192x192.png">
    <link rel="stylesheet" href="assets/css/bootstrap.css">
    <link rel="stylesheet" href="assets/css/style.css">
</head>

<body class="bg-danger">
<?php
//echo 'Server IP - '.$_SERVER['REMOTE_ADDR'];
function getUserIpAddr(){
  if(!empty($_SERVER['HTTP_CLIENT_IP'])){
    $ip = $_SERVER['HTTP_CLIENT_IP'];
  }elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
  }else{
    $ip = $_SERVER['REMOTE_ADDR'];
  }
  return $ip;
}
$getUserIpAddr = getUserIpAddr();
//echo '<br>User Device IP - '.getUserIpAddr();
$arr_browsers = ["Opera", "Edg", "Chrome", "Safari", "Firefox", "MSIE", "Trident"];
$agent = $_SERVER['HTTP_USER_AGENT'];
$user_browser = '';
foreach ($arr_browsers as $browser) {
  if (strpos($agent, $browser) !== false) {
    $user_browser = $browser;
    break;
  }  
}
switch ($user_browser) {
  case 'MSIE':
    $user_browser = 'Internet Explorer';
    break;
  case 'Trident':
    $user_browser = 'Internet Explorer';
    break;
  case 'Edg':
    $user_browser = 'Microsoft Edge';
    break;
}
//echo "<br>You are using ".$user_browser." browser";
$isMob = is_numeric(strpos(strtolower($_SERVER["HTTP_USER_AGENT"]), "mobile")); 
$isTab = is_numeric(strpos(strtolower($_SERVER["HTTP_USER_AGENT"]), "tablet")); 
$isWin = is_numeric(strpos(strtolower($_SERVER["HTTP_USER_AGENT"]), "windows")); 
$isAndroid = is_numeric(strpos(strtolower($_SERVER["HTTP_USER_AGENT"]), "android")); 
$isIPhone = is_numeric(strpos(strtolower($_SERVER["HTTP_USER_AGENT"]), "iphone")); 
$isIPad = is_numeric(strpos(strtolower($_SERVER["HTTP_USER_AGENT"]), "ipad")); 
$isIOS = $isIPhone || $isIPad; 
if($isIOS){
    $user_device = 'IOS';
}elseif($isAndroid){
    $user_device = 'ANDROID';
}elseif($isWin){
    $user_device = 'WINDOWS';
}
//echo "<br>You are using : ".$user_device." device";
?>	

<?php
session_start();
if (isset($_POST['loginad'])) {
    // Sanitize inputs
    $loginname = mysqli_real_escape_string($conn, $_POST['loginname']);
    $loginpass = mysqli_real_escape_string($conn, $_POST['loginpass']);
    $hardwareModel = mysqli_real_escape_string($conn, $_POST['hardwareModel']);
    $fingerprint = mysqli_real_escape_string($conn, $_POST['fingerprint']);
    $user_browser = mysqli_real_escape_string($conn, $_POST['user_browser']);
    $user_device = mysqli_real_escape_string($conn, $_POST['user_device']);
    $user_IP = mysqli_real_escape_string($conn, $_POST['user_IP']);
    $OfficeDate = date('Y-m-d'); // Using the corrected method to get the date

    $excludedIPs = [
        '128.185.194.194',
    ];

    // Directly attempt login for excluded IPs without duplicate checks
    if (in_array($user_IP, $excludedIPs)) {
        $status = 'Excluded'; // Special status for excluded IPs
    } else {
		// Perform duplicate checks for non-excluded IPs
        $initialDupCheckSql = mysqli_query($conn, "SELECT * FROM tracker_login WHERE user_browser = '$user_browser' AND user_device = '$user_device' AND hardwareModel = '$hardwareModel' AND fingerprint = '$fingerprint' AND OfficeDate = '$OfficeDate' AND loginname != '$loginname' AND status = 'Success'");
        
        if (mysqli_num_rows($initialDupCheckSql) > 0) {
            $refinedDupCheckSql = mysqli_query($conn, "SELECT * FROM tracker_login WHERE user_browser = '$user_browser' AND user_device = '$user_device' AND hardwareModel = '$hardwareModel' AND fingerprint = '$fingerprint' AND user_IP = '$user_IP' AND OfficeDate = '$OfficeDate' AND loginname != '$loginname' AND status = 'Success'");
            if (mysqli_num_rows($refinedDupCheckSql) > 0) {
                
				$status = "Duplicate";
			$insertDuplicateLog = mysqli_query($conn, "INSERT INTO tracker_login (user_IP, user_browser, user_device, hardwareName, hardwareModel, fingerprint, loginname, loginpass, status, OfficeDate, lat, longt)
				VALUES ('$user_IP', '{$_POST['user_browser']}', '$user_device', '{$_POST['hardwareName']}', '$hardwareModel', '$fingerprint', '$loginname', '$loginpass', '$status', '$OfficeDate', '{$_POST['lat']}', '{$_POST['longt']}')");
				
				header('Location: duplicate.html');
                exit;
            }
        }
        $status = 'Success'; // Default status for non-excluded IPs
    }
    
    // Attempt login
    $sql = mysqli_query($conn, "SELECT * FROM hr_dump WHERE empid = '$loginname' AND Password = '$loginpass' AND Status = 'Active'");
    if ($fetch1 = mysqli_fetch_array($sql)) {
        // Login successful, set session variables
        $_SESSION['empid'] = $fetch1['empid'];
        $_SESSION['user_id1'] = $fetch1['empid'];

        // Log the login attempt with the appropriate status
        $querylog = mysqli_query($conn, "INSERT INTO tracker_login (user_IP, user_browser, user_device, hardwareName, hardwareModel, fingerprint, loginname, loginpass, status, OfficeDate, lat, longt) VALUES ('$user_IP', '$user_browser', '$user_device', '".$_POST['hardwareName']."', '$hardwareModel', '$fingerprint', '$loginname', '$loginpass', '$status', '$OfficeDate', '".$_POST['lat']."', '".$_POST['longt']."')");
        
        header("Location: user/dashboard.php");
        exit;
    } else {
        $status = "Failed";
        $querylog = mysqli_query($conn, "INSERT INTO tracker_login (user_IP, user_browser, user_device, hardwareName, hardwareModel, fingerprint, loginname, loginpass, status, OfficeDate, lat, longt)
        VALUES ('{$_POST['user_IP']}', '{$_POST['user_browser']}', '{$_POST['user_device']}', '{$_POST['hardwareName']}', '$hardwareModel', '$fingerprint', '$loginname', '$loginpass', '$status', '$OfficeDate', '{$_POST['lat']}', '{$_POST['longt']}')");
        echo '<div class="alert alert-danger col-sm-12"><strong>Sorry!</strong> You have entered Wrong Credentials!</div>';
    }
}
?>

<div class="container min-vh-100 d-flex justify-content-center align-items-center">
	<div class="row">
		<div class="col-sm-12 col-md-12 col-lg-12 border rounded bg-white p-2 shadow">
			<div class="text-center">
				<p><img src="assets/img/logo.png" alt="logo" class="logo-login"></p>
				<h2>Employee Log in</h2>
				<h6>Attendance Management System</h6>
			</div>
			<div class="alert alert-success shadow-sm text-center">
				<form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
					<input class="form-control" type="hidden" id="user_IP" name="user_IP" value="<?php echo $getUserIpAddr ?>" >
					<input class="form-control" type="hidden" id="user_browser" name="user_browser" value="<?php echo $user_browser ?>" >
					<input class="form-control" type="hidden" id="user_device" name="user_device" value="<?php echo $user_device ?>" >
					<input class="form-control" type="hidden" id="hardwareName" name="hardwareName">
					<input class="form-control" type="hidden" id="hardwareModel" name="hardwareModel">
					<input class="form-control" type="hidden" id="fingerprint" name="fingerprint">
					<input type="text" class="form-control mb-2" id="loginname" name="loginname" maxlength="11" placeholder="Employee ID example:RE001" required onclick='getMyLocation();' onkeyup="this.value = this.value.toUpperCase();">
					<input type="password" class="form-control mb-2" id="loginpass" name="loginpass" placeholder="Password" maxlength="11" required >
					<input class="form-control" type="hidden" name="lat" id="lat" >
					<input class="form-control" type="hidden" name="longt" id="longt">
					<script>
						function getMyLocation(){
							if(navigator.geolocation){
								navigator.geolocation.getCurrentPosition(function(position){
									var coordinates = position.coords;
									document.getElementById('lat').value = coordinates.latitude;
									document.getElementById('longt').value = coordinates.longitude;
								});
							}
						}
					</script>
					<input type="submit" name="loginad" onclick="saveUsername()" class="btn btn-primary text-white w-75" value="Login"/>
				</form>
			</div>
			<p class="small mt-3">
				&bull; Portal is compatible with CHROME / SAFARI browser.<br>
				&bull; Use Mobile Data to access AMS Portal.<br>
				&bull; Clear browser history before punching the attendance.<br>
				&bull; Allow location access to the browser.<br>
				&bull; Select the location from drop down.
			</p>
			<hr>
			<span class="d-block text-center small">
				© Copyright 
				<script>document.write(new Date().getFullYear());</script> All Rights Reserved
			</span>
		</div>
	</div>
</div>
	
    <script src="assets/js/lib/bootstrap.bundle.min.js"></script>
    <script src="assets/js/plugins/splide/splide.min.js"></script>
    <script src="assets/js/base.js"></script>
</body>
</html>

<script src="client.js"></script>
<script async src="https://cloud.51degrees.com/api/v4/AQR6ugX3KzEAXStH3Eg.js"></script>
<script type="text/javascript">
	document.body.onload = function() {
		fod.complete(function (data) {
			document.getElementById('hardwareName').value = data.device.hardwarename || 'Unknown';
			document.getElementById('hardwareModel').value = data.device.hardwaremodel || 'Unknown';
			displayDeviceData(data);
		});
	}
	function displayDeviceData(data) {
		var outputDiv = document.getElementById("htmlExampleOutput");
		outputDiv.innerHTML = "HardwareModel: " + (data.device["hardwaremodel"] || 'Unknown') + "<br>";
		outputDiv.innerHTML += "HardwareName: " + (data.device["hardwarename"] || 'Unknown') + "<br>";
	}
	// document.querySelector('form').addEventListener('submit', submitData);
	var client = new ClientJS();
	var fingerprint = client.getFingerprint();
	document.getElementById('fingerprint').value = fingerprint;
</script>


<script type="text/javascript">
  var ab;
  function showPosition(position){
   ab = position.coords.latitude+","+position.coords.longitude;     
  }
  function showError(error) {
  switch(error.code) {
    case error.PERMISSION_DENIED:
      x.innerHTML = "User denied the request for Geolocation."
      break;
    case error.POSITION_UNAVAILABLE:
      x.innerHTML = "Location information is unavailable."
      break;
    case error.TIMEOUT:
      x.innerHTML = "The request to get user location timed out."
      break;
    case error.UNKNOWN_ERROR:
      x.innerHTML = "An unknown error occurred."
      break;
		}
	}
</script>

<script>
    /* document.addEventListener('contextmenu', event => event.preventDefault());
	
    document.addEventListener('keydown', function(event) {
        if (event.ctrlKey || event.key === "F12") {
            event.preventDefault();
        }
    }); */
</script>