<?php  
  session_start();
    header('Content-Type: text/html; charset=utf-8');
	$ClientId = $_SESSION['client_id'];
	include 'TOiR_translate.php';
	
        //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();
$start = isset($_REQUEST['start']) ? $_REQUEST['start'] : 0;
$limit = isset($_REQUEST['limit']) ? $_REQUEST['limit'] : 50;		
if ($_REQUEST['func'] == 'showUsers') {	
	$data = array();
	$data[0] = array(
		'id' => 0,
		'name' => $all_workers
	);
	$query = "SELECT `id`, `name` FROM toir_users WHERE instance_id=$ClientId";
	$stmt = $db->prepare($query);
    $stmt->execute();
	$stmt->bind_result($id, $name);
	while($stmt->fetch()) {
		$data[] = array(
			'id' => $id,
			'name' => $name
		);
	}
	$stmt->close();	
	echo '{rows:'.json_encode($data).'}';	
}

if ($_REQUEST['func'] == 'showData') {	
	$groupSparel = isset($_REQUEST['groupSparel']) ? $_REQUEST['groupSparel'] : '';
	$nameSparel = isset($_REQUEST['nameSparel']) ? $_REQUEST['nameSparel'] : '';
	$selectUser = isset($_REQUEST['selectUser']) ? $_REQUEST['selectUser'] : false;
	if ($selectUser) {
		$user = "AND s.`users_id` = $selectUser";
		
	} else {
		$user = '';
		
	}
	$query = "SELECT COUNT(s.`id`) FROM  `toir_spares` s 
	WHERE s.`client_id`=$ClientId  
	AND (s.`spares_group` LIKE '%$groupSparel%' OR s.`spare` LIKE '%$nameSparel%')	 $user";
	$ObjLogsTOiR->WriteLogAttendance("SELECT count ".$query,'Toir_log','../logs');
	$stmt = $db->prepare($query);
    $stmt->execute();
	$stmt->bind_result($total);
	$stmt->fetch();
	$stmt->close();
		
	
	$query = "SELECT s.`id`,      
    s.`spares_group`,
    s.`spare`,
    s.`aticle`,
    s.`count` ,
    u.name 	FROM toir_spares s 
	LEFT JOIN  `toir_users` u ON u.id = s.users_id
    WHERE s.`client_id`=$ClientId 
	AND (s.`spares_group` LIKE '%$groupSparel%' OR s.`spare` LIKE '%$nameSparel%') $user LIMIT $start, $limit";
	
	
	$stmt = $db->prepare($query);
    $stmt->execute();
	$stmt->bind_result($id, $spares_group, $spare, $aticle, $count,$user);
	while($stmt->fetch()) {		
		$data[] = array(
			'id' => $id,
			'spares_group' => $spares_group,
			'spare' => $spare,
			'aticle' => $aticle,
			'count' => $count,		
			'user' => $user
		);
	}
	$stmt->close();
	echo '{"total":"'.$total.'","rows":'.json_encode($data).'}';
}

