<?php
error_reporting(E_ALL & ~(E_NOTICE | E_WARNING)); // 關閉警示及錯誤訊息
session_write_close();
include_once 'Parameters.php';
include_once 'auth/func.php';
header('Access-Control-Allow-Origin: *');

$jwt  = isset($_POST['jwt']) ? $_POST['jwt'] : '';
$mode = isset($_POST['mode']) ? $_POST['mode'] : '';
if ($token = parseToken($jwt)) {
	$result = validationData($token);
	switch ($mode) {
		case 'user': $mode = _Logout_Normal_Mode; break;
		case 'idle': $mode = _Logout_Force_Mode; break;
		case 'expired': $mode = _Logout_TimeOut_Mode; break;
		case 'close': $mode = _Logout_Close_Mode; break;
		// 驗證
		case 'validate': $mode = 0; break;
		default: $mode = _Logout_Unknow_Mode;
	}
	$h = hash("crc32", $token, false);
	$dt= date("Y-m-d H:i:s");
	$user = $token->getClaim('user_id');
	
	$dsn = sprintf("sqlsrv:Server=%s; Database=%s;", $DataSource , $DataBase_Alarm);
	$pdo_mssql = new PDO($dsn, $UserID, $Password); 
	
	if ($mode > 0) {
		$sql = sprintf("UPDATE %s.dbo.user_login SET logout_time = '{$dt}', logout_mode = '{$mode}' WHERE user_id='{$user}' AND token_hash = '{$h}' AND logout_mode IS NULL", $DataBase_Alarm);
	} else {
		$sql = sprintf("UPDATE %s.dbo.user_login SET curr_check = '{$dt}' WHERE user_id='{$user}' AND token_hash = '{$h}'", $DataBase_Alarm);
	}
	
	$pdo_mssql->prepare($sql)->execute();
	die('succ');
}

die('fail');
?>