<?php
include('connection.php');
include('session.php');
error_reporting(E_ALL);
//session_start();
$status = 'A';
$time = 20;
$myPublicIP = trim(shell_exec("dig +short myip.opendns.com @resolver1.opendns.com"));

if($_SERVER["REQUEST_METHOD"] == "POST")
{
 //username and password sent from Form
$myusername=addslashes($_POST['username']);
$mypassword=addslashes($_POST['password']);


$captcha=$_POST['captcha'];

$ranStr=$_SESSION["vercode"];
$encrypted_mypassword=md5($mypassword);
//$checkblock = "select max(date) as blockdate,attemptno from block_user where ip_add = '$myPublicIP'";
$checkblock = "SELECT attemptno,date as blockdate FROM `block_user` where ip_add = '$myPublicIP' and date = (select max(date) from `block_user`)";
$res_checkblock = mysqli_query($GLOBALS["___mysqli_ston"], $checkblock);
while($rw1 = mysqli_fetch_assoc($res_checkblock))
{
			$blockdate = $rw1['blockdate'];
			$attemptno = $rw1['attemptno'];
			//echo $attemptno;
			if($attemptno >= 5)
			{
							//$dbdate = $rw['dbdate'];
 							$blockdate = strtotime($blockdate);
 							$currentTime1 = strtotime(date('Y-m-d H:i:s'));
 							$interval1 = round($currentTime1 - $blockdate) / 60;
 							//echo $interval1;
 							if($interval1 >= $time)
 							{
 										$status = 'A';
 							}
 							else 
 							{
 										$status = 'B';
 							}
			}
}
if($status == 'A')
{
						$sql="SELECT * FROM login WHERE username='$myusername' and password='$encrypted_mypassword'";
						
						$result=mysqli_query($GLOBALS["___mysqli_ston"], $sql);
						
						while($row=mysqli_fetch_array($result)) 
						{
									$user=$row['username'];
									$pass=$row['password'];
						}
						   $count=mysqli_num_rows($result);
						  
							  //	 $id=session_regenerate_id(true);
						
								 $Session_id=session_id();
								 
									$Session_date=date('Y-m-d');
						
								//$user=$_SESSION['login_user'];
							//	$user =	$_SESSION['username'];
									//echo $_SESSION['login_user'];
						   if($count==1 && $captcha==$ranStr)               
						   {
												 echo'<script>
										   window.location.href="home.php"
													</script>';
								     $sql1=mysqli_query($GLOBALS["___mysqli_ston"], "INSERT INTO `session` VALUES ('','$myusername','$Session_id','$Session_date',NOW(),'','$myPublicIP')")or die('Query1 failed: ' . mysqli_error($GLOBALS["___mysqli_ston"]));
						   }
						  else if($count!=1 && $captcha==$ranStr)
							 {
							 	
							 					$sql1 = "select max(date) as dbdate from block_user where ip_add = '$myPublicIP'";
							 					$result1 = mysqli_query($GLOBALS["___mysqli_ston"], $sql1) or die ("Error Message" . mysqli_error($GLOBALS["___mysqli_ston"]));	
							 					$count1 = mysqli_num_rows($result1);
							 					if($count1 == 1)
							 					{
							 								while($rw=mysqli_fetch_assoc($result1))
							 								{
							 											$dbdate = $rw['dbdate'];
							 											$savedTime = strtotime($dbdate);
							 											$currentTime = strtotime(date('Y-m-d H:i:s'));
							 											$interval = round($currentTime - $savedTime) / 60;
							 											//echo $interval;
							 											if($interval >= $time)
							 											{
							 														$sqlpass = "insert into block_user(username,attemptno,ip_add,date,status)values('$myusername',1,'$myPublicIP',now(),'B')";
							 														mysqli_query($GLOBALS["___mysqli_ston"], $sqlpass);
							 											}
							 											else 
							 											{
							 														$sqlupt = "Update block_user set attemptno = attemptno + 1 where date = '$dbdate' and ip_add = '$myPublicIP'";
							 														mysqli_query($GLOBALS["___mysqli_ston"], $sqlupt);
							 											}
							 								}
							 					}
							 					
										  echo"<script>";
												  echo"alert('Invalid Username or Password..!!!'); window.history.back();";
												  echo"</script>";
							 }
						  else if($count!=1 && $captcha!=$ranStr)
							 {
							 					$sql1 = "select max(date) as dbdate from block_user where ip_add = '$myPublicIP'";
							 					$result1 = mysqli_query($GLOBALS["___mysqli_ston"], $sql1) or die ("Error Message" . mysqli_error($GLOBALS["___mysqli_ston"]));	
							 					$count1 = mysqli_num_rows($result1);
							 					if($count1 == 1)
							 					{
							 								while($rw=mysqli_fetch_assoc($result1))
							 								{
							 											$dbdate = $rw['dbdate'];
							 											$savedTime = strtotime($dbdate);
							 											$currentTime = strtotime(date('Y-m-d H:i:s'));
							 											$interval = round($currentTime - $savedTime) / 60;
							 											//echo $interval;
							 											if($interval >= $time)
							 											{
							 														$sqlpass = "insert into block_user(username,attemptno,ip_add,date,status)values('$myusername',1,'$myPublicIP',now(),'B')";
							 														mysqli_query($GLOBALS["___mysqli_ston"], $sqlpass);
							 											}
							 											else 
							 											{
							 														$sqlupt = "Update block_user set attemptno = attemptno + 1 where date = '$dbdate' and ip_add = '$myPublicIP'";
							 														mysqli_query($GLOBALS["___mysqli_ston"], $sqlupt);
							 											}
							 								}
							 					}
							 					
							 		echo"<script>";
												  echo"alert('Invalid Username or Password..!!!'); window.history.back();";
												  echo"</script>";
							 }
							 else if($count==1 && $captcha!=$ranStr) 
						  	{
						  			   
											   echo"<script>";
												  echo"alert('Wrong verification code..!!!'); window.history.back();";
												  echo"</script>";
						  	}
						  	else 
						  {
							    	
										  echo"<script>
											 alert('Incorrect Username or Password & Wrong Verification Code..!!!');  window.history.back();
											 </script>"; 
						 }
						 
					//	$user_check=$_SESSION['login_user'];
						 
						//$ses_sql=mysql_query("select username from login where username='$user_check' ");
						
					//	$row=mysql_fetch_array($ses_sql);
						 
						$login_session=$row['username'];
						 
						if(!isset($login_session))
						{
						//header("Location:index.php");
						}
							
							//$Session_id=session_id();
							//$myusername=$_SESSION['login_user'];
						
						 $expireAfter = 15;
						// $session_life = time() - $_session['timeout'];
						 
						if(isset($_SESSION['last_action']))
						{
						    
						    $secondsInactive = time() - $_SESSION['last_action'];
						    $expireAfterSeconds = $expireAfter * 60;
						    	if($secondsInactive >= $expireAfterSeconds)
						    	{
						       
						       session_unset();
						        session_destroy();
						        $sql="UPDATE `session` SET `Logout_time`= NOW() WHERE `session_id`= '$Session_id' AND `username`='$myusername'";			       
						         mysqli_query($GLOBALS["___mysqli_ston"], $sql)or die('Query failed: ' . mysqli_error($GLOBALS["___mysqli_ston"]));
						        header("Location: index.php"); 
						    }
						    
							}
						
						$_SESSION['last_action'] = time();
}
else 
{
				//Header('location:block.php')
				echo "Your I.P. has been block. Try again after 20 minutes!!";
}
}
else 
  {
	    header("location:index.php");
     //exit;	
	}												
//}
?>