<?php
	require_once '../autoload.php';

	
	require_once dirname(__FILE__).'/../../../Config/odbc.php';
	require_once dirname(__FILE__). '/../../../Config/config.php';
	require_once dirname(__FILE__). '/../../global.php';
	require_once dirname(__FILE__). '/utils.php';

	$pdo = getPDO();
	
	$answer = "";

	if ( $pdo )
	{
		$stmt = $pdo->prepare ( "SELECT id,lastname,firstname,login_role_id from staff_member where login = ? and decode(password,'base64') = ? and active = true" );

		if ( $stmt->execute ( [$_POST['username'], $_POST['password']] ) )
		{
			$results = $stmt->fetchAll ( PDO::FETCH_ASSOC );

			if ( count($results) == 1 )
			{
				$row = $results[0];

				$_SESSION['loggedin'] 	= TRUE;
				$_SESSION['username'] 	= $_POST['username'];
				$_SESSION['id'] 		= $row["id"];
				$_SESSION['lastname'] 	= $row["lastname"];
				$_SESSION['firstname'] 	= $row["firstname"];


				error_log ( "login-role_id : " .$row["login_role_id"] );

				$array_view_idx = array();
				$stmt = $pdo->prepare ( "select nameid, value::integer, working_view::integer from login_role_permission where ? = login_role_id" );
				if ( $stmt->execute ( [$row["login_role_id"]] ) )
				{
					while ( $row2 = $stmt->fetch () )
					{
						error_log ( "VIEW : " .$row2[0]. " / " .$row2[1]. " / ".$row2[2] );
						$array_view_idx[$row2[0]] = $row2[1];
						if($row2[2]== "1")
						{
							$array_view_idx[$row2[0].'_WORKING'] = "1";
						}
						else
						{
							$array_view_idx[$row2[0].'_WORKING'] = "0";
						}
					}
				}
				$_SESSION['view'] = $array_view_idx;

				error_log(print_r($_SESSION, true));


				$conn = get_dbconnection();
				update_session_useraccess($conn);

				$answer = json_encode ( array ('id' => $row['id'], 'lastname' => $row['lastname'], 'firstname' => $row['firstname'], 'access' => $array_view_idx ) );
			}
			else 
			{
				// echo 'Failed to log in!';
				$answer = json_encode ( array ('error' => 'Failed to log' ) );
			}
		}
		else
		{
			// echo 'query failed';
			$answer = json_encode ( array ('error' => 'Query failed' ) );
		}
	}	
	else
	{
		// echo 'no DB connection';
		$answer = json_encode ( array ('error' => 'no DB connection' ) );
	}

	header ('Content-type: application/json' );

	echo $answer;
?>