<?php

require '../../lib/glob.php';
require '../../lib/muoribene.php';
require '../../lib/sessionstart.php';
require '../../lib/myconn.php';
require '../../lib/getadmacc.php';
require '../../lib/menu.php';
$menu['menu']['selected']=true;
$menu['menu']['submenu']['account']['selected']=true;
buildmenu($menu);
if ($account['Level']!='guest') {
	require '../../lib/notifs.php';
	$notifs=notifs($link);
	$english=false;
} else {
	$english=true;
}
require '../../lib/tables.php';
$fields=tables($link);
$fields=$fields['Admins'];
require '../../lib/transiten.php';

$dbg='';
$dbg.='<pre>'.print_r($_POST,1).'</pre>'.N;

use function mysqli_real_escape_string as myesc;

// praticamente una macro
function hspech($str) {
	return(htmlspecialchars($str,ENT_QUOTES|ENT_HTML5,'UTF-8'));
}

function inputerr(&$account) {
	muoribene(t('<p>Errori di input.<br>Stavi cercando di editare <a href="account.php?id='.$account['ID'].'">il tuo account</a>?</p>','<p>Input errors.<br>Where you trying to edit <a href="account.php?id='.$account['ID'].'"> your account</a>?</p>').N,true);
}

$postmisskeys=ckkeys(array('id','Username','Email','Password','CPassword'),$_POST);

if (count($postmisskeys)==0 && preg_match('/^[0-9]+$/',$_POST['id'])===1 && mb_strlen($_POST['Username'])>=1 && mb_strlen($_POST['Username'])<=$fields['Username'] && mb_strlen($_POST['Email'])>=3 && mb_strlen($_POST['Email'])<=$fields['Email'] && $_POST['Password']==$_POST['CPassword'] && ($_POST['Password']=='' || (mb_strlen($_POST['Password'])>=8 && mb_strlen($_POST['Password'])<=64))) {
	$id=$_POST['id']+0;
	$post=true;
} elseif (array_key_exists('id',$_GET) && preg_match('/^[0-9]+$/',$_GET['id'])==1) {
	$id=$_GET['id']+0;
	$post=false;
} else {
	inputerr($account);
}
if ($account['Level']=='guest' && $id==0) inputerr($account);
if ($account['Level']=='guest' && $id!=$account['ID'])
	muoribene('<p>You can edit <a href="account.php?id='.$account['ID'].'">your account</a> only.</p>'.N,true);
if ($id!=0) {
	$res=mysqli_query($link,'SELECT * FROM Admins WHERE ID='.$id)
		or muoribene(__LINE__.': '.mysqli_error($link),true);
	if (mysqli_num_rows($res)==0)
		muoribene('<p>Non esiste alcun account con ID='.$id.'<br>Se vuoi puoi editare <a href="account.php?id='.$account['ID'].'">il tuo account</a>.</p>',true);
	$acc=mysqli_fetch_assoc($res);
	$passreq='';
} else {
	$acc=array(
		'ID'=>0,
		'Username'=>'',
		'Email'=>'',
		'Password'=>'',
		'Level'=>'normal',
		'MaxLocalities'=>1,
		'MaxLanguages'=>0,
		'MaxFinancing'=>3,
		'MaxPolicies'=>3,
		'MaxTags'=>3,
		'Enabled'=>1
	);
	$passreq=' required';
}
($account['ID']==$acc['ID']) ? $ownacc=true : $ownacc=false;
if ($id!=0 && $account['Level']=='normal' && !$ownacc && $acc['Level']!='guest')
	muoribene('<p>Come admin di livello “normale” puoi editare solo <a href="account.php?id='.$account['ID'].'">il tuo account</a> e gli account di livello “guest”.</p>',true);
if ($id==0)
	$atit=t('Nuovo account','New account');
elseif ($ownacc)
	$atit=t('Il tuo account','Your account');
else
	$atit='Account «'.hspech($acc['Email']).'»';

/*
    [id] => 3
    [Username] => bida
    [Email] => mastodon@bida.im
    [Password] =>
    [CPassword] =>
    [Level] => guest
    [MaxLocalities] => 1
    [MaxLanguages] => 0
    [MaxFinancing] => 5
    [MaxPolicies] => 3
    [MaxTags] => 3
    [Enabled] => 1
*/

