<?php  
  session_start();
    header('Content-Type: text/html; charset=utf-8');
    $instance_id = $_SESSION['client_id'];
        //require "log.php";
        //include "../settings.php";
    require_once("../settings.php");
    require_once("ClassLibs/ClassMessageAndLogs.php");
		include "writedblog.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;
        }
        $ObjLogsTOiR = new MessageAndLogs();
//-----------------------------------------------------------------show-------------------------------------------------------------    
    
    if ($_GET['func']=='show')
        {
        $i=0;
        $query = "SELECT id,name,password,id_role,tel,email,post,department,imei, external_id FROM toir_users  
        		WHERE instance_id = $instance_id LIMIT 100";
    if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($id,$name,$password,$id_role,$tel,$email,$post,$department,$imei,$external_id);
            while ($stmt->fetch()) 
            {
              $Model [$i]= 
                array(
					  'id'=>$id,
					  'name'=>$name,
                      'password'=>$password,
                      'id_role'=>$id_role,
                      'tel'=>$tel,
                      'email'=>$email,
                      'post'=>$post,
                      'department'=>$department,
                      'imei'=>$imei,
                	  'external_id' => $external_id	
                      );            
                $i++;
            } 
            $stmt->close();
            $db->close();
        }
   echo'{rows:'.json_encode($Model).'}';   
        }

// ----------------------------------------------------roles--------------------------------------------------------------
if ($_GET['func']=='roles')
{
		$i=0;
		$query = "SELECT `id_role`,`name_role` FROM `toir_roles`";
		if ($stmt = $db->prepare($query)) {
			$stmt->execute();
            $stmt->bind_result($id,$type);
			while ($stmt->fetch()) 
            {
              $Model [$i]= 
                array(
					  'id'=>$id,
					  'type'=>$type
                      );            
                $i++;
            } 
            $stmt->close();
			echo'{rows:'.json_encode($Model).'}';
		}
		$db->close();
		exit;
}
//-----------------------------------------------------------------add-------------------------------------------------------        

if ($_POST['func']=='addedit')
        {  
          foreach ($_POST as $key => $value)
          {
            $data[$key] = $value;
          }
          
          $query = "SELECT `id` FROM `toir_users` WHERE  `name`='$data[name]' ";
          $stmt = $db->prepare($query);
          $stmt->execute();
          $stmt->bind_result($id);
          $stmt->fetch();
          $stmt->close();
          if ($id && (!$_POST['id'] || $_POST['id'] =="")) {
          	echo json_encode(array('success'=>false,'message'=>'Пользователь с таким именем уже существует в системе. Введите другое имя.'));
          } else {
          	if($_POST['id'] || $_POST['id']!=""){
          		//password='".$data[password]."',
				$query = "UPDATE toir_users SET name='".$data[name]."',id_role=3,
          				tel='".$data[tel]."',email='".$data[email]."',post='".$data[post]."',department='".$data[department]."',
          						imei='".$data[imei]."', external_id='$data[external_id]', password='".$data[password]."' WHERE id = ".$data[id].";";
          	}else{
          		$query = "INSERT INTO toir_users (name,password,id_role,tel,email,post,department,imei, instance_id, external_id)
						VALUES ('".$data[name]."','".$data[password]."',3,'".$data[tel]."','".$data[email]."',
								'".$data[post]."','".$data[department]."','".$data[imei]."',$instance_id, '$data[external_id]')";
          	}
          	// echo $query;
          	// exit;
          	//$sql = $db->real_query($query);
          	//writeToLogDB($db,$query);
          	$ObjLogsTOiR->WriteLogAttendance("ADD users".$query,'Toir_log','../logs');
          	if ($stmt = $db->prepare($query)) {
          		$stmt->execute();
          		$stmt->close();
          		echo json_encode(array('success'=>true,'message'=>''));
          	} else {
          		echo json_encode(array('success'=>false, 'message'=>$db->errno . ' ' . $db->error));
          	}
          	 
          	/*$time = date("j-M-Y G:i : s");
          	 $ip = getenv('REMOTE_ADDR');
          	$referrer = getenv('HTTP_REFERER');
          	$quer = $query;
          	$msg = "IP: ".$ip." || TIME: ".$time." || REFERRER: ".$referrer." || DATA: Добавление нового пользователя   || SEARCHSTRING  ".$quer;
          	writeToLogFile($msg);*/
          	 
          	$db->close();
          	exit;
          	//echo json_encode(array('success'=>true,'content'=>$_POST));
          }
           
		       
        }
        
        
//-----------------------------------------------------------------delete-------------------------------------------------------------    
                
    if ($_POST['func']=='del')
        { 
           //$name = $_POST['name'];
		   $id = $_POST['name'];
           //$query = "DELETE FROM user WHERE name='".$name."' LIMIT 1";
		   $query = "DELETE FROM toir_users WHERE id='".$id."' LIMIT 1";
            if ($stmt = $db->prepare($query)) {
            $stmt->execute();
			$stmt->close();
				echo json_encode(array('success'=>true,'message'=>''));
			} else {
				echo json_encode(array('success'=>false, 'message'=>$db->errno . ' ' . $db->error));
			}
            /*$time = date("j-M-Y G:i : s");
            $ip = getenv('REMOTE_ADDR');
            $referrer = getenv('HTTP_REFERER');
            $quer = $query;  
            $mes = $name;
            $msg = "IP: ".$ip." || TIME: ".$time." || REFERRER: ".$referrer." || DATA: Удаление пользователя : ".$mes." || SEARCHSTRING  ".$quer;
            writeToLogFile($msg);
            */
           $db->close(); 
        }
        

//-----------------------------------------------------------------update-------------------------------------------------------------    
                    
    /*if ($_GET['func']=='update')
        {  
          foreach ($_POST as $key => $value)
          {
            $data[$key] = $value;
          }
           $query = "UPDATE user SET password='".$data[password]."',id_role='".$data[id_role]."',tel='".$data[tel]."',email='".$data[email]."',post='".$data[post]."',department='".$data[department]."' WHERE name='".$data[name]."'";
           $stmt = $db->prepare($query);
           $stmt->execute();
           
            $time = date("j-M-Y G:i : s");
            $ip = getenv('REMOTE_ADDR');
            $referrer = getenv('HTTP_REFERER');
            $quer = $query;  
            $mes = $data['name'];
            $msg = "IP: ".$ip." || TIME: ".$time." || REFERRER: ".$referrer." || DATA: Изменение данных пользователя : ".$mes." || SEARCHSTRING  ".$quer;
            writeToLogFile($msg);
           
           $stmt->close();
           echo json_encode(array('success'=>true,'content'=>$_POST));
        }*/
		
		
	if ($_POST['func']=='editshow')
      {
		$id = $_POST['id'];
		$query = "SELECT `name`,`password`,`id_role`,`tel`,`email`,`post`,`department`,imei, external_id FROM `toir_users` WHERE `id`=".$id.";";
		//echo $query;
		if (!$stmt = $db->query($query)) {
			echo json_encode(array('success'=>false, 'message'=>$db->errno . ' ' . $db->error));
		} else {
			//$result = $stmt->fetch_all(MYSQLI_ASSOC);
			for ($result = array(); $tmp = $stmt->fetch_array(MYSQL_NUM);)
            $result[] = $tmp;
			$stmt->close();
			echo json_encode($result[0]);
		}
	}
        
        

?>