<?php
session_start();
 
$username = $_POST['username'];
$password = $_POST['password'];

include_once('confdb.php');
include_once('db.functions.php');
 
//$USERNAME = mysqli_real_escape_string($con, $USERNAME);
		
//$result = mysqli_query($con,"SELECT USER_SEQ_ID, USERNAME, PASSWORD, FULL_NAME, LEVEL FROM users WHERE USERNAME = '$USERNAME' AND PASSWORD = '$PASSWORD'");
 
//$row = mysqli_fetch_array($result);

$row=DB::queryFirstRow( "SELECT* FROM main_login WHERE username = %s AND password = %s", $username, $password );

$counter = DB::count();

//if(mysqli_num_rows($result) == 0) 
if($counter == 0) 
{
	$MESSAGE_FAIL = '<blockquote>
	<br>
                          <h6>
                              <div style="color:#FF0000" align="justify"> Please input correct username & password, if you forgot your password please contact ICT Helpdesk at 03-88876065.</div>
                          </h6>
                          <br>
                </blockquote>';
    $_SESSION['MESSAGE'] = $MESSAGE_FAIL;
    header('Location: ml_index.php');
}

else { 

		session_regenerate_id(); 
		$_SESSION['username'] = $row['username'];
		$_SESSION['password'] = $row['password'];
		$_SESSION['id'] = $row['id'];
		

		//session_write_close();
			
		//header('Location:index.php');





$d= $_SESSION['username'];
$today= date('Y-m-d');
$s=DB::queryFirstRow("SELECT* FROM ml_history WHERE staff_id = '$d' AND DATE_FORMAT( in_time, '%Y-%m-%d' )  ='$today'");
$counter1 = DB::count();
      $c=strtotime ($s['in_time']);
$cformat=date('Y-m-d',$c);
      $e=strtotime($s['out_time']);
$eformat=date('Y-m-d',$e);
      $f=date('0000-00-00');
    $v=$g['out_time'];
	 $z=$g['in_time'];
	 $format= date($v, '%Y-%m-%d' );
	 $zformat= date($z, '%Y-%m-%d' );  
  
if($counter1 ==0 && $today !=$cformat  ) 
{
DB::insert('ml_history',array('staff_id'=> $row['username']));
 DB::query("UPDATE ml_history SET last_session=NOW()+ INTERVAL 1 HOUR WHERE staff_id ='$d' AND  DATE_FORMAT(in_time, '%Y-%m-%d' )='$today'");

        header('Location:staff_search.php');
}
 
else{

DB::query("UPDATE ml_history SET  out_time=NOW(), last_session=out_time+ INTERVAL 1 HOUR WHERE  staff_id ='$d' AND DATE_FORMAT( in_time, '%Y-%m-%d' )  ='$today' ");
   session_write_close();
    header('Location:staff_search.php');
}
}

  

?>
