<?php
require_once "./shared/classes.php";
if (checkSource()==false) {return;}
/* -- Object returned decalaration --*/
$obj = new stdClass();


/* -- T O K E N -- */
if (isset($_POST['token'])) { 
	$token=trim(htmlspecialchars($_POST['token'])); 
} else {
	returnError(-1002, "Invalid Token");
	return false;
}

/* -- uid -- */
if (isset($_POST['uid'])) { 
	$uid=trim(htmlspecialchars($_POST['uid'])); 
} else {
	returnError(-1002, "Invalid uid");
	return false;
}

/*-- Sql Connection --*/
$dbCo = phpPdoConnect();
if ($dbCo===false) {return; } //Error message is handled in function


//get user from token and check rights
$user_pk="0";
$user_uid="";
$user_isanonymous="0";
$user_admin="0";
try {
	$sql="Select * from _auth where auth_token=:token";
	$stmt = $dbCo->prepare($sql);
	$stmt->bindParam(':token', $token);
	$stmt->execute();
	if ($row = $stmt->fetch(PDO::FETCH_OBJ)) {
		$user_pk=$row->pk;
		$user_uid=$row->uid;
		$user_isanonymous=$row->auth_anonymous;
		$user_admin=$row->auth_admin;
		$user_enabled=$row->auth_enabled;
	} else {
		returnError(-1010, "Invalid user token");
		return false;
	}
} catch (PDOException $e) {
	returnError(-1002, "Unable to load user from token: ".$e->getMessage());
	return false;
}

/*-- Check Anonymous --*/
if ( ($user_isanonymous==="1")) {
	returnError(-1011, "Unable to disable Anonymous user");
	return false;
}

// -- Delete --*/
 try {
	 $dbCo->beginTransaction();
	 $sql = 'delete from _auth where uid=:uid and pk=:pk';
	 $stmt = $dbCo->prepare($sql);
	 $stmt->bindValue('uid', $uid);
	 $stmt->bindValue('pk', $user_pk);
	 $stmt->execute();
	 $rowCount = $stmt->rowCount(); //number of rows affected by the last SQL statement
 } catch (PDOException $e) {
	 $dbCo->rollBack();
	 returnError(-1011, $e->getMessage());
	 return;
 }

 if (($rowCount == 0) && ($newRecord == false)) {
	returnError(-1050, "Nothing was Deleted, Record not found ". $uid." ".$pk);
	return;
}


	//OK Commit
	$dbCo->commit();

	header("Content-Type: application/json; charset=UTF-8");
	/* -- Object returned decalaration --*/
	$obj->code = 0;
	$obj->message = "User Account Deleted";
	$obj->deleted=$rowCount;
	echo safe_json_encode($obj);
	return;

?>