<?php  
  session_start();
    header('Content-Type: text/html; charset=utf-8');
	$instance_id = $_SESSION['client_id'];
        //require "log.php";
        //include "../settings.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;
        }
        
if ($_REQUEST['func'] == 'show') {
	$userID = $_REQUEST['userID'];
	$time = $_REQUEST['time'];
	$query = "SELECT r.`id_request`,  c.`client`, o.`name`, r.`region`,  r.`city`, r.`address`, 
		r.`status`, r.`time_execut`, t.`name_job`, o.`id_outlet`, o.geoX, o.geoY, r.time_beginning_work FROM `toir_request` r
		INNER JOIN  `type_job` t   ON t.id_type_job= r.`id_type_job`
		INNER JOIN `client` c ON c.id_client = r.`client_id`
		INNER JOIN `toir_users` u ON u.id=r.`name_master`
		INNER JOIN `equipment` e ON e.`id_equipment`=r.`id_equipment`
		INNER JOIN `toir_outlets` o ON o.`id_outlet`=r.`outlet_id`
		 WHERE u.id = $userID AND r.`time_execut`>='".$time.' 00:00:00'."' AND r.`time_execut`<='".$time.' 23:59:59'."' 
		 		ORDER BY r.place;";
	//echo $query; exit;
	$stmt = $db->prepare($query);
	$stmt->execute();
	$stmt->bind_result($id, $client, $outlet,    $region, $city, $address,   $status,  $time_execut, $job_type, $id_outlet,
						$geoX, $geoY, $time_beginning_work);	
	while($stmt->fetch()) {
		$address = $region.' '.$city.' '.$address;
		if ($status == 1) {
			$status = '<img src="images/cmd_ok24.png" />';
		} else {
			$status = '<img src="images/Point_Red_old.png" />';
		}
		$data[] = array(
			'id' => $id,
			'client' => $client,
			'outlet' => $outlet,
			'address' => $address,
			'status' => $status,
			'time_execute'	=> $time_execut,
			'job_type' => $job_type,
			'id_outlet' => $id_outlet,
			'geoX' => $geoX,
			'geoY' => $geoY,
			'time_beginning_work' => $time_beginning_work								
		);
	}	
	echo'{rows:'.json_encode($data).'}';
} 

if ($_REQUEST['func'] == 'showUsers') {	
	$query = "SELECT id, `name` FROM `toir_users` WHERE `instance_id`=$instance_id";
	$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'] == 'getRoutePath') {
	$trip_id = $_REQUEST['trip_id'];
	$query = "SELECT `trip_route` FROM `toir_trip` WHERE `id`=$trip_id";	
	$stmt = $db->prepare($query);
	$stmt->execute();
	$stmt->bind_result($trip_route);
	$stmt->fetch();
	echo $trip_route;
}