<?php
include '../env.php';
require_once(LIB.'common.inc.php');

require_once(LIB.'User.class.php');
$userObj = new User();
try {
	if (empty($_GET['id'])) {
		if (! is_login()) {
			echo json_encode(FALSE);
			die;
		}

		$log_ret = _a_log('user', 'modify', array(
			'target_id' => $_SESSION['user']['id'],
			'detail' => serialize($_POST)
		));
		if ($log_ret === FALSE)
			throw new UserRegistException('system', 'error');

		$ret = $userObj->updateProfile($_SESSION['user']['id'], $_POST);
		if ($ret === FALSE)
			throw new UserRegistException('system', 'error');

		$new_user = $userObj->read($_SESSION['user']['login_id']);
		$userObj->save($new_user);
	} else {
		$log_ret = _a_log('user', 'modify', array(
			'target_id' => $_GET['id'],
			'detail' => serialize($_POST)
		));
		if ($log_ret === FALSE)
			throw new UserRegistException('system', 'error');

		$ret = $userObj->updateProfile($_GET['id'], $_POST);
		if ($ret === FALSE)
			throw new UserRegistException('system', 'error');
	}

	_a_log_write($log_ret);

} catch (UserRegistException $ex) {
	_a_log_fail('user', 'modify', $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);
?>