<?php
/** @var array $data */
$pageTitle='User: '.$data['fullname'];
include realpath(__DIR__).'/../_common/header.php'; ?>
<script type="text/javascript"><?php include realpath(__DIR__).'/../../model/user/extensions.js'; ?></script>
<script type="text/javascript">
window.addEventListener('DOMContentLoaded',function(){
	
	ui.grid();
    let detailsBox;
    let passwordBox;

	//basic page layout first
	if(isAdmin || 1*userId===1*data['id']){
		detailsBox=grid.box({
			classes:'r1 c1 h2 w1',
			title:'Details'
		});
		passwordBox=grid.box({
			classes:'r3 c1 h1 w1',
			title:'Set or change password'
		});
			                   	
	} else {
		detailsBox=grid.box({
			classes:'r1 c1 h3 w1',
			title:'Details'
		});
	}

	
	let ts=grid.tabSet({ classes:'r1 c2 h3 w2' });

	//see ../model/extensions.js
	userExtensions.tabsBefore(ts);	

	if(isAdmin || 1*userId===1*data['id']){ //User VIEWING THIS PAGE is admin, or is SAME as user BEING VIEWED

        ts.tab({
            id:'projects',
            label:'Projects',
            url:'/api/user/'+data['id']+'/project',
            successHandler:writePermissions
         });

		if(isAdmin){ //User VIEWING THIS PAGE is an administrator
			//Show all groups with add/add-as-admin/remove
			ts.tab({ 
    			id:'memberships', 
    			label:'Groups', 
    			url:'/api/usergroup',
    			getAll:1000,
    			headers:['Name','','','',''],
    			cellTemplates:[
        			'<a href="/usergroup/{{id}}">{{name}}</a>',
        			'<span class="user_groupstatus">...</span>', 
        			'<span class="user_groupnonmember">...</span>', 
        			'<span class="user_groupmember">...</span>', 
        			'<span class="user_groupadmin">...</span>'
        		]
    		});
    		UserGroupManagement.getMemberships();
		} else{
			//Show only groups the user belongs to, read-only
			ts.tab({ 
    			id:'memberships', 
    			label:'Groups', 
    			url:'/api/user/'+data['id']+'/usergroup',
    			headers:['Name','Is group admin'],
    			cellTemplates:['<a href="/usergroup/{{id}}">{{name}}</a>',[ui.checkmark,'isgroupadmin'] ]
    		});
		}

	} else {
		ts.tab({ 
			id:'more', 
			label:'Info', 
			content:'If you aren\'t an administrator, you can\'t see other users\' project and group information', 
		 });
	}

    BackgroundImages.writeUserImagesTab(ts);

	//see ../model/extensions.js
	userExtensions.tabsAfter(ts);	

	
	if(undefined!==passwordBox){
		let passwordForm=passwordBox.form({
			action:'/api/user/'+data['id'],
			classes:'create' //Disables auto-update on the fields
		});
		if(!isAdmin){
			passwordForm.passwordField({ label:"Old", name:'oldpassword', value:'', readonly:false });
		}
		passwordForm.passwordField({ label:"New", name:'password1', value:'', readonly:false});
		passwordForm.passwordField({ label:"New again", name:'password2', value:'', readonly:false });
		passwordForm.buttonField({ label:"Change", id:"changepassword", onclick:changePassword });
        passwordBox.insertAdjacentHTML("beforeend",'<p>This only affects logging in with an IceBear username and password. If '+
             ((1*userId===1*data['id']) ? "you log in" : " the user logs in") +
             ' with a university or corporate ID, this will have no effect.</p>');
	}

    if(1*userId===1*data['id']){
        ui.infoMessageBar("This is you!",detailsBox);
    }
	let frm=detailsBox.form({
		action:'/api/user/'+data['id'],
	});
	frm.textField({ label:"Full name", name:'fullname', value:data['fullname'], readonly:!isAdmin });
	if(isAdmin){
		frm.textField({ label:"Email address", name:'email', value:data['email'] });
		frm.textField({ label:"Username", name:'name', value:data['name'], readonly:true });
        frm.textField({ label:"Last login", name:"lastlogin", value:ui.friendlyDateTime(data["lastlogin"]), readonly:true});
		frm.checkbox({ label:"Account is active", name:'isactive', value:data['isactive'] });
	} else if(1*userId===1*data['id']){
        frm.textField({ label:"Email address", name:'email', value:data['email'], readonly:true });
    }

	if(""===data["supervisorid"] || 0===data["supervisorid"]){
		frm.roleField({
            nullable:true,
			readonly:!isAdmin,
			label:"Supervisor", 
			name:'supervisorid', 
			otherType:'user',
			labelField:'fullname',
			headers:['Name'],
			cellTemplates:['{{fullname}}']
		});
	} else {
		new AjaxUtils.Request('/api/user/'+data["supervisorid"], {
			method:'get',
			onSuccess:function(transport){
				let supervisor=transport.responseJSON;
				frm.roleField({
                    nullable:true,
					readonly:!isAdmin,
					label:"Supervisor", 
					name:'supervisorid', 
					otherId:supervisor.id, 
					otherName:supervisor["fullname"],
					otherType:'user',
					labelField:'fullname',
					headers:['Name'],
					cellTemplates:['{{fullname}}']
				});
			},
			onFailure:function(){}
		});
	}
	
});

