<?php
require_once(LIB.'User.class.php');
if (! can_action('admin'))
	redirect();

$user = new User();
$auths = $user->getAuths();
$user_types = $user->getUserTypes();
$user_auth = $user->getAllAuth();

$table = array();
foreach ($user_types as $user_type) {
	$table[$user_type['id']] = array();
	foreach ($auths as $a) {
		$table[$user_type['id']][$a['name']] = 0;
	}
}
foreach ($user_auth as $ua) {
	$table[$ua['user_type_id']][$ua['auth_name']] = $ua['auth'];
}

$script = '
function swap_auth(auth_name, user_type_id, val) {
	var user_types = [];
';
foreach ($user_types as $user_type) {
	$script .= 'user_types['.$user_type['id'].'] = "'.h($user_type['name']).'";
';
}
$script .= <<<EOD
	if (user_type_id == 1 && auth_name == "admin") {
		alert("Adminユーザのadmin権限は変更できません");
		return;
	}
	var mes;
	if (val) {
		mes = user_types[user_type_id]+"に"+auth_name+"の権限を追加します。\\nよろしいですか？";
	} else {
		mes = user_types[user_type_id]+"から"+auth_name+"の権限を削除します。\\nよろしいですか？";
	}
	if (!confirm(mes))
		return;
	$("#auth-table a").css("visibility","hidden");
	$.post2(
		T.api+"change_auth.php",
		{auth_name: auth_name, user_type_id: user_type_id, auth: val},
		function(ret) {
			if (! ret) {
				alert("更新に失敗しました");
				$("#auth-table a").css("visibility","visible");
			} else {
				location.reload();
			}
		},
		function() {
			if (! ret) {
				alert("更新に失敗しました");
			}
			$("#auth-table a").css("visibility","visible");
		},
		"json"
	);
}
EOD;

$title = '権限管理';
$css_links = array('admin.css');
include LAYOUTS.'header.inc.php';
$box = get_show_boxes(__FILE__);
include LAYOUTS.'control.inc.php';
?>
<div id="content-container" class="container ui-widget">
	<div class="box controller ui-widget-content ui-corner-all">
		<div class="controller-box">
			<table id="auth-table"><tbody>
			<tr>
				<th></th>
<?php
	foreach ($auths as $a) {
		echo '<th>'.h($a['name']).'</th>';
	}
?>
			</tr>
<?php
	foreach ($table as $user_type_id => $a) {
		echo '<tr>';
		echo '<th>'.h($user_types[$user_type_id]['name']).'</th>';
		foreach ($a as $auth_name => $a2) {
			echo '<td>'.($a2 ? '◆' : '').'<br/>';
			echo '<a href="javascript:swap_auth(\''.h($auth_name).'\', '.$user_type_id.', '.($a2 ? '0' : '1').')">'.($a2 ? '削除' : '追加').'</a></td>';
		}
		echo '</tr>';
	}
?>
			</tbody></table>
		</div>
	
		<div class="controller-box">
			<h2>各権限について</h2>
<?php
	foreach ($auths as $a) {
		echo '<div class="content">';
		echo '<h3>'.$a['name'].'</h3>';
		echo '<div>'.nl2br(h($a['explain_jp'])).'</div>';
		echo '</div>';
	}
?>
		</div>
	</div>
</div>
<?php
include LAYOUTS.'footer.inc.php';
?>