function ckmax($key) {
	global $fields;
	if (preg_match('/^[0-9]+$/',$_POST[$key])==1 && $_POST[$key]+0>=$fields[$key]['min'] && $_POST[$key]+0<=$fields[$key]['max'])
		return(true);
	else
		return(false);
}

if ($post) {
	$quea=array();
	$quea[]='Username="'.myesc($link,$_POST['Username']).'"';
	$quea[]='Email="'.myesc($link,$_POST['Email']).'"';
	if ($_POST['Password']!='' || $_POST['CPassword']!='') {
		if ($_POST['Password']!=$_POST['CPassword']) inputerr($account);
		$quea[]='Password="'.myesc($link,password_hash($_POST['Password'],PASSWORD_DEFAULT)).'"';
	}
	$ok=true;
	if (array_key_exists('Level',$_POST)) {
		if (!in_array($_POST['Level'],array('guest','normal','super'))) $ok=false;
		if ($account['Level']=='normal' && !$ownacc && !in_array($_POST['Level'],array('guest','normal'))) $ok=false;
		if ($account['Level']=='normal' && $ownacc) $ok=false;
		if ($account['Level']=='guest') $ok=false;
		if (!$ok) inputerr($account);
		$quea[]='Level="'.$_POST['Level'].'"';
	}
	if (count(ckkeys(array('MaxLocalities','MaxLanguages','MaxFinancing','MaxPolicies','MaxTags'),$_POST))==0) {
		if ($account['Level']=='guest') $ok=false;
		if ($account['Level']=='normal' && $ownacc) $ok=false;
		if ($ok && ckmax('MaxLocalities') && ckmax('MaxLanguages') && ckmax('MaxFinancing') && ckmax('MaxPolicies') && ckmax('MaxTags')) {
			$quea[]='MaxLocalities='.$_POST['MaxLocalities'];
			$quea[]='MaxLanguages='.$_POST['MaxLanguages'];
			$quea[]='MaxFinancing='.$_POST['MaxFinancing'];
			$quea[]='MaxPolicies='.$_POST['MaxPolicies'];
			$quea[]='MaxTags='.$_POST['MaxTags'];
		} else {
			inputerr($account);
		}
	}
	if (array_key_exists('Enabled',$_POST)) {
		if (!in_array($_POST['Enabled'],array('0','1'))) inputerr($account);
		($ownacc && $_POST['Enabled']=='0') ? $logout=true : $logout=false;
		$quea[]='Enabled='.$_POST['Enabled'];
	}
	if ($id!=0)
		$que='UPDATE Admins SET '.implode(', ',$quea).' WHERE ID='.$id;
	else
		$que='INSERT INTO Admins SET '.implode(', ',$quea);
	$dbg.='QUERONA: '.hspech($que);
	mysqli_query($link,$que)
		or muoribene(__LINE__.': '.mysqli_error($link),true);
	if ($logout) {
		$_SESSION=array();
		session_destroy();
		muoribene('<p>'.t('Il tuo account è stato disattivato correttamente. Ciao! :-)','Your account has been correctly disabled. Bye! :-)').'</p>'.N,true);
	}
	$out='<div class="message">';
	if ($id!=0) {
		if ($ownacc)
			$out.=t('L’aggiornamento del <a href="account.php?id='.$id.'">tuo account («'.hspech($_POST['Email']).'»)</a> è andato a buon fine.','<a href="account.php?id='.$id.'">Your account («'.hspech($_POST['Email']).'»)</a> was updated successfully.');
		else
			$out.=t('L’aggiornamento dell’<a href="account.php?id='.$id.'">account «'.hspech($_POST['Email']).'»</a> è andato a buon fine.','<a href="account.php?id='.$id.'">Account «'.hspech($_POST['Email']).'»</a> was updated successfully.');
	} else {
		$id=mysqli_insert_id($link);
		$out.='Il <a href="account.php?id='.$id.'">nuovo account «'.hspech($_POST['Email']).'»</a> è stato creato correttamente.';
	}
	$out.='</div>'.N;
} else {
	$out='<form action="account.php" method="post" name="f" id="f">'.N;
	$out.='<table class="edtab">'.N;
	$out.='<tr><td class="insthead">'.$atit.'</td></tr>'.N;
	$out.='<tr>'.N;
	$out.='<td>'.N;
	$out.='<input type="hidden" name="id" value="'.$id.'">'.N;
	$out.='<div class="edrow"><div class="edfieldd"><label for="Username">'.t('Nome','Name').':</label></div><div class="edfield"><input type="text" name="Username" id="Username" value="'.hspech($acc['Username']).'" class="edinp" minlength="1" maxlength="'.$fields['Username'].'" required autofocus></div></div>'.N;
	$out.='<div class="edrow"><div class="edfieldd"><label for="Email">Email:</label></div><div class="edfield"><input type="email" name="Email" id="Email" value="'.hspech($acc['Email']).'" minlength="3" maxlength="'.$fields['Email'].'" class="edinp" required></div></div>'.N;
	if ($id!=0) $out.='<div class="eddesc">'.t('Lascia vuoti i campi “Password” e “Conferma password” per mantenere la password attuale.','Leave “Password” and “Password confirm” fields blank to keep your current password.').'</div>'.N;
	$out.='<div class="edrow"><div class="edfieldd"><label for="Password">Password:</label></div><div class="edfield"><input type="password" name="Password" id="Password" minlength="8" maxlength="64" class="edinp" autocomplete="new-password"'.$passreq.'></div></div>'.N;
	$out.='<div class="edrow"><div class="edfieldd"><label for="CPassword">'.t('Conferma password','Confirm password').':</label></div><div class="edfield"><input type="password" name="CPassword" id="CPassword" minlength="8" maxlength="64" class="edinp"></div></div>'.N;
	if ($account['Level']!='guest' && !$ownacc) {
		$out.='<div class="edrow"><div class="edfieldd"><label for="Level">Livello:</label></div><div class="edfield"><select name="Level" id="Level" class="edinp"><option value="guest"'.(($acc['Level']=='guest') ? ' selected' : '').'>Ospite</option><option value="normal"'.(($acc['Level']=='normal') ? ' selected' : '').'>Normale</option>';
		if ($account['Level']=='super')
			$out.='<option value="super"'.(($acc['Level']=='super') ? ' selected' : '').'>Super</option>';
		$out.='</select></div></div>'.N;
		$out.='<div class="edrow"><div class="edfieldd"><label for="MaxLocalities">Numero massimo di località aggiungibili:</label></div><div class="edfield"><input type="number" step="1" name="MaxLocalities" id="MaxLocalities" min="'.$fields['MaxLocalities']['min'].'" max="'.$fields['MaxLocalities']['max'].'" value="'.$acc['MaxLocalities'].'" required class="edinp"></div></div>'.N;
		$out.='<div class="edrow"><div class="edfieldd"><label for="MaxLanguages">Numero massimo di lingue aggiungibili:</label></div><div class="edfield"><input type="number" step="1" name="MaxLanguages" id="MaxLanguages" min="'.$fields['MaxLanguages']['min'].'" max="'.$fields['MaxLanguages']['max'].'" value="'.$acc['MaxLanguages'].'" required class="edinp"></div></div>'.N;
		$out.='<div class="edrow"><div class="edfieldd"><label for="MaxFinancing">Numero massimo di mod. di finanziamento aggiungibili:</label></div><div class="edfield"><input type="number" step="1" name="MaxFinancing" id="MaxFinancing" min="'.$fields['MaxFinancing']['min'].'" max="'.$fields['MaxFinancing']['max'].'" value="'.$acc['MaxFinancing'].'" required class="edinp"></div></div>'.N;
		$out.='<div class="edrow"><div class="edfieldd"><label for="MaxPolicies">Numero massimo di policies aggiungibili:</label></div><div class="edfield"><input type="number" step="1" name="MaxPolicies" id="MaxPolicies" min="'.$fields['MaxPolicies']['min'].'" max="'.$fields['MaxPolicies']['max'].'" value="'.$acc['MaxPolicies'].'" required class="edinp"></div></div>'.N;
		$out.='<div class="edrow"><div class="edfieldd"><label for="MaxTags">Numero massimo di categorie aggiungibili:</label></div><div class="edfield"><input type="number" step="1" name="MaxTags" id="MaxTags" min="'.$fields['MaxTags']['min'].'" max="'.$fields['MaxTags']['max'].'" value="'.$acc['MaxTags'].'" required class="edinp"></div></div>'.N;
	}
	$out.='<div class="edrow"><div class="edfieldd"><label for="Enabled">'.t('Stato account:','Account status:').'</label></div><div class="edfield"><select name="Enabled" id="Enabled" class="edinp"><option value="1"'.(($acc['Enabled']==1) ? ' selected' : '').'>'.t('Attivo','Enabled').'</option><option value="0"'.(($acc['Enabled']==0) ? ' selected' : '').'>'.t('Non attivo','Disabled').'</option></select></div></div>'.N;
	$out.='<input type="submit" value="'.t('Salva','Save').'" class="button" onclick="return ckf();">'.N;
	$out.='</td>'.N;
	$out.='</tr>'.N;
	$out.='</table>'.N;
	$out.='</form>'.N;
}

