<?php
    session_start();
    header('Content-Type: text/html; charset=utf-8');
    //echo chr(239).chr(187).chr(191);
    $user_id = $_SESSION['user_id'];
    $role = $_SESSION['role'];
	
	$instance_id = $_SESSION['client_id'];
	
        //include "db.php";
        //include "../settings.php";
		//include ('mysql.php');
        
		$dbset = json_decode($_SESSION['settingsApp'],true);
		$db = new mysqli ($dbset['DB']['DB_HOST'],$dbset['DB']['DB_USER'],$dbset['DB']['DB_PASS'],$dbset['DB']['DB_NAME']);

		//$db = new mysqli ($DB_HOST,$DB_USER,$DB_PASS,$DB_NAME);
        $db->query("SET CHARSET SET utf8");
        $db->query("SET NAMES 'utf8'");
        if (mysqli_connect_errno()) {
            echo "Error connecting to DB";
            exit;
        }
//-------------show-------------------------------------------------------------		
		if ($_GET['func']=='users_adm_menfields')
        {
             $i=0;
             $query = "SELECT ms_user.id, ms_user.login, ms_user.first_name, ms_user.last_name, ms_rolenames.name FROM ms_user INNER JOIN ms_rolenames ON ms_user.id_role = ms_rolenames.id WHERE ms_user.`instance_id` = ".$instance_id.";"; // WHERE ms_user.id_role < 6
		//$query = "SELECT id, login, firstName, lastName, role FROM mw_users";
		  if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($id,$login,$first_name,$last_name,$name);
            while ($stmt->fetch()) {
                  $Users_adm_menFields [$i]= 
                    array(
    
                        'id'=>$id,
                        'login'=>$login,
			            'first_name'=>$first_name,
			            'last_name'=>$last_name,
			            'name'=>$name
                        );
    $i++;
            } 
            $stmt->close();
            $db->close();
        }

   echo'{rows:'.json_encode($Users_adm_menFields).'}';
            
        }
	
//-------------add--------------------------------------------------------------
           $i=0;
      /*  if ($_POST['func']=='users_adm_add')
        {
          $login=$_POST['login'];
		      $password=$_POST['password'];
          $role=$_POST['role'];
		       $firstName=$_POST['firstName'];
		       $lastName=$_POST['lastName'];
		       $middleName=$_POST['middleName'];
		       $position=$_POST['position'];
		       $bossID=$_POST['bossID'];
		       $email=$_POST['email'];
           $tel=$_POST['tel'];
		       $address=$_POST['address'];
           $comments=$_POST['comments'];
		       $client_id=$_POST['client_id'];
		   

           $query ="select max(id_user) from users";
           $stmt = $db->prepare($query);
           $stmt->execute();
           $stmt->bind_result($id);
            while ($stmt->fetch()) {
                $n_id=$id;
            }
            $n_id++;
            $query = "INSERT INTO users (id_user,bossId,login,password,firstName,lastName,middleName,position,email,tel,address,comments,role,client) VALUES (".$n_id.",'".$bossID."','".$login."','".md5($password)."','".$firstName."','".$lastName."','".$middleName."','".$position."','".$email."','".$tel."','".$address."','".$comments."',".$role.",".$client_id.")";
            $stmt = $db->prepare($query);
            $stmt->execute();       
            
			$i=0;
            $query = "SELECT users.id_user, users.login, users.firstName, users.lastName, roleNames.name_role FROM users INNER JOIN roleNames ON users.role = roleNames.id_role";
            if ($stmt = $db->prepare($query)){
            //$stmt->bind_param('i', $client_id);
            $stmt->execute();
            $stmt->bind_result($id,$login,$firstName,$lastName,$roleIndex);
            while ($stmt->fetch()) {
                  $Users_adm_menFields [$i]= 
            array(
            'id_user'=>$id,
            'login'=>$login,
			      'firstName'=>$firstName,
			      'lastName'=>$lastName,
			      'name_role'=>$roleIndex
            );
            $i++;
            } 
            $stmt->close();
            $db->close();
        }

   echo'{rows:'.json_encode($Users_adm_menFields).'}';
        }*/

