<?php

session_start();
require_once '_toolkit_loader.php';
require_once 'constants.php';

//SSO Authentication
$auth = new OneLogin_Saml2_Auth();

if (isset($_SESSION) && isset($_SESSION['AuthNRequestID'])) {
    $requestID = $_SESSION['AuthNRequestID'];
} else {
    $requestID = null;
}

$auth->processResponse($requestID);

$errors = $auth->getErrors();
$lastError = $auth->getLastErrorReason();

if (!empty($errors)) {
    echo '<p>', implode(', ', $errors), '</p>';
    echo '<p>' . $lastError . '</p>';
}

if (!$auth->isAuthenticated()) {
    echo "<p>Not authenticated</p>";
    exit();
} else {
    $_SESSION['samlUserdata'] = $auth->getAttributes();
    $_SESSION['samlNameId'] = $auth->getNameId();
    $_SESSION['samlNameIdFormat'] = $auth->getNameIdFormat();
    $_SESSION['samlNameIdNameQualifier'] = $auth->getNameIdNameQualifier();
    $_SESSION['samlNameIdSPNameQualifier'] = $auth->getNameIdSPNameQualifier();
    $_SESSION['samlSessionIndex'] = $auth->getSessionIndex();

    unset($_SESSION['AuthNRequestID']);

    if (isset($_SESSION['samlUserdata'])) {
        if (!empty($_SESSION['samlUserdata'])) {
            $attributes = $_SESSION['samlUserdata'];
            foreach ($attributes as $attributeName => $attributeValues) {
                if (htmlentities($attributeName) == 'samAccountName') {
					//if (htmlentities($attributeName) == 'userPrincipalName') {
                    foreach ($attributeValues as $attributeValue)
                        $_SESSION['emp_id'] = htmlentities($attributeValue);
                }
            }
        }
    }
}

if (isset($_SESSION['emp_id']) && $_SESSION['emp_id'] != "") {
   
 header("location:" . constants::PROCESS_LOGIN_PAGE);
} else {
    die("Invalid Access");
}