function changePassword(evt){
	let btn=evt.target;
	let frm=btn.closest("form");
	let oldPasswordField=frm.querySelector("[name=oldpassword]");
	let new1Field=frm.querySelector("[name=password1]");
	let new2Field=frm.querySelector("[name=password2]");
	if(oldPasswordField && ""===oldPasswordField.value){
		alert("Old password is required");
		return false;
	} else if(new1Field.value!==new2Field.value || ""===new1Field.value){
		alert("New password: Both fields must match");
		return false;
	}
	btn.closest("label").classList.add("updating");
	let body="csrfToken="+csrfToken+"&password="+new1Field.value;
	if(oldPasswordField){ body +="&oldpassword="+oldPasswordField.value; }
	new AjaxUtils.Request("/api/user/"+data['id'], {
		method:"patch",
		postBody:body,
		onSuccess:changePassword_onSuccess,
		onFailure:changePassword_onFailure
	});
}
function changePassword_onSuccess(transport){
	if(!transport.responseJSON || transport.responseJSON.error){ return changePassword_onFailure(transport); }
    let lbl=document.getElementById("changepassword").closest("label");
	lbl.classList.remove("updating");
	lbl.innerHTML="Password changed";
}
function changePassword_onFailure(transport){
	document.getElementById("changepassword").closest("label").classList.remove("updating");
	if(transport.responseJSON && transport.responseJSON.error){ 
		alert(transport.responseJSON.error);
	} else {
		alert(transport.responseText);
	}
}

