<?php
include '../connect.php';
session_start();

function sanitizeString($var)
{
    $var = stripslashes($var);
    $var = htmlentities($var);
    $var = strip_tags($var);
    return $var;
}

if (isset($_POST['kadPengenalan']))
{
	$kadPengenalan = sanitizeString($_POST['kadPengenalan']);
	$password = sanitizeString($_POST['password']);

		$query = "SELECT * FROM user WHERE katalaluan_user ='".$password."' AND kad_pengenalan ='".$kadPengenalan."' AND status='APPROVED' AND peranan_user='USER' "; 
		$result = mysqli_query ($conn, $query) or exit("The query could not be performed");
		
		$query1 = "SELECT * FROM user WHERE katalaluan_user ='".$password."' AND kad_pengenalan ='".$kadPengenalan."' AND status='APPROVED' AND peranan_user='ADMIN' "; 
		$result1 = mysqli_query ($conn, $query1) or exit("The query could not be performed");
		
		$query2 = "SELECT * FROM user WHERE katalaluan_user ='".$password."' AND kad_pengenalan ='".$kadPengenalan."' AND status='APPROVED' AND peranan_user='SUPER ADMIN' "; 
		$result2 = mysqli_query ($conn, $query2) or exit("The query could not be performed");
		
        //tambahan looping untuk cari nama user based on katalaluan,kad pengenalan,status dan peranan by fikri
		if (mysqli_num_rows($result) == 1)
		{
			$_SESSION["kadPengenalan"] = $kadPengenalan;
			$_SESSION["password"] = $password;
			while ($row = $result->fetch_assoc()) 
			{
		        $nama = $row["nama_user"];
		    
		    }
			//$_SESSION['last_activity'] = time();
			$_SESSION["nama"] = $nama;
			header ("location:../mainMenu.php");
		}
		else if (mysqli_num_rows($result1) == 1)
		{
			$_SESSION["kadPengenalan"] = $kadPengenalan;
			$_SESSION["password"] = $password;
			while ($row = $result1->fetch_assoc()) 
			{
		        $nama = $row["nama_user"];
		    
		    }
			$_SESSION["nama"] = $nama;
			header ("location:../mainMenu.php");
		}
		else if (mysqli_num_rows($result2) == 1)
		{
			$_SESSION["kadPengenalan"] = $kadPengenalan;
			$_SESSION["password"] = $password;
			while ($row = $result2->fetch_assoc()) 
			{
		        $nama = $row["nama_user"];
		    
		    }
			$_SESSION["nama"] = $nama;
			header ("location:../mainMenu.php");
		}
		else
		{
				echo "<script>alert('Log masuk gagal. Sila masukkan semula id pengguna dan katalaluan dengan  betul! ');";
				echo "window.location.href = '../loginPage.html';</script>";
				exit;
		}
}
else
{
	echo 'MySQL Error: ' . mysqli_error($conn);
	exit;
}

?>