<?php 
  include "settings.php";
  include "logger.php";
  
  $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;
  }
  writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> loginClient <> '.$_POST['data'] );
  
  $data = $_POST['data'];
  $data = stripslashes($data);
  $arraydata = (array)json_decode($data);

  if ($arraydata['func']=='check_login')
  {
    $login = $arraydata["login"];
    $password = $arraydata["password"];

    $i=0;
    //$query = "SELECT COUNT(id),id FROM ms_user WHERE login='".$login."' AND password=md5('".$password."')" ;
	//$query = "SELECT COUNT(ID),ID FROM `tms_device` WHERE `Login`='".$login."' AND `Pwd`='".md5($password)."';";
	$query = "SELECT COUNT(`ID`),`ID` FROM `tms_device` WHERE DeletedRecord = 0 AND (`Login`='".$login."' AND `Pwd`='".md5($password)."') GROUP BY ID LIMIT 0,1;";
	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> loginClient <> '.$query );
	$globID;
	$carCount;
	$Model = array();
	if ($stmt = $db->prepare($query)){
		$stmt->execute();
		$stmt->bind_result($count_id,$id);
		$r = $stmt->fetch();
		if( !empty( $r ))
		{
			//$Model[0]=array('COUNT(id)'=>$count_id,'id'=>$id);
			$globID = $id;
		}
		$stmt->close();
	}	
	if( !empty( $globID ))
	{	
		$query = "SELECT COUNT(*) FROM tms_car WHERE Device_ID = ".$globID." AND DeletedRecord = 0;";
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> loginClient <> '.$query );
		if ($stmt = $db->prepare($query)){
		$stmt->execute();
		$stmt->bind_result($carCount);
		$stmt->fetch();
		$stmt->close();
		}
	}
	
	if($carCount > 0)
	{
		$Model[0] = array('id'=>$globID);
	}
	else
	{
		$query = "SELECT t_cr.`Device_id` FROM tms_driver t_dr LEFT JOIN tms_car t_cr ON t_dr.`Driver_ID`=t_cr.`Driver_id` WHERE t_cr.`DeletedRecord`=0 AND t_dr.`DeletedRecord`=0 AND t_dr.`Device_id`=".$globID." LIMIT 1;";
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> loginClient <> '.$query );
		if ($stmt = $db->prepare($query)){
		$stmt->execute();
		$stmt->bind_result($id);
		$stmt->fetch();
		$stmt->close();
		$Model[0] = array('id'=>$id);
		}
	}
	  
	$db->close();

    echo json_encode($Model);
	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> loginClient <> '.json_encode($Model) );
  }
?>