#!/usr/bin/php
<?php


/*

first unset $channelInfoNew[$channelInfoKey]["channeluser"] ?!? 

tmp_usr table...create, insert ... do update set... usr_managment, drop tmp_usr 

create table tmp_usr (like usr_managment including all);
or
create table tmp_usr as table usr_managment with no data;

---

create table if not exists usr_managment( 
 channelid         bigint not null,
 channelname       text not null,
 userid            bigint not null,
 username          text not null default '-1',
 first_name        text not null default '-1',
 last_name         text not null default '-1',
 full_name         text not null default '-1',
 role              text not null, 
 activity          text not null default 'userStatusNoStatusSet', -- userStatusNoStatusSet|userStatusOnline|userStatusOffline|userStatusRecently|userStatusLastWeek|userStatusLastMonth|userStatusEmpty 
 lastupdate        bigint not null, 
 lastupdate_human  text not null, -- take: date($globalsettings["bot"]["defaultdateformat"], time())
  constraint usr_managment_pkey primary key(channelid, userid))

insert into usr_managment ... on conflict on constraint usr_managment_pkey do update set...
  
*/

function usr_managment_useractivity($data) {
 foreach (array_keys($data) as $k) {
  if (!array_key_exists("status", $data)) return "userStatusNoStatusSet";
  if ($data[$k]=="status") {
   if ($data["status"]["_"] == "" ) return "userStatusArrayIsEmpty_wtf";
   return $data["status"]["_"];
  } // if ($data[$k]=="status") 
 } // foreach (array_keys($data) as $k)
} // function end 

