<?php
	session_start();
	header('Content-type: application/json');
	include_once '../backend/db/db.php';
	$response = array();

	if ($_POST) {
		
		$user = trim($_POST['user']);
		$pass = trim($_POST['password']);
		
		$uname = strip_tags($user);
		$upass = strip_tags($pass);
	    
		$uname = htmlspecialchars($uname, ENT_QUOTES, 'UTF-8');		
		$upass = htmlspecialchars($upass, ENT_QUOTES, 'UTF-8');
		$password = hash('sha256', $upass); // password hashing using SHA256
				
		$sql_con = mysqli_query($conn, "SELECT id, pwd, SIDA_no FROM contractor_reg WHERE SIDA_no='$uname' and del=0");
		$sql_st = mysqli_query($conn, "SELECT id, pwd, nic_no FROM staff_members WHERE nic_no='$uname' and del=0");
			
		if(mysqli_num_rows($sql_con) == 1) {			
			$row_con = mysqli_fetch_assoc($sql_con);
			
			if($row_con['pwd'] == $password){
				$response['status'] = 'ok'; // log in
				$response['acc_type'] = 'contr';
				$_SESSION['user'] = $row_con['SIDA_no'];
			
			} else{
				$response['status'] = 'error';
				 // wrong details
				$response['message'] = '<span class="glyphicon glyphicon-info-sign"></span> &nbsp; Username or Password does not match.'; 
			}
		
		} else if(mysqli_num_rows($sql_st) == 1) {			
			$row_st = mysqli_fetch_assoc($sql_st);
			
			if($row_st['pwd'] == $password){				
				$response['status'] = 'ok'; // log in
				$response['acc_type'] = 'staff';
				$_SESSION['user'] = $row_st['nic_no'];
			
			} else{
				$response['status'] = 'error';
				 // wrong details
				$response['message'] = '<span class="glyphicon glyphicon-info-sign"></span> &nbsp; Username or Password does not match.'; 
			}
		
		} else{
			$response['status'] = 'error';
			// wrong details
			$response['message'] = '<span class="glyphicon glyphicon-info-sign"></span> &nbsp; Username or Password does not match.'; 
		}
		
	}
	
	echo json_encode($response);
?>