<?php

require_once '../../AccessControl.php';

$profiles = array();
$q = $db->Execute("SELECT profilename FROM ". TBL_PROFILES . " ORDER BY profilename");
while($row = $q->fetchRow()){
	$profiles[] = $row['profilename'];
}

$result = array(
	"Status" => "Success"
	,"availableTags" => $profiles
);

if(!$session->isAdmin() && !$session->canEditUserInfo()){
	die('{ "Status" : "Error" , "Message" : "'. _ACCESS_DENIED .'" }');
}

if($session->isAdmin()){
	$userdata = array(
		"userid" => 0
		,"username" => ""
		,"name" => ""
		,"password" => ""
		,"email" => ""
		,"profiles" => ""
		,"foreignkey" => null
		,"created" => ""
		,"isAdmin" => 0
		,"active" => 1
		,"accessUpdateLogs" => 0
		,"accessAddProfile" => 0
		,"usersessionid" => null
		,"lastlogin" => 0
		,"accessEditProfile" => 0		
		,"expires" => 0		
		,"metadata" => array(
			"changeAccountInfo" => 0
			,"profileLimit" => 0
			,"trackermode_0" => 0
			,"trackermode_1" => 0
			,"trackermode_2" => 0
			,"trackermode_3" => 0
			,"allProfiles" => 0
			,"accessBasicEditProfile" => 0
		)
		,"subscriptionid"  => null
	);

	# lets set the values of the user in an array
	if(!empty($_POST['action']) && $_POST['action'] == 'saveuser'){

		$selectors = array();
		$data = array();

		# overwrite user setting
		foreach ($_POST as $key => $value) {
			if(!empty($value) && isset($userdata[$key])){
				$userdata[$key] = $value;
			}
		}

		
		if(isset($_POST['active'])){
			$userdata['active'] = $_POST['active'];
		}

		# implode the profile list
		if(!empty($userdata['profiles'])){
			$userdata['profiles'] = implode(",", $userdata['profiles']);
		}

		# encode the password
		if(!empty($userdata['password'])){
			$userdata['password'] = md5($userdata['password']);
		} else {			
			unset($userdata['password']);
			unset($userdata['usersessionid']);
		}

		# encode the password
		if(!empty($userdata['created'])){
			$cdtmp=explode("/", $_POST["created"]);
			$userdata["created"] = mktime(12,0,0,$cdtmp[0],$cdtmp[1], $cdtmp[2]);
		}

		# encode the expire
		if(!empty($userdata['expire'])){
			$cdtmp=explode("/", $_POST["expire"]);
			$userdata["expire"] = mktime(12,0,0,$cdtmp[0],$cdtmp[1], $cdtmp[2]);
		}    

		# overwrite meta setting
		if(!empty($_POST['changeAccountInfo'])){
			$userdata["metadata"]["changeAccountInfo"] = 1;
		}

		# Check if there is a profile limit set
		if(!empty($_POST['profileLimit']) && is_numeric($_POST['profileLimit'])){
			$userdata["metadata"]["profileLimit"] = $_POST['profileLimit'];	
		}
		# Check if there is a limited edit permission
		if(!empty($_POST['accessBasicEditProfile']) && is_numeric($_POST['accessBasicEditProfile'])){
			$userdata["metadata"]["accessBasicEditProfile"] = $_POST['accessBasicEditProfile'];	
			if ($_POST['accessBasicEditProfile'] ==1) {
				//if this is true, accessEditProfile must also be true
				$userdata["accessEditProfile"] = 1;
			}
		}		

		if(!empty($_POST['userSubscription'])){
			$userdata["subscriptionid"] = $_POST['userSubscription'];
		}

		# add the trackermode permissions to the meta setting
		if(!empty($_POST['trackermode_0'])){ $userdata["metadata"]["trackermode_0"] = 1;  } 
		if(!empty($_POST['trackermode_1'])){ $userdata["metadata"]["trackermode_1"] = 1;  } 
		if(!empty($_POST['trackermode_2'])){ $userdata["metadata"]["trackermode_2"] = 1;  } 
		if(!empty($_POST['trackermode_3'])){ $userdata["metadata"]["trackermode_3"] = 1;  } 
		
		if(!empty($_POST['canViewAllProfiles'])){ 
			$userdata["metadata"]["allProfiles"] = 1;  
			$userdata["profiles"] = "";
		} 

		$userdata["metadata"] = json_encode($userdata["metadata"]);

		# new user
		if(empty($userdata['userid'])){
			# remove id
			unset($userdata['userid']);
			$userdata["created"] = time();

			if (($db->getOne("SELECT count(*) from ".TBL_USERS." where username = " . $db->Quote($userdata['username']))) != 0) {
				die( json_encode(array("Status" => "Error", "Message" => _USER_ALREADY_EXISTS_CANT_DUPLICATE ) ) );
            } else {
                if (CheckIfTableExists(TBL_USERS)) {
                    $db->AutoExecute(TBL_USERS, $userdata, "INSERT") or die(
                    json_encode(
                        array("Status" => "Error", "Message" => $db->ErrorMsg())
                    )
                    );
                }
            }

            $result['Message'] = _ADDED_NEW_USER . " {$userdata['username']}";
            $result['userid'] = $db->_insertid();
        } else {
            $userdata["metadata"] = CheckUserMetaData($userdata['userid'], $userdata['metadata']);

            if (CheckIfTableExists(TBL_USERS)) {
                $db->AutoExecute(
                    TBL_USERS,
                    $userdata,
                    "UPDATE",
                    "userid = " . $db->Quote($_POST["userid"])
                ) or die(json_encode(array("Status" => "Error", "Message" => $db->ErrorMsg())));
            }
            $result['Message'] = _EDITED_USER . " {$userdata['username']}";
        }
    }
} elseif ($session->canEditUserInfo()) {
    if (!empty($_POST['action']) && $_POST['action'] == 'saveuser') {
        $userdata = array("name" => $_POST['name'], "email" => $_POST['email']);

        if (!empty($_POST['userSubscription'])) {
            $userdata["subscriptionid"] = $_POST['userSubscription'];
        }

        if (!empty($_POST['password'])) {
            $userdata["password"] = md5($_POST['password']);
        }

        if (CheckIfTableExists(TBL_USERS)) {
            $db->AutoExecute(
                TBL_USERS,
                $userdata,
                "UPDATE",
                "userid = " . $db->Quote($session->userinfo["userid"])
            ) or die(json_encode(array("Status" => "Error", "Message" => $db->ErrorMsg())));
        }
        $result['Message'] = _EDITED_USER;
    }
}

echo json_encode($result);

