<?php
include('includes/config/config.php');
include('constants.php');
include('log_entry.php');

include('includes/functions.php');

?>
<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta http-equiv="Content-Language" content="en-us">
	<meta http-equiv="Pragma" content="no-cache">
	<meta http-equiv="Cache-Control" content="no-cache">
	<meta http-equiv="Expires" content="Sat, 01 Dec 2001 00:00:00 GMT">
	<title>OHCTech | Occupational Heath System</title>
	<!-- Tell the browser to be responsive to screen width -->
	<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
	<!-- Bootstrap 3.3.7 -->
	<link rel="stylesheet" href="adminlte/bower_components/bootstrap/dist/css/bootstrap.min.css">
	<!-- Font Awesome -->
	<link rel="stylesheet" href="adminlte/bower_components/font-awesome/css/font-awesome.min.css">
	<!-- Ionicons -->
	<link rel="stylesheet" href="adminlte/bower_components/Ionicons/css/ionicons.min.css">
	<!-- Theme style -->
	<link rel="stylesheet" href="adminlte/dist/css/AdminLTE.min.css">
	<!-- iCheck -->
	<link rel="stylesheet" href="adminlte/plugins/iCheck/square/blue.css">
	<!-- <link rel="icon" type="image/png" href="images/n1.jpg" />-->
	<!-- Google Font -->
	<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic">
	<!-- <style>
       body {
    background-image: url("images/diwali.gif") !important;
    background-repeat: repeat-both;
}
  </style>
  -->
	<style>
		.alert-w {
			padding: 20px;
			background-color: orange;
			/* yellow */
			color: white;
			margin-bottom: 15px;
			text-align: center;
		}

		.alert-d {
			padding: 20px;
			background-color: #f44336;
			/* Red */
			color: white;
			margin-bottom: 15px;
			text-align: center;
		}

		/* The close button */
		.closebtn {
			margin-left: 15px;
			color: white;
			font-weight: bold;
			float: right;
			font-size: 22px;
			line-height: 20px;
			cursor: pointer;
			transition: 0.3s;
		}

		/* When moving the mouse over the close button */
		.closebtn:hover {
			color: black;
		}
	</style>
</head>
<script>
	function delCookie(NameOfCookie) {
		// The function simply checks to see if the cookie is set.
		// If so, the expiration date is set to Jan. 1st 1970.
		if (getCookie(NameOfCookie)) {
			document.cookie = NameOfCookie + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
		}
	}
</script>

<?php
if (isset($_REQUEST['__SSOAuthenticated_username'])) {
	$_SESSION['__SSOAuthenticated_username'] = $_REQUEST['__SSOAuthenticated_username'];
}