//---------------- select to update------------------------------------------------------------------
	if ($_POST['func']=='users_adm_men_edit')
	{
	$select=$_POST['sel_adm_men_edit'];
    
	$query = "SELECT id,id_boss,login,password,first_name,last_name,middle_name,position,email,phone,address,comments,id_role,imei FROM ms_user WHERE id=".$select;
	
	if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($id,$id_boss,$login,$password,$first_name,$last_name,$middle_name,$position,$email,$phone,$address,$comments,$id_role,$imei);
            
			while ($stmt->fetch()) {
            $adm_men_edit .= $id.'/t'.$id_boss.'/t'.$login.'/t'.$password.'/t'.$first_name.'/t'.$last_name.'/t'.$middle_name.'/t'.$position.'/t'.$email.'/t'.$phone.'/t'.$address.'/t'.$comments.'/t'.$id_role.'/t'.$imei.'/n';
            } 
			$adm_men_edit = substr($adm_men_edit,0,strlen($adm_men_edit)-2);
            $stmt->close();
            $db->close();
        }
   echo $adm_men_edit;
   }
   
 //---------------- get Boss Name------------------------------------------------------------------
  if ($_POST['func']=='getBossName')
  {//DebugBreak();
  $id_boss = $_POST['id_boss'];
    
  $query = "SELECT CONCAT_WS(' ',first_name, last_name, middle_name) AS bossName FROM ms_user WHERE id=".$id_boss." AND `instance_id` = ".$instance_id.";";
  if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($bossName);
            
      while ($stmt->fetch()) {
            $adm_men_edit .= $bossName.'/t/n';
            } 
      $adm_men_edit = substr($adm_men_edit,0,strlen($adm_men_edit)-2);
            $stmt->close();
            $db->close();
        }
   echo $adm_men_edit;
   } 
   
   
//----------------create and update------------------------------------------------------------------
        $i=0;
        if ($_POST['func']=='users_adm_update')
        {
           $id=$_POST['id'];
		       $login=$_POST['login'];
		       $password=$_POST['password'];
           $role=$_POST['id_role'];
		       $firstName=$_POST['first_name'];
		       $lastName=$_POST['last_name'];
		       $middleName=$_POST['middle_name'];
		       $position=$_POST['position'];
		       $bossID=$_POST['id_boss'];
		       $email=$_POST['email'];
           $tel=$_POST['phone'];
		       $address=$_POST['address'];
		       $comments=$_POST['comments'];
			   $imei=$_POST['imei'];
				
				if(!isset($bossID) || $bossID==""){ $bossID = 'NULL'; }
				
		   //DebugBreak();
            if ($id == 'NaN')                             // add new rows
            {
              $query = "SELECT MAX(id) FROM ms_user";
              $result = $db->query($query);
              //$stmt->execute();
              $row = $result->fetch_array(MYSQLI_NUM);
              $id = $row[0];
              $id++;
              $query = "INSERT INTO ms_user (id,login,password,id_role,first_name,last_name,middle_name,position,id_boss,email,phone,address,comments,imei,instance_id) VALUES (".$id.",'".$login."','".md5($password)."',".$role.",'".$firstName."','".$lastName."','".$middleName."','".$position."',".$bossID.",'".$email."','".$tel."','".$address."','".$comments."','".$imei."',".$instance_id.")";
            }
            else                                        // update rows
            {
              if (empty($password)){
                $query ="SELECT password FROM ms_user WHERE id=".$id;
                $sql = mysql_query($query) or die(mysql_error());
                if (mysql_num_rows($sql) == 1)
                {
                  $row = mysql_fetch_assoc($sql);
                  $password=$row['password'];
                }
              }
              else{
                $password=md5($password);
              }
              
              $query = "UPDATE ms_user SET login='".$login."',password='".$password."',id_role=".$role.",first_name='".$firstName."',last_name='".$lastName."',middle_name='".$middleName."',position='".$position."',id_boss=".$bossID.",email='".$email."',phone='".$tel."',address='".$address."',comments='".$comments."',imei=".$imei." WHERE id=".$id;
            }
			//echo $query;
			
            $stmt = $db->prepare($query);
            $stmt->execute();
            $i++;       
			
			
			
           /*$i=0;
		   $query = "SELECT ms_user.id, ms_user.login, ms_user.first_name, ms_user.last_name, ms_rolenames.name FROM ms_user INNER JOIN ms_rolenames ON ms_user.id_role = ms_rolenames.id";
        if ($stmt = $db->prepare($query)){
            //$stmt->bind_param('i', $client_id);
            $stmt->execute();
            $stmt->bind_result($id,$login,$first_name,$last_name,$name);
            while ($stmt->fetch()) {
                  $Users_adm_menFields[$i]= 
    array(
    
				  'id'=>$id,
				  'login'=>$login,
			      'first_name'=>$first_name,
			      'last_name'=>$last_name,
			      'name'=>$name
    );
    $i++;
            } 
       */
            
            $stmt->close();
            $db->close();
        }

   //echo'{rows:'.json_encode($Users_adm_menFields).'}';
        //}
		
