<?php
include '../env.php';
require_once(LIB.'common.inc.php');
require_once(LIB.'User.class.php');
$userObj = new User();
$user = $userObj->load();

try {
	if (! can_action('regist'))
		throw new UserRegistException('auth', 'nothing');

	$user_type_id = $_POST['user_type_id'];
	$is_active = isset($_POST['is_activec']);
	if ($user_type_id == 1 || $user_type_id == 3 || $is_active) {
		if (! can_action('admin'))
			throw new UserRegistException('auth', 'nothing');
	}

	$log_ret = _a_log('user', 'regist', array(
		'detail' => serialize(array(
			'id' => $_POST['id'],
			'display_name' => $_POST['display_name'],
			'user_type_id' => $_POST['user_type_id'],
			'is_active' => isset($_POST['is_active']) ? $_POST['is_active'] : 1
		))
	));
	if ($log_ret === FALSE)
		throw new UserRegistException('system', 'error');

	$ret = $userObj->registUser(
		@$_POST['id'],
		@$_POST['password'],
		@$_POST['display_name'],
		@$_POST['user_type_id'],
		//TODO: 本当はメールバリデーションくらいやった方がいいけど。
		isset($_POST['is_active']) ? $_POST['is_active'] : 1
	);
	if ($ret === FALSE)
		throw new UserRegistException('system', 'error');

	_a_log_write($log_ret, array('target_id' => $ret));

} catch (UserRegistException $ex) {
	_a_log_fail('user', 'regist', $ex->field.': '.$ex->reason);
	$ret = new stdClass;
	$ret->ret = false;
	$ret->message = $ex->getMessage();
	$ret->field = $ex->field;
	$ret->reason = $ex->reason;
	echo json_encode($ret);
	die;
}
$ret = new stdClass;
$ret->ret = TRUE;
echo json_encode($ret);
?>