session_start();
$hide = $_REQUEST['hide'];
if ($hide == 1 || isset($_SESSION['__SSOAuthenticated_username']) || isset($_SESSION['__SSOAuthenticated_BlueCollar_EmpCode'])) {

	if (isset($_POST['token']) || isset($_SESSION['__SSOAuthenticated_username']) || $_SESSION['__SSOAuthenticated_BlueCollar_EmpCode']) {

		error_log('#tocken' . $_POST['token']);
		error_log('#sess' . $_SESSION['csrf_Token']);
		error_log('#__SSOAuthenticated_username' . $_SESSION['__SSOAuthenticated_username']);
		error_log('#__SSOAuthenticated_BlueCollar_EmpCode' . $_SESSION['__SSOAuthenticated_BlueCollar_EmpCode']);

		if ($_POST['token'] == $_SESSION['csrf_Token'] || isset($_SESSION['__SSOAuthenticated_username']) || isset($_SESSION['__SSOAuthenticated_BlueCollar_EmpCode'])) {
			// echo "CSRF Token accepted";

			// Getting username/ email and password
			$str = $_POST['user_name'];
			$str = strtolower($str);
			$str = addslashes($str);
			$username = htmlspecialchars(trim($str));
			$empcode = "";
			$query_part = "";

			if (isset($username)) {
				$query_part = " upper(t.user_name)=upper('$username') ";
			}

			if (isset($_SESSION['__SSOAuthenticated_username'])) {
				$username = $_SESSION['__SSOAuthenticated_username'];
				$query_part = " upper(t.user_name)=upper('$username') ";
			}

			if (isset($_SESSION['__SSOAuthenticated_BlueCollar_EmpCode'])) {
				$empcode = $_SESSION['__SSOAuthenticated_BlueCollar_EmpCode'];
				$pat_id = getFieldFromTable('id', 'patient_master', 'emp_code', $empcode);

				if (!empty($username) && isset($username)) {
					$query_part = " upper(t.user_name)=upper('$username') and t.emp_id = '" . $pat_id . "' and t.emp_id <> 0";
				} else {
					$query_part = " t.emp_id = '" . $pat_id . "' and t.emp_id <> 0 ";
				}
			}

			error_log("emp code sso " . $empcode);

			$password = $_POST['user_password'];


			error_log("entered pass " . $password);

			// Hashing with Random Number
			$saltedpasswrd = hash('sha256', $password);
			error_log('#salt_' . $saltedpasswrd);
			// Fetch stored password� from database on the basis of username/email/empcode
			$sql = "select t.*,m.*, r.role_home_page,r.role_code from tbl_users t left join menu_master m on t.landing_page=m.menu_id left join role_master r on t.role_id= r.role_id  where " . $query_part;

			$result = mysqli_query($conn,$sql);

			error_log("#query :" . $sql);

			$row = mysqli_fetch_assoc($result);
			// error_log("#got inside " . print_r($row, true));
			
			$currentDate = new DateTime();
			$c_time = $currentDate->format('Y-m-d H:i:s');
			// login check query
			$ipaddress = null;
			if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
				// ip from share internet
				$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
			} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
				// ip pass from proxy
				$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
			} else {
				$ipaddress = $_SERVER['REMOTE_ADDR'];
			}

			$is_success = 0;

			$id_session = $_SESSION['csrf_Token'];
			$err_reason = "";
			$logout_time = "";
			$sn_log = 0;

			if (!isset($_SESSION['__SSOAuthenticated_username']) && !isset($_SESSION['__SSOAuthenticated_BlueCollar_EmpCode'])) { //No Lock if SSO User 

				$log_time_query = "select * from login_check where user_id='$username' AND login_time ";

				$rs_log = "select sn_log from login_check";
				if (!$r_log = @mysqli_query($conn, $rs_log)) {
					error_log("I am here" . __LINE__ . " MySQL Error:" . mysqli_error($conn));
					exit(mysqli_error($conn));
				}
				if (mysqli_num_rows($r_log) > 0) {
					error_log("I am here" . __LINE__);
					while ($row_log = mysqli_fetch_array($r_log)) {
						error_log("I am here" . __LINE__);

						$sn_log = $row_log['sn_log'];
					}
				}
				$sn_log++;

				$success_check = 0;

				$log_time_query = "select * from login_check where user_id='$username' AND is_success=0";
				if (!$r_log = @mysqli_query($conn, $log_time_query)) {
					error_log("I am here" . __LINE__ . " MySQL Error:" . mysqli_error($conn));
					exit(mysqli_error($conn));
				}
				if (mysqli_num_rows($r_log) > 0) {
					error_log("I am here" . __LINE__);
					$end = new DateTime();
					while ($row_log = mysqli_fetch_array($r_log)) {
						error_log("I am here" . __LINE__);

						"<br>" . $start = $row_log['login_time'] . "";
						$start = new DateTime($start);

						$diff = $end->diff($start);

						$days = $diff->format('%a');
						$hours = $diff->format('%h');
						$minutes = $diff->format('%i');

						"<br>" . $diffInMinutes = $days * 24 * 60 + $hours * 60 + $minutes;
						if ($diffInMinutes < 30) {
							error_log("I am here" . __LINE__);
							$success_check++;
						} else {
							error_log("I am here" . __LINE__);
							$success_check = 0;
						}
					}
				}
			} //No Lock if SSO User end+
			$log_check_query = "insert into login_check set sn_log='$sn_log',ip_address='$ipaddress',user_id='$username',u_password='$password' ";

			if (!isset($_SESSION['__SSOAuthenticated_username']) && !isset($_SESSION['__SSOAuthenticated_BlueCollar_EmpCode']) && $success_check >= 5) {
				error_log("I am here" . __LINE__);
				$err_reason = "tried more than 5 times";

				$log_check_query = $log_check_query . ", is_success='$is_success' , id_session='$id_session',err_reason='$err_reason' ,logout_time='$logout_time' ";

				if (!$login_check = @mysqli_query($conn, $log_check_query)) {
					error_log("I am here" . __LINE__ . " MySQL Error:" . mysqli_error($conn) . " Query:" . $log_check_query);

					exit(mysqli_error($conn));
				} else {
					error_log("I am here" . __LINE__);

					$user_name = strtoupper($username);

					$set_status = 2;
					$status_change_query = "update tbl_users set status='" . $set_status . "' where user_name='" . $user_name . "' ";
					error_log($status_change_query);
					if (!$status_update_tbl = @mysqli_query($conn, $status_change_query)) {
						error_log("I am here" . __LINE__ . " MySQL Error:" . mysqli_error($conn));
						exit(mysqli_error($conn));
						echo "<script>location.replace('index.php?msg=$msg')</script>";
					} else {
						error_log("I am here" . __LINE__);
						echo " updated ";
					}

					echo "<script>location.replace('index.php?msg=Too many failed attempts. Your account is locked. Please connect application administrator. ')</script>";
				}
			}

			// error_log("#DATA" . print_r($row, true));
			// // $query->rowCount();
			// error_log("#count" . print_r($query->rowCount(), true));
			// // echo $query->rowCount();
			$row_counts = mysqli_num_rows($result);
			error_log("rows count " . $row_counts);
			if ($row_counts > 0) {
				error_log("I am here" . __LINE__);

				error_log("db pass " .$row['user_password']);

				$fetchpassword = hash('sha256', $row['user_password']);
				error_log("#DB_PASSWORD: " . $fetchpassword);

				error_log("#user_PASSWORD: " . $saltedpasswrd);
				// // foreach ($row as $result)
				// {

				// //print_r($fetchpassword);
				// // hashing for stored password
				// // $storedpass= hash('sha256',$fetchpassword);
				// }
				// You can configure your cost value according to your server configuration.By Default value is 10.
				$options = [
					'cost' => 12
				];

				// Hashing of the post password
				// $hash= password_hash($storedpass,PASSWORD_DEFAULT, $options);
				// $hash= password_hash($saltedpasswrd,PASSWORD_DEFAULT, $options);
				// echo $hash1;
				// Verifying Post password againt stored password
				// echo "<br>".$saltedpasswrd;
				if ($saltedpasswrd === $fetchpassword || ((isset($_SESSION['__SSOAuthenticated_username']) || isset($_SESSION['__SSOAuthenticated_BlueCollar_EmpCode'])) && isset($row['user_name']))) {
					error_log("Passwords Matched. I am here" . __LINE__);
					// echo "welcome";
					// $_SESSION['userlogin'] = $username;

					error_log("status:" . $row['status']);
					if ($row['status'] == '1') {
						error_log("I am here" . __LINE__);
						$_SESSION['user_id'] = $row['user_id'];

						$id_session = $_SESSION['csrf_Token'];

						$user_id_new = $row['user_id'];

						$_SESSION['username'] = $row['user_name'];
						$_SESSION['firstname'] = $row['first_name'];
						error_log("firstname:" . $row['first_name']);
						$_SESSION['lastname'] = $row['last_name'];

						$_SESSION['userpassword'] = $row['user_password'];

						// $_SESSION['RoleId'] = $row->role_id;
						$_SESSION['RoleCode'] = $row['role_code'];
						$_SESSION['role_home_page'] = $row['role_home_page'];
						$_SESSION['logged_user_empid'] = $row['emp_id'];
						error_log("emp_id:" . $row['emp_id']);
						$menu_id = $row['menu_id'];
						// $s = $row['menu_url'];
						$ohcTypes = $row['ohc_type'];
						$userRoles = $row['role_id'];
						// login check query
						$is_success = 1;
						$id_session = $_SESSION['csrf_Token'];

						$log_check_query = $log_check_query . ", is_success='$is_success' , id_session='$id_session',err_reason='$err_reason' ,logout_time='$logout_time' ";

						if (!$login_check = @mysqli_query($conn, $log_check_query)) {
							error_log("I am here" . __LINE__ . " MySQL Error:" . mysqli_error($conn) . ". Failing Query:" . $log_check_query);
							exit(mysqli_error($conn));
						} else {
							//echo "<script>alert('yes');</script>";
						}
						if (isset($ohcTypes) && strlen($ohcTypes) > 0) {
							$ohc_arr = explode(",", $ohcTypes);
							if (sizeOf($ohc_arr) > 1) {
								$_SESSION['ohctypes'] = $ohcTypes;
								echo "<script>location.replace('interim_ohc_selection.php')</script>";
							} else if (sizeOf($ohc_arr) == 1) {
								$_SESSION['current_ohcttype'] = $ohc_arr[0];
							}
						}
						$userRoles = $row['role_id'];
						error_log("role ids " . $userRoles);

						if (isset($userRoles) && strlen($userRoles) > 0) {
							$role_arr = explode(",", $userRoles);
							if (sizeOf($role_arr) > 1) {
								$_SESSION['roleids'] = $userRoles;
								error_log("role ids " . $_SESSION['roleids']);
								//echo "<script>location.replace('interim_selection.php')</script>";

								echo "<script>location.replace('interim_role_selection.php')</script>";
							} else if (sizeOf($role_arr) == 1) {
								$_SESSION['RoleId'] = $role_arr[0];
								if (sizeOf($ohc_arr) > 1) {
									echo "<script>location.replace('interim_ohc_selection.php')</script>";
								}
							}
						}
						if (isset($_SESSION['role_home_page']) && sizeOf($_SESSION['role_home_page']) > 0) {
							// echo $_SESSION['role_home_page'];
							echo "<script>location.replace('" . $_SESSION['role_home_page'] . "')</script>";
							// echo "<script>location.replace('home.php?pagekey=226')</script>";
						} else {
							echo "<script>location.replace('home.php')</script>";
						}
					} else {
						//even patient record is not found.
						//redirect to error page asking for user to connect OHC Team for registration.
						error_log(" patient record is not found. Patient Id: " . $id);
					}



					//end SSO patient only login
				} else {
					$err_reason = "You are barred to use this application";

					$msg = 'You are barred to use this application';
					echo "<script>location.replace('index.php)</script>";
				}

				//echo "<script type='text/javascript'> document.location = 'welcome.php'; </script>";
			} else if (isset($_SESSION['__SSOAuthenticated_username']) || isset($_SESSION['__SSOAuthenticated_BlueCollar_EmpCode'])) {
				//to allow SSO Employee Users for whom specific role setup is not in place but still can access as Patient their individual records.
				if (isset($_SESSION['__SSOAuthenticated_username'])) {
					$patient_id = getFieldFromTable('id', 'patient_master', 'offiial_email_id', $_SESSION['__SSOAuthenticated_username']);
				} else if (isset($_SESSION['__SSOAuthenticated_BlueCollar_EmpCode'])) {
					$patient_id = getFieldFromTable('id', 'patient_master', 'emp_code', $_SESSION['__SSOAuthenticated_BlueCollar_EmpCode']);
				}

				if (isset($patient_id)) {
					//atleast patient record must be found for a patient to access the software.
					error_log("at least patient record is found. Patient Id: " . $patient_id);

					$sql_emp = "select * from patient_master where id ='" . $patient_id . "' ";
					$query_emp = $conn->prepare($sql_emp);
					error_log("#query_emp :" . $sql_emp);

					$query_emp->execute();
					$result_emp = $query_emp->get_result()->fetch_object();


					//Fix role to employee only when only patient .. no user.
					$sql_role = "select * from role_master where role_code ='EMP' ";
					$query_role = $conn->prepare($sql_role);
					error_log("#query_role :" . $sql_role);

					$query_role->execute();
					$result_role = $query_role->get_result()->fetch_object();
					$_SESSION['RoleCode'] = $result_role->role_code;
					$_SESSION['role_home_page'] = $result_role->role_home_page;
					$_SESSION['logged_user_empid'] = $patient_id;
					$_SESSION['RoleId'] = $result_role->role_id;
					//Patients can be assigned only one OHC if not OHC staff member as well.
					$_SESSION['current_ohcttype'] = $result_emp->ohc_type_id;
					//Menu id field is required to ensure the user is not accessing unauthenticated pages.
					$menu_id = getFieldFromTable('menu_id', 'menu_master', 'menu_url', $result_role->role_home_page);

					$_SESSION['username'] = $result_emp->offiial_email_id;
					if (empty($_SESSION['username'])) {
						$_SESSION['username'] = $result_emp->patient_name;
					}

					$_SESSION['firstname'] = $result_emp->patient_name;
					error_log("firstname:" . $result_emp->patient_name);
					$_SESSION['lastname'] = $result_emp->last_name;
					error_log("redirecting to" . $_SESSION['role_home_page']);

					echo "<script>location.replace('" . $_SESSION['role_home_page'] . "')</script>";
				} else {
					$err_reason = "SSO User. No Patient Record Found for " . $_SESSION['__SSOAuthenticated_username'];
					$msg = "Unidentified user. Please connect your IT/OHC team for getting yourself registered";
					error_log($err_reason);
					echo "<script>location.replace('accessdenied.php?msg=$msg')</script>";
				}
			} else {

				$err_reason = "No Record Found and its not sso user";
				$msg = "User name or Wrong password";
				error_log($err_reason);
				echo "<script>location.replace('index.php?msg=$msg')</script>";
			}

			$id_session = $_SESSION['csrf_Token'];

			$log_check_query = $log_check_query;

			if (!$login_check = @mysqli_query($conn, $log_check_query)) {
				error_log("I am here" . __LINE__ . " MySQL Error:" . mysqli_error($conn) . ". Failing Query:" . $log_check_query);
				exit(mysqli_error($conn));
				echo "<script>location.replace('index.php?msg=$msg')</script>";
			} else {
				echo "<script>location.replace('index.php)</script>";
			}
		}
	} else {

		$msg = 'Login failure !!!';
		echo "<script>location.replace('index.php)</script>";

		// echo "";
	}
}

