<?php
session_start();
require "../config/configDB.php";

if(isset($_POST["submit"])){
    
    if(empty($_POST["username"]) || empty($_POST["password"]))  {
        
        $error = "Both fields are required.";
    }
    else {
        
        $username=$_POST['username'];
        $password=$_POST['password'];
        
        $username = stripslashes($username);
        $password = stripslashes($password);
        $username = mysqli_real_escape_string($conn, $username);
        $password = mysqli_real_escape_string($conn, $password);
        $password = ($password);
     
        $sql="SELECT * FROM admin_login WHERE username='$username' and password='$password'";
        $result=mysqli_query($conn,$sql);
        $row=mysqli_fetch_array($result,MYSQLI_ASSOC);
        
        if(mysqli_num_rows($result) == 1)
        {
            $login_user     =   $row['username'];
            $login_pk       =   $row['id'];    
            
            $_SESSION['username']      = $login_user;
            $_SESSION['user_id']       = $login_pk;
            $_SESSION['loggedin_time'] = time();  

            if(isset($_SESSION["user_id"])) {
                if(!isLoginSessionExpired()) {
                    
                    $sql_update = "UPDATE admin_login SET loginstatus=1 WHERE username='$username' and password='$password'";
                    
                    $_SESSION['login_status']   = "1";        
                    
                    mysqli_query($conn,$sql_update);

                    if($login_pk==1) {

                        header("location: adminDashboard.php"); 
                    }
                    else if($login_pk>1) {
                        header("location: adminDashboard.php");
                    }
                } 
                else {
                    header("Location:index.php?session_expired=1");
                }
            }
        }
        else {
            $error = "Incorrect username or password.";
            header("Location:index.php?session_expired=1");
        } 
    }
}

function isLoginSessionExpired() {
	$login_session_duration = 10; 
	$current_time = time(); 
	if(isset($_SESSION['loggedin_time']) and isset($_SESSION["user_id"])){  
		if(((time() - $_SESSION['loggedin_time']) > $login_session_duration)){ 
			return true; 
		} 
	}
	return false;
}
 
?>