//---------------------------------- delete ------------------------------------------------------------------
        $i=0;
		if ($_POST['func']=='delete')
        {
           $id=$_POST['id'];
           $query = "DELETE FROM ms_user WHERE id=".$id;
           //echo $query;
           $stmt = $db->prepare($query);
           $stmt->execute();       
        
		/*$i=0;
        $query = "SELECT ms_user.id, ms_user.login, ms_user.first_name, ms_user.last_name, ms_rolenames.name FROM ms_user INNER JOIN ms_rolenames ON ms_user.id_role = ms_rolenames.id";
        if ($stmt = $db->prepare($query)){
            //$stmt->bind_param('i', $client_id);
            $stmt->execute();
            $stmt->bind_result($id,$login,$first_name,$last_name,$name);
            while ($stmt->fetch()) {
                  $Users_adm_menFields [$i]= 
    array(
    
            'id'=>$id,
            'login'=>$login,
			      'first_name'=>$first_name,
			      'last_name'=>$last_name,
			      'name'=>$name
    );
    $i++;
            } 
       
         */   
            $stmt->close();
            $db->close();
        }

   //echo'{rows:'.json_encode($Users_adm_menFields).'}';
        //}
		
//---------------------- select model boss ------------------------------------------------------------------------
		if ($_GET['func']=='boss')
        {
             $i=0;
        $query = "SELECT id, CONCAT_WS(' ',first_name, last_name, middle_name) AS FIO_B FROM ms_user WHERE `instance_id` = ".$instance_id.";";
		if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($id, $FIO_B);
            while ($stmt->fetch()) {
                  $boss_id [$i]= 
    array(
    
            'id'=>$id,
			      'FIO_B'=>$FIO_B
    );
    $i++;
            } 
            
            $stmt->close();
            $db->close();
        }

   echo'{rows:'.json_encode($boss_id).'}';
            
        }
        /*if ($_GET['func']=='client')
        {
             $i=0;
        $query = "SELECT id,name FROM mw_clients";
        if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($id, $name);
            while ($stmt->fetch()) {
                  $boss_id [$i]= 
    array(
    
            'id'=>$id,
            'name'=>$name
    );
    $i++;
            } 
       
            
            $stmt->close();
            $db->close();
        }

   echo'{rows:'.json_encode($boss_id).'}';
            
        }*/
		
		
		
		if ($_GET['func']=='getRolenames')
{
  $i=0;
  $query = "SELECT id,name FROM ms_rolenames LIMIT 100";
  if ($stmt = $db->prepare($query))
  {
    $stmt->execute();
    $stmt->bind_result($id,$name);
    while ($stmt->fetch())
    {
      $arrayRolenames[$i]= 
      array(
        'id'=>$id,
        'name'=>$name
      );
      $i++;
    } 
    $stmt->close();
    $db->close();
  }

  echo'{rows:'.json_encode($arrayRolenames).'}';
}
		
?>