function writePermissions(transport){
    let pb=document.getElementById("projects_body");
    pb.innerHTML="";
	if(!transport.responseJSON){
		pb.innerHTML="Could not understand reply from server:</br></br>"+transport.responseText;
		return;
	}
    if(!isAdmin) { //User VIEWING THIS PAGE is NOT an administrator
        pb.innerHTML="Only administrators can view this.";
        return;
    }

    if(1*data["isadmin"]){
        if(1*userId===1*data['id']){
            ui.infoMessageBar("You are an administrator, so you have full access rights on all projects.", pb);
        } else {
            ui.infoMessageBar(data["fullname"]+" is an administrator, and has full access rights on all projects.", pb);
        }
    }

	pb.classList.add("hastable");
	let permissionTypes=['read','update','create','delete'];
	let out='<table><tr>';
    if(Project.showArchivedProjects){ out+='<th>Archived</th>'; }
    out+='<th>Project</th><th>Read</th><th>Update</th><th>Create</th><th>Delete</th></tr>';

	transport.responseJSON.rows.forEach(function(proj){
        let isArchived=1*proj['isarchived'];
		let ownerFlag='';
		if(1===1*proj["isowner"]){ ownerFlag=' (owner)'; }
		out+='<tr>';
        if(Project.showArchivedProjects){
            out+='<td>';
            out+=1*proj['isarchived']?'<img alt="Yes" src="/imag'+'es/icons/yes.gif" />':'&nbsp;'; }
            out+='</td>';
        out+='<td><a href="/project/'+proj.id+'">'+proj.name+'</a>'+ownerFlag+'</td>';
		//Read-only view of permissions, cannot edit here.
		permissionTypes.forEach(function(t){
			if(1===1*proj["isowner"]){
                if(isArchived && "read"!==t){
                    out+='<td><img alt="Yes" src="/images/icons/yellowcross.gif" title="'+data["fullname"]+' owns the project, but it is archived" id=""/></td>';
                } else {
                    out+='<td><img alt="Yes" src="/images/icons/yes.gif" title="Because '+data["fullname"]+' owns the project" id=""/></td>';
                }
			} else if(!!proj.permissions[t]){
				let label="Permission from group";
				if(proj.permissions[t].length>1){ label+="s"; }
				label+=": ";
				proj.permissions[t].forEach(function(perm){
					label+=perm["usergroupname"]+", ";
				});
				label=label.slice(0,-2);
                if(isArchived && "read"!==t){
                    label+=', but project is archived';
                    out+='<td><img alt="Archived project" src="/images/icons/yellowcross.gif" title="'+label+'" id=""/></td>';
                } else {
                    out+='<td><img alt="Yes" src="/images/icons/yes.gif" title="'+label+'" id=""/></td>';
                }
			} else {
				out+='<td><img alt="No" src="/images/icons/no.gif" id="'+''+'"/></td>';
			}
		});
		out+='</tr>';
	});
	out+='</table>';
	pb.innerHTML+=out;
}

