<?php

include ("dbset.php");
$today = date("Y-m-d");
$ip_address = $_SERVER['REMOTE_ADDR'];
$username = $_GET['user_name_text'];


//msqli settings
$con = mysqli_connect("localhost",$dbu,$dbp);
if (!$con)
  {
  die('Could not connect to database: ' . mysql_error());
  }
mysqli_select_db($con, $dbs);

//mysql settings
//$conn = @mysql_connect("localhost",$dbu,$dbp);
//if (!$conn)
//  {
//  die('Could not connect to database: ' . mysql_error());
//  }
//mysql_select_db($dbs, $conn);
//
//function execsql($qry){
//	$result = @mysql_query($qry);
//	return $result;
//}

$login_query = "SELECT username FROM system_users WHERE username = '" . $username . "' ";
$login_result = $con->query($login_query);
$login_num = mysqli_num_rows($login_result);

if ($login_num == 1) {
// Inialize session
@session_start();	
// Set username session variable
$access = "SELECT access_id, home_page FROM pec_users WHERE (username = '" .$username. "') ";
//echo $access;
$accessResult = $con->query($access);
while($row = $accessResult->fetch_assoc()) {
$_SESSION['access_id'] = $row["access_id"];
$home_page = $row["home_page"];
}

$_SESSION['username'] = $_GET['user_name_text'];

date_default_timezone_set('Africa/Gaborone');
$entry_date = date("Y-m-d H:i:s", time());  

$table_name = "active_users";
$update_query = "UPDATE $table_name SET logged_into = 'Pecus'  WHERE username = '".$username."' ";
$update_result = $con->query($update_query);


include('log_in_check.php');

$table_name = "pec_tracking_log_in";
$action_query = "INSERT INTO $table_name (entry_date, user, action, details) VALUES ('".$entry_date."' ,'".$_SESSION['username']."','log in', '".$ip_address."' )";
$action_result = $con->query($action_query);



$login_check_query = "SELECT log_in_check_id FROM pec_login_check WHERE log_in_date = '".$today."' ";
$login_check_result = $con->query($login_check_query);
$login_check_num = mysqli_num_rows($login_check_result);

if ($login_check_num == 0 ) {
}

if ($home_page=="hr") {$location = "hr_module/hr_main.php?date="; }
if ($home_page=="production") {$location = "production/production_main.php"; }
if ($home_page=="stores") {$location = "store/store_main.php"; }
if ($home_page=="admin") {$location = "admin_module/user_list.php";  }
if ($home_page=="") {$location = "../mainmenu.php?log=1&e=2&cx=".$_SESSION['access_id']; }
$_SESSION['location'] = $location;


// Jump to secured page
   header('Location: '."../".$location );
}
else {
//Jump to login page
  ?>
  <script language="javascript" type="text/javascript">
        window.location="../mainmenu.php?log=1&e=0";
</script>
<?php
}

?>