function usr_managment_user($channelInfoKey, $useridsearch, $useroption, $option) {
 global $globalsettings, $channelInfoNew;
 switch ($option) {
  case "userid":
                 if (!array_key_exists($useroption, $useridsearch)) { 
				  logger(mb_sprintf("usr_managment_getuser: userid %s not found", $useroption)); 
				  logger(mb_sprintf("------------------------------------------"));
				  $useridsearch=false; 
				 } // if (!array_key_exists($useroption, $useridsearch)) 
				 if ($useridsearch!=false) $useridsearch=array($useroption => true);
			     return $useridsearch; 
  break;  
  case "username":
                 $useridsearch=array(); 
				 foreach (array_keys($channelInfoNew[$channelInfoKey]["channeluser"]) as $userkey) {
				  if ($userkey != "lastupdate") {					  
				   if (str_contains(strtolower($channelInfoNew[$channelInfoKey]["channeluser"][$userkey]["full_name"]), strtolower($useroption))) {
					if (!array_key_exists($userkey, $useridsearch)) $useridsearch+=array($channelInfoNew[$channelInfoKey]["channeluser"][$userkey]["id"] => true);
				   } // if (str_contains($channelInfoNew[$channelInfoKey]["channeluser"][$userkey]["full_name"], $useroption)) 
 				   if (str_contains(strtolower($channelInfoNew[$channelInfoKey]["channeluser"][$userkey]["username"]), strtolower($useroption))) {
					if (!array_key_exists($userkey, $useridsearch)) $useridsearch+=array($channelInfoNew[$channelInfoKey]["channeluser"][$userkey]["id"] => true);
				   } // if (str_contains($channelInfoNew[$channelInfoKey]["channeluser"][$userkey]["full_name"], $useroption)) 
                  } // if ($userkey != "lastupdate"
				 } // foreach (array_keys($useridsearch) as $userkey) 
                 if (count($useridsearch) == 0) { 
				  logger(mb_sprintf("usr_managment_getuser: username like %s not found", $useroption)); 
				  logger(mb_sprintf("------------------------------------------"));
				  $useridsearch=false;
				 } // if (count($useridsearch) == 0) 				 
				 return $useridsearch;
  break;  
  case "role":
			  if (is_numeric($useroption)) { 
			   $useridsearch=usr_managment_user($channelInfoKey, $useridsearch, $useroption, "userid");
			  } else {
			   $useridsearch=usr_managment_user($channelInfoKey, $useridsearch, $useroption, "username");
			  } // if (is_numeric($useroption))
			  return $useridsearch;
  break;  
 } // switch ($searchterm) 	 
 return array(); // later...
} // function end

 
function usr_managment($channelInfoKey, $option=false, $useroption=false) { 
 global	$globalsettings, $channelInfoNew;

 if ($option=="renewcache") { $caching="renew cache"; } else $caching="caching";
 if (!array_key_exists("channeluser", $channelInfoNew[$channelInfoKey])) $channelInfoNew[$channelInfoKey]["channeluser"]=array();

 if ($option==false) {$printoption=""; } else $printoption="option: ".$option;
 if ($useroption==false) {$printuseroption=""; } else $printuseroption=", useroption: ".$useroption;

 logger(mb_sprintf("usr_managment: users on: %s (%s%s)", $channelInfoNew[$channelInfoKey]["name"], $printoption, $printuseroption));
 logger(mb_sprintf("------------------------------------------"));
 
 $usercount=array();
 
 if (array_key_exists("lastupdate", $channelInfoNew[$channelInfoKey]["channeluser"]) && $channelInfoNew[$channelInfoKey]["channeluser"]["lastupdate"] == 0) {
  logger(mb_sprintf("no rights to read userdata"));	
  logger(mb_sprintf("------------------------------------------"));  
  return false;
 } // if (!array_key_exists("lastupdate", $channelInfoNew[$channelInfoKey]["channeluser"]) && $channelInfoNew[$channelInfoKey]["channeluser"]["lastupdate"] == 0) 

 if (!array_key_exists("lastupdate", $channelInfoNew[$channelInfoKey]["channeluser"]) || $option == "renewcache") {
  logger(mb_sprintf("usr_managment: %s users on channel: %s", $caching, $channelInfoNew[$channelInfoKey]["name"]));
  
  $userdata = made("","getPwrChat()", array("peer" => $channelInfoNew[$channelInfoKey]["peerid"]));
  if ($userdata == false || count($userdata["participants"]) == 0) {
   $channelInfoNew[$channelInfoKey]["channeluser"]["lastupdate"]=0; 
   logger(mb_sprintf("------------------------------------------"));  
   logger(mb_sprintf("no rights to read userdata"));	
   logger(mb_sprintf("------------------------------------------"));  
  return false;
  } // if (count($userdata["participants"]) == 0 ) 

/*
 two steps... @db to a deleted user with lastupdate=0 into db. 

*/ 

  $channelInfoNew[$channelInfoKey]["channeluser"]["lastupdate"]=time();
  
  foreach ($userdata["participants"] as $user) { 
  
   foreach ($globalsettings["user"]["role"] as $role) {

	if (!array_key_exists("role", $user)) { 
	 $user["role"]="overloading";
	 logger(mb_sprintf("ERR: user has no role(overloading [role]), debug-data below"));  
	 print_r($user);
	} // if (!array_key_exists("role", $user)) 
		
    if ($role == $user["role"]) {
	
	 $deleted=true;
	 $userkey=$user["user"]["id"];
	
	 $channelInfoNew[$channelInfoKey]["channeluser"][$userkey]["id"]=$user["user"]["id"];
	 $channelInfoNew[$channelInfoKey]["channeluser"][$userkey]["role"]=$role;
	 $channelInfoNew[$channelInfoKey]["channeluser"][$userkey]["full_name"]="";
	
	 if (!array_key_exists("username", $user["user"])) {
      $channelInfoNew[$channelInfoKey]["channeluser"][$userkey]["username"]=-1; if ($deleted) $deleted=true;
	 } else { $channelInfoNew[$channelInfoKey]["channeluser"][$userkey]["username"]=$user["user"]["username"]; $deleted=false; }
	
	 if (!array_key_exists("first_name", $user["user"])) {
      $channelInfoNew[$channelInfoKey]["channeluser"][$userkey]["first_name"]=-1; 
	  $channelInfoNew[$channelInfoKey]["channeluser"][$userkey]["full_name"].=""; 
	  if ($deleted) $deleted=true;
	 } else { 
	 $channelInfoNew[$channelInfoKey]["channeluser"][$userkey]["first_name"]=$user["user"]["first_name"]; 
	 $channelInfoNew[$channelInfoKey]["channeluser"][$userkey]["full_name"].=$user["user"]["first_name"]; 
	 $deleted=false; }

     if (!array_key_exists("last_name", $user["user"])) {
      $channelInfoNew[$channelInfoKey]["channeluser"][$userkey]["last_name"]=-1; 
	  $channelInfoNew[$channelInfoKey]["channeluser"][$userkey]["full_name"].=""; 
	  if ($deleted) $deleted=true;
     } else { 
	  $channelInfoNew[$channelInfoKey]["channeluser"][$userkey]["last_name"]=$user["user"]["last_name"]; 
	  $channelInfoNew[$channelInfoKey]["channeluser"][$userkey]["full_name"].=" ".$user["user"]["last_name"]; 
	  $deleted=false; }
	
 	 if ($deleted && $role != "banned") $channelInfoNew[$channelInfoKey]["channeluser"][$userkey]["role"]="deleted account"; 
	
    } // if ($role == $users["role"]) 
   } // foreach ($globalsettings["user"]["role"] as $role)
  } // foreach ($userdata["participants"] as $users)
 } // if (!array_key_exists("lastupdate", $channelInfoNew[$channelInfoKey]["channeluser"])) 

 $rolesearch=$globalsettings["user"]["role"];
 $useridsearch=$channelInfoNew[$channelInfoKey]["channeluser"];
 
 switch (explode(":", $option)[0]) { 
  case "role": 
               $rolesearch=array();
               $dontprintchannelstats=true;
               foreach (explode("+", explode(":", $option)[1]) as $roleoption) {
				if (!in_array($roleoption, $globalsettings["user"]["role"])) { 
				 logger(mb_sprintf("usr_managment: role %s doesnt exists", $roleoption));
                 logger(mb_sprintf("------------------------------------------"));
				 return false; 
				} // if (!in_array($roleoption, $globalsettings["user"]["role"])) 
					
				if (!in_array($roleoption, $rolesearch)) $rolesearch[]=$roleoption;
			   } // foreach (explode("+", explode(":"$option)[1])) as $roleoption) 
			   
			   if ($useroption != false) {
				$useridsearch=usr_managment_user($channelInfoKey, $useridsearch, $useroption, "role");
			   } // if ($useroption != false) 
				   
               if ($useridsearch==false) return false;
  break;
  case "userid": 
                 if ($useroption == false) { logger(mb_sprintf("usr_managment: no userid")); return; }
				 $useridsearch=usr_managment_user($channelInfoKey, $useridsearch, $useroption, explode(":", $option)[0]); 
				 if ($useridsearch==false) return false;
				 $dontprintchannelstats=true;
  break;
  case "username": 
                 if ($useroption == false) { logger(mb_sprintf("usr_managment: no username")); return; }
				 $useridsearch=usr_managment_user($channelInfoKey, $useridsearch, $useroption, explode(":", $option)[0]); 
				 if ($useridsearch==false) return false;
				 $dontprintchannelstats=true;
  break;  
 } 
 
 
 $returnuser=array();
 foreach ($rolesearch as $role) {
  if(!array_key_exists($role, $usercount)) $usercount[$role]=0;
  if (!isset($dontprintchannelstats)) logger(mb_sprintf("------------------------------------------"));
  foreach (array_keys($useridsearch) as $userkey) {
   if ($userkey != "lastupdate") {
    if ($role == $channelInfoNew[$channelInfoKey]["channeluser"][$userkey]["role"]) {
     $usercount[$role]++;		
     if (!array_key_exists("alluser", $usercount)) $usercount["alluser"]=0;
     $usercount["alluser"]++;

     if ($channelInfoNew[$channelInfoKey]["channeluser"][$userkey]["username"] == -1) { $un=""; } else $un="@".$channelInfoNew[$channelInfoKey]["channeluser"][$userkey]["username"];
     
	 $returnuser[$userkey]["id"]=$channelInfoNew[$channelInfoKey]["channeluser"][$userkey]["id"];
	 $returnuser[$userkey]["username"]=$channelInfoNew[$channelInfoKey]["channeluser"][$userkey]["username"];
	 $returnuser[$userkey]["first_name"]=$channelInfoNew[$channelInfoKey]["channeluser"][$userkey]["first_name"];
	 $returnuser[$userkey]["last_name"]=$channelInfoNew[$channelInfoKey]["channeluser"][$userkey]["last_name"];
	 $returnuser[$userkey]["full_name"]=$channelInfoNew[$channelInfoKey]["channeluser"][$userkey]["full_name"];
	 $returnuser[$userkey]["role"]=$channelInfoNew[$channelInfoKey]["channeluser"][$userkey]["role"];
	 
     logger(mb_sprintf("usr_managment: id: %-11s un: %-20s(fn: %-30s) role: %-8s", 
       $channelInfoNew[$channelInfoKey]["channeluser"][$userkey]["id"],
	   $un,
       $channelInfoNew[$channelInfoKey]["channeluser"][$userkey]["full_name"],
	   $channelInfoNew[$channelInfoKey]["channeluser"][$userkey]["role"]
     )); 
    } // if ($role == $channelInfoNew[$channelInfoKey]["channeluser"][$userkey]["role"])
   } // if ($userkey != "lastupdate") 
  } // foreach (array_keys($channelInfoNew[$channelInfoKey]["channeluser"]) as $userkey)
 } // foreach ($globalsettings["user"]["role"] as $role) 

 if (!isset($dontprintchannelstats)) {
  foreach ($globalsettings["user"]["role"] as $role) {
   if (array_key_exists($role, $usercount)) logger(mb_sprintf("usr_managment: %-8s %s", $role.":", $usercount[$role])); 
  } // foreach ($globalsettings["user"]["role"] as $role) 
  if (!array_key_exists("alluser", $usercount)) {
   $channelInfoNew[$channelInfoKey]["channeluser"]["lastupdate"]=0;
   $usercount["alluser"]=0;
  } // if (!array_key_exists("alluser", $usercount)) 
  logger(mb_sprintf("usr_managment: alluser(-banned): %s", $usercount["alluser"]-$usercount["banned"])); 
  logger(mb_sprintf("------------------------------------------"));
  logger(mb_sprintf("last update: %s", date($globalsettings["bot"]["defaultdateformat"], $channelInfoNew[$channelInfoKey]["channeluser"]["lastupdate"])));
  logger(mb_sprintf("------------------------------------------"));
  
  if ($usercount["alluser"]==0) {
   logger(mb_sprintf("no rights to read userdata"));
   logger(mb_sprintf("------------------------------------------"));
   return false;
  } // if ($usercount["alluser"]==0) 
 } else { 
  if (!array_key_exists("alluser", $usercount)) {
   logger(mb_sprintf("no user found"));
   return false;
  } // if (!array_key_exists("alluser", $usercount)) 
  logger(mb_sprintf("------------------------------------------")); 
  return $returnuser;
 } // if (!isset($dontprintchannelstats)) 
} // function end

