<?php 
session_start();
header('Content-Type: text/html; charset=utf-8');



$client_id = $_SESSION['client_id'];
$user_id = $_SESSION['id'];
$role = $_SESSION['role_id'];

//require "log.php";
//include "../settings.php";
include "writedblog.php";
include "logger.php";
include "LogistMobile_function.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_HOST='194.0.150.90';
$DB_USER='ilog';
$DB_PASS='1111';
$DB_NAME='tms37';
$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') {
	
	$whereWarh = "";
	$whereDevc = "";
	if( $_REQUEST['warehouse'] || $_REQUEST['warehouse'] != "" ){
		$whereWarh = " AND ch.`Name` = '".$_REQUEST['warehouse']."'";
	}
	
	if( $_REQUEST['device'] || $_REQUEST['device'] != "" ){
		$whereDevc = " AND (wc.`imei` LIKE '%".$_REQUEST['device']."%' OR wc.`car_name` LIKE '%".$_REQUEST['device']."%')";
	}
	
	$whereon = "";
	$project_in = project_to_users($db);
	if(count($project_in)>0){
		$whereon = " AND p.`Project_ID` IN (".implode(",", $project_in).")";
	}
	
	$imei_in = imei_to_users($db);
	if($role == 1){
		$where = "";
	}else{
		if(count($imei_in)>0){
			$imei_in_str = "'".implode("','", $imei_in)."'";
			$where = " AND td.`Login` IN (".$imei_in_str.")";
		}else{ echo '{rows:[]}'; exit; }
	}

//CONCAT('',wc.`car_name`,' (',td.`Login`,')') AS Login
$query = "SELECT f.`TripId`,f.`Name`,wc.`car_name`,p.`Name` AS Project,f.`StartTime`,f.`EndTime`,td.`Login`,IF(tc.`Active`=2,'true','false') FROM tms_facttrip f
INNER JOIN `tms_checkpoint` ch ON ch.`FactTripID` = f.`ID`
INNER JOIN `tms_project` p ON p.`Project_ID` = f.`Project_Id` ".$whereon."
LEFT JOIN `tms_car` tc ON f.`Car_ID`=tc.`Car_ID`
LEFT JOIN `tms_device` td ON tc.`Device_id`=td.`ID`
INNER JOIN `wm_car_info` wc ON wc.`imei` = td.`Login`  
WHERE p.`Client_ID` = ".$client_id." AND DATE(p.`Date`) = CURDATE() ".$whereDevc." ".$whereWarh." ".$where." GROUP BY f.`TripId`";
//echo $query;
$i=0;
$j=0;

$stmt = $db->prepare($query);
$stmt->execute();
$stmt->bind_result($TripId,$Name,$Login,$Project,$StartTime,$EndTime,$Login2,$Active);
$stmt->store_result();
if($stmt->num_rows()>0){
while( $stmt->fetch() ){
	$idArr[$j] = $Login2;
	$data[$i] = array(
			'TripId' => $Name,
			'Name' => $Name,
			'Login' => $Login,
			'Project' => $Project,
			'Login2' => $Login2,
			'StartTime' => $StartTime,
			'StartTime' => $StartTime,
			'EndTime' => $EndTime,
			'indoor' => $Active
		);
	$i++;
	$j++;
}
}
$stmt->close();

/*
	if(!$stmt = $db->query($query)){
			echo '{"success":false,"message":"'.$db->errno.' '.$db->error.'"}';
	}else{
			//$result = $stmt->fetch_all(MYSQLI_ASSOC);
			for ($result = array(); $tmp = $stmt->fetch_array(MYSQLI_ASSOC);) $result[] = $tmp;
			$stmt->close();
			echo '{rows:'.json_encode($result).'}';
	}
*/

if( count($idArr) > 0 ){
$strid = implode(',', $idArr);
}else{ $strid = '0'; }

//CONCAT('',c.`car_name`,' (',d.`Login`,')') AS Login

if( !$_REQUEST['warehouse'] || $_REQUEST['warehouse'] == "" ){

$query = "SELECT wc.`car_name`, td.Login, IF(cr.`Active`=2,'true','false') FROM `tms_device` td
INNER JOIN `wm_car_info` wc ON wc.`imei` = td.`Login`
INNER JOIN `tms_car` cr ON cr.`Device_id` = td.`ID`
WHERE td.`Client_id` = ".$client_id." ".$where." AND td.Login NOT IN (".$strid.") ".$whereDevc.";";
//echo $query;
$stmt = $db->prepare($query);
$stmt->execute();
$stmt->bind_result($Login,$Login2,$Active);
while( $stmt->fetch() ){
	$data[$i] = array(
			'TripId' => '',
			'Name' => '',
			'Login' => $Login,
			'Project' => '',
			'Login2' => $Login2,
			'StartTime' => '',
			'StartTime' => '',
			'EndTime' => '',
			'indoor' => $Active
		);
	$i++;
}

$stmt->close();
}

echo'{rows:'.json_encode($data).'}';

	$db->close();
	exit;
}


// -------- блокировки/разблокировки авто----------
if ($_REQUEST['func'] == 'blockCar') {
//if(isset($_REQUEST['blockCar'])){
	$login = $_REQUEST['login'];
	$checked = $_REQUEST['checked'];
	
	if($checked=='true'){ $checked = 2; }else{ $checked = 1; }
	
	$query = "UPDATE tms_car SET `Active`=".$checked." WHERE `Device_id` = (SELECT ID FROM tms_device WHERE Login = '".$login."' LIMIT 1);";
	if($stmt = $db->prepare($query)){
	$stmt->execute();
	$stmt->close();
	echo '{"success":true,"message":""}';
	}else{ echo '{"success":false,"message":""}'; } 
	
	$db->close();
	exit;
}


// -------- функционал блокировки/разблокировки всех авто----------
if (isset($_REQUEST['blockcarall']))
{
	$checked = $_REQUEST['pressed'];
	
	$imei_in = imei_to_users($db);
	$imei_in_str = "'".implode("','", $imei_in)."'";
	$where = "SELECT ID FROM tms_device WHERE `Login` IN (".$imei_in_str.") AND client_id = ".$client_id."";
	
	if($checked=='true'){
		//$query = "UPDATE tms_car SET `Active`=2 WHERE `Device_id` IN (SELECT ID FROM tms_device WHERE client_id = ".$client_id.");";
		$query = "UPDATE tms_car SET `Active`=2 WHERE `Device_id` IN (".$where.");";
	}else{
		//$query = "UPDATE tms_car SET `Active`=1 WHERE `Device_id` IN (SELECT ID FROM tms_device WHERE client_id = ".$client_id.");
		$query = "UPDATE tms_car SET `Active`=1 WHERE `Device_id` IN (".$where.");";
	}
	//echo $query;
	if($stmt = $db->prepare($query)){
	if($stmt->execute()){
		$stmt->close();
	echo '{"success":true,"message":""}';
	}else{ echo '{"success":false,"message":""}'; }
	}else{ echo '{"success":false,"message":""}'; }
	
	$db->close();
	exit;
}