?>

<body class="hold-transition login-page">
	<div class="login-box">
		<div class="login-logo">
			<a href="http://www.ohctech.com"><img src="images/ohctech_logo.svg" alt="" style="width: 200px; height: 60px;" title="OHCTECH"></a><br>
			<h4>Occupational Health System</h4>
		</div>

		<!-- /.login-logo -->
		<div class="login-box-body">
			<?php
			if ($msg) {
				echo " <p class=\"text-red\">$msg</p>";
			} else {
				echo " <p class=\"login-box-msg\">Sign in to Enter</p>";
			}
			?>
			<?php

			// 1.Create CSRF Token to Form
			$csrf_Token = md5(uniqid(rand(), true));
			$_SESSION['csrf_Token'] = $csrf_Token;
			?>
			<form method="POST">
				<div class="form-group has-feedback">

					<input type="text" name="user_name" class="form-control" placeholder="User Name"> <span class="glyphicon glyphicon-user form-control-feedback"><input type="hidden" name="token" value=<?= $csrf_Token; ?>></span>
				</div>
				<div class="form-group has-feedback">
					<input type="password" class="form-control" placeholder="Password" name="user_password"><input type="hidden" name="hide" value="1"> <span class="glyphicon glyphicon-lock form-control-feedback"></span>
				</div>
				<div class="row">
					<div class="col-xs-8">
						<div class="checkbox icheck">
							<label> <input type="checkbox"> Remember Me
							</label>
						</div>
					</div>
					<!-- /.col -->
					<div class="col-xs-4">
						<button type="submit" name="acn" class="btn btn-primary btn-block btn-flat">Sign In</button>
					</div>
					<!-- /.col -->
				</div>
			</form>
		</div>
		<!-- /.login-box-body -->
	</div>
	<!-- /.login-box -->
	<?php
	$due_date_old = getConfigKey("SUBSCRIPTION_END_DATE");
	error_log("date : " . $due_date_old);
	$due_date = strtotime($due_date_old);
	$due_date = date('Y-m-d', $due_date);

	$date = date_create($due_date_old);
	date_sub($date, date_interval_create_from_date_string("30 days"));
	$date =  date_format($date, "Y-m-d");
	// echo $date. " ".date("Y-m-d");
	// echo $due_date; 

	if ($due_date_old != '' && $date <= date("Y-m-d") && date("Y-m-d") < $due_date) {
	?>
		<div class="alert-w">
			<!-- <span class="closebtn" onclick="this.parentElement.style.display='none';">&times;</span>  -->
			<strong>Alert!</strong> Your support will end on <?= $due_date_old ?>.Please get your
			subscription renewed.
		</div>
	<?php } else if ($due_date_old != '' && date("Y-m-d") > $due_date) { ?>
		<div class="alert-d">
			<!-- <span class="closebtn" onclick="this.parentElement.style.display='none';">&times;</span>  -->
			<strong>Alert!</strong> Your support has ended on <?= $due_date_old ?>.Please get your
			subscription renewed as soon as possible.
		</div>
	<?php
	} ?>
	<!-- jQuery 3 -->
	<script src="adminlte/bower_components/jquery/dist/jquery.min.js"></script>
	<!-- Bootstrap 3.3.7 -->
	<script src="adminlte/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
	<!-- iCheck -->
	<script src="adminlte/plugins/iCheck/icheck.min.js"></script>
	<script>
		$(function() {
			$('input').iCheck({
				checkboxClass: 'icheckbox_square-blue',
				radioClass: 'iradio_square-blue',
				increaseArea: '20%' // optional
			});
		});
	</script>
</body>

</html>