function usr_managmentJob() {
 global $channelInfoNew, $globalsettings;
 $channelread=1;
 foreach(array_keys($channelInfoNew) as $channelInfoKey) {
  if (!array_key_exists("channeluser", $channelInfoNew[$channelInfoKey]) || (!is_array($channelInfoNew[$channelInfoKey]["channeluser"]))) $channelInfoNew[$channelInfoKey]["channeluser"]=array();
  if ($channelInfoKey != "pandabot owner") {
   if ($channelInfoNew[$channelInfoKey]["status"] == "ok" && (!array_key_exists("lastupdate", $channelInfoNew[$channelInfoKey]["channeluser" ]))) {
    logger(mb_sprintf("job: usr_managment - gather userdata on: %s", $channelInfoNew[$channelInfoKey]["name"])); 
    usr_managment($channelInfoKey); 
    return;	
   }  // if ($channelInfoNew[$channelInfoKey]["status"] == "ok" && (!array_key_exists("lastupate", $channelInfoNew[$channelInfoKey]["channeluser"])))
  } // if ($channelInfoKey!="pandabot owner") 
 } // foreach(array_keys($channelInfoNew) as $channelInfoKey)
 if ($globalsettings["user"]["allchannelsreaded"] == false) {
  $globalsettings["user"]["allchannelsreaded"]=true;
  sendmessageintochannel("pandabot owner", "usr_managmentJob: all users on all channels done", -1);
  logger(mb_sprintf("job: usr_managment - all users on all channels readed")); 
 } // if ($globalsettings["user"]["allchannelsreaded"] == false) 
} // function end 

//$tet=usr_managment(2223393727, "username", "ove"); // lounge
//if ($tet!=false) print_r($tet);

// these inc contains:
//
// usr_managment()
// usr_managment_user()
// usr_managment_loaddbchache()
// usr_managment_savedbchache()
// usr_managmentJob() 
// usr_managment_useractivity() -- not in use 