mysqli_close($link);

?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>Mustard - <?php echo($atit); ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="description" content="Admin pages for Mastodon Help">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link rel="icon" type="image/png" href="imgs/icona-32.png" sizes="32x32">
<link rel="icon" type="image/png" href="imgs/icona-192.png" sizes="192x192">
<link rel="icon" type="image/png" href="imgs/icona-512.png" sizes="512x512">
<link rel="apple-touch-icon-precomposed" href="imgs/icona-180.png">
<link rel="stylesheet" type="text/css" href="css/theme.css?v=<?php echo($cjrand); ?>">
<script language="JavaScript" src="js/menu.js?v=<?php echo($cjrand); ?>"></script>
<script language="JavaScript" src="js/alerta.js?v=<?php echo($cjrand); ?>"></script>
<script language="JavaScript" src="js/confirma.js?v=<?php echo($cjrand); ?>"></script>
<script language="JavaScript">
<!--
<?php if ($account['Level']!='guest') require 'js/notifs.js.php'; ?>

let english=<?php if ($english) echo('true'); else echo('false'); ?>;
let ownacc=<?php if ($ownacc) echo('true'); else echo('false'); ?>;

function t(it,en) {
	if (!english)
		return(it);
	else
		return(en);
}

function ckf() {
	/*let objv=document.getElementById('Username').value, amsg='';
	if (objv.length()<1) amsg+='<li>'+t('“Nome” deve essere almeno un carattere','“Name” must be at least one character')+'</li>';*/
	//alert('La gira!');
	let pass=document.getElementById('Password'), cpass=document.getElementById('CPassword');
	pass.setCustomValidity('');
	if (pass.value!='' && pass.value!=cpass.value) {
		pass.setCustomValidity(t('“Password” e “Conferma password” non corrispondono','“Password” and “Confirm password” don’t match'));
		pass.reportValidity();
		return(false);
	} else {
		if (ownacc && document.getElementById('Enabled').value=='0') {
			confirma(t('Attenzione!','Warning!'),'<p>'+t('Stai per disabilitare il tuo stesso account: la sessione corrente sarà interrotta e non potrai più rientrare in Mustard finché un admin non lo riabiliterà. Confermi di voler disabilitare il tuo account?', 'You are about to disable your own account: current session will be closed and you won’t be able to log into Mustard again until an admin will re-enable it. Do you confirm you want to disable it?')+'</p>','No',t('Si','Yes'),'','document.f.submit();');
			return(false);
		} else {
			//document.f.submit();
			return(true);
		}
	}
}
//-->
</script>
</head>
<body>

<nav>
<div id="hmenu">
<ul>
<?php echo($menuout); ?>
</ul>
<div class="mtit"><?php echo($atit); ?></div>
<div id="rightdiv">
<?php if ($account['Level']!='guest') echo('<img src="'.$notifs['imgoff'].'" id="bell" class="rlinks" title="Show notifications" onclick="shidenotifs();">'.N); ?>
<img src="imgs/esci.svg" class="rlinks" title="Logout" onclick="document.location.href='logout.php';">
</div>
</div>
</nav>

<?php if ($account['Level']!='guest') echo($notifs['div']); ?>

<div id="popup">
<div id="inpopup">
<div id="popupcont">
...
</div>
</div>
</div>

<!-- <div id="footer">
</div> -->

<div id="fullscreen">
<div id="middlerow">
<?php echo($out); ?>
</div>
</div>

<div id="debug">
<?php echo($dbg); ?>
</div>

</body>
</html>