let UserGroupManagement={

	getMemberships:function(){
		new AjaxUtils.Request('/api/user/'+data['id']+'/usergroup?all=1',{
			method:"get",
			onSuccess:function(transport){
				UserGroupManagement.updateGroupMembershipStatuses(transport.responseJSON.rows);
			},	
			onFailure:function(transport){
				if(404===1*transport.status){
					UserGroupManagement.updateGroupMembershipStatuses([]);
				} else {
					alert("Could not get group memberships");
				}
			}	
		});
	},

 	updateGroupMembershipStatuses:function(groups){
	    let mb=document.getElementById("memberships_body");
 	 	if(!mb.querySelector("td")){
			window.setTimeout(function(){
				UserGroupManagement.updateGroupMembershipStatuses(groups);
			},250);
			return false;
 	 	}
 		mb.querySelectorAll("tr").forEach(function(tr){
			if(!tr.rowData){ return; }
			tr.id="group"+tr.rowData["id"];
			tr.rowData['groupmembershipid']=null;
			tr.rowData['isgroupadmin']=null;
		});
		groups.forEach(function(grp){
		    let tr=document.getElementById("group"+grp.id);
			tr.rowData['groupmembershipid']=grp['groupmembershipid'];
			tr.rowData['userisgroupadmin']=grp['isgroupadmin'];
 		});
 		mb.querySelectorAll("tr").forEach(function(tr){
			if(!tr.rowData){ return; }
			UserGroupManagement.updateGroupMembershipStatus(tr);
 		});
 	},
	
	updateGroupMembershipStatus:function(tr){
		tr.classList.remove("updating");
		if(!tr.rowData){ return; }
		let groupStatus='Not in group';
		let bgColor='';
		let removeButton='<input type="button" data-newstatus="nonmember" value="Remove from group" onclick="UserGroupManagement.handleMemberButton(this)"/>';
		let addButton='<input type="button" data-newstatus="groupmember" value="Make group member" onclick="UserGroupManagement.handleMemberButton(this)" />';
		let addAdminButton='<input type="button" data-newstatus="groupadmin" value="Make group admin" onclick="UserGroupManagement.handleMemberButton(this)" />';
		if(!tr.rowData['groupmembershipid']){ 
			//Not a member "Add" "Add as group admin"
			removeButton='&nbsp;';
		} else {
			let isGroupAdmin=1*tr.rowData['userisgroupadmin'];
			if(!isGroupAdmin){ 
    			//Regular member "Remove" "Make group admin" 
    			addButton='&nbsp;';
    			groupStatus='<span style="font-weight:bold;color:green">Group member</span>';
    			bgColor='#dfd';
    		} else {
    			//Group admin "Remove" "Make regular member" 
    			addAdminButton='&nbsp;';
    			groupStatus='<span style="font-weight:bold;color:#f60">Group admin</span>';
    			bgColor='#ffd';
    		}
		}
        tr.style.backgroundColor=bgColor;
        tr.querySelectorAll("th,td").forEach(function (cell){
            cell.style.backgroundColor=bgColor;
        });
		tr.querySelector(".user_groupstatus").innerHTML=groupStatus;
		tr.querySelector(".user_groupnonmember").innerHTML=removeButton;
		tr.querySelector(".user_groupmember").innerHTML=addButton;
		tr.querySelector(".user_groupadmin").innerHTML=addAdminButton;
	},

	handleMemberButton:function(btn){
		let tr=btn.closest("tr");
		let membershipId=tr.rowData['groupmembershipid'];
		let newStatus=btn.dataset.newstatus;
		if("nonmember"===newStatus){
			UserGroupManagement.removeFromGroup(tr);
		} else {
			let makeAdmin=false;
			if("groupmember"===newStatus){
				makeAdmin=false;
			} else if("groupadmin"===newStatus){
				makeAdmin=true;
			}
			if(membershipId){
				UserGroupManagement.changeGroupAdminStatus(tr, makeAdmin);
			} else {
				UserGroupManagement.addToGroup(tr, makeAdmin);
			}
		} 
	},
	
	removeFromGroup:function(tr){
		tr.classList.add("updating");
		new AjaxUtils.Request('/api/groupmembership/'+tr.rowData['groupmembershipid'],{
			method:'delete',
			parameters:{ csrfToken:csrfToken },
			onSuccess:function(){
				tr.rowData['groupmembershipid']=null;
				tr.rowData['userisgroupadmin']=null;
				UserGroupManagement.updateGroupMembershipStatus(tr);
			},
			onFailure:AjaxUtils.checkResponse
		});
	},

	addToGroup:function(tr, makeAdmin){
		tr.classList.add("updating");
		new AjaxUtils.Request('/api/groupmembership/',{
			method:'post',
			parameters:{ 
				csrfToken:csrfToken, 
				userid:data['id'],
				usergroupid:tr.rowData['id'],
				isgroupadmin:1*makeAdmin
			},
			onSuccess:function(transport){ 
				tr.rowData['groupmembershipid']=transport.responseJSON.created.id;
				tr.rowData['userisgroupadmin']=transport.responseJSON.created.isgroupadmin;
				UserGroupManagement.updateGroupMembershipStatus(tr);
			},
			onFailure:AjaxUtils.checkResponse
		});

	},

	changeGroupAdminStatus(tr, makeAdmin){
		tr.classList.add("updating");
		new AjaxUtils.Request('/api/groupmembership/'+tr.rowData['groupmembershipid'],{
			method:'patch',
			parameters:{ 
				csrfToken:csrfToken, 
				isgroupadmin:1*makeAdmin
			},
			onSuccess:function(){
				tr.rowData['userisgroupadmin']=makeAdmin;
				UserGroupManagement.updateGroupMembershipStatus(tr);
			},
			onFailure:AjaxUtils.checkResponse
		});

	}
	
};
</script>
<?php include realpath(__DIR__).'/../_common/footer.php';