<?php $pageTitle='Users';
$showCreateLink=session::isAdmin();
include realpath(__DIR__).'/../_common/header.php'; ?>
<script type="text/javascript">
window.addEventListener('DOMContentLoaded',function(){

    let showInactiveUsers=<?php echo 1*session::get('showInactiveUsers'); ?>;
    let inactiveUserControl='';

	let headers=['Name'];
    let showFilters=[true];
    let sortOrders=['fullname'];
	let cellTemplates=['<a href="/user/{{id}}">{{fullname}}</a>'];

    if(isAdmin){
        inactiveUserControl='Inactive users are hidden. <input onclick="setShowInactiveUsers(this,1);return false" type="button" style="float:none" value="Show inactive users" />';
        headers=["Name","Username","Email","Last login"];
        showFilters=[true,true,true,false];
        sortOrders=["fullname","name","email","-lastlogin"];
        cellTemplates=['<a href="/user/{{id}}">{{fullname}}</a>',"{{name}}","{{email}}", [ui.fieldToFriendlyDate,"lastlogin"] ];
        if(showInactiveUsers) {
            inactiveUserControl = 'Inactive users are included in this list. <input onclick="setShowInactiveUsers(this,0);return false" type="button" style="float:none" value="Hide inactive users" />';
            headers.push("Active");
            showFilters.push(false);
            sortOrders.push("-isactive");
            cellTemplates.push([ui.checkmark,"isactive"]);
        }
    }

	let grid=ui.grid();
	grid.box({ 
        contentBefore:inactiveUserControl,
		classes:'r1 c1 h3 w3',
		url:'/api/user',
		headers:headers,
		cellTemplates:cellTemplates,
        sortOrders:sortOrders,
        showFilters:showFilters
	});

});

function setShowInactiveUsers(clicked,show){
    if(!isAdmin){ return false; }
    let wrapper=clicked.closest("th,td,tr,a");
    if(wrapper.classList.contains("updating")){ return false; }
    wrapper.classList.add("updating");
    new AjaxUtils.Request('/api/user/'+userId,{
        method:"patch",
        parameters: {"showInactiveUsers":show },
        onSuccess: function(){ document.location.reload(); },
        onFailure: function(xhr){
            wrapper.classList.remove("updating");
            AjaxUtils.checkResponse(xhr);
        }
    });
}

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