<?php  
  session_start();
    header('Content-Type: text/html; charset=utf-8');
    $instance_id = $_SESSION['client_id'];
	$user_id = $_SESSION['id'];
	
        //require "log.php";
        //include "../settings.php";
    //require '../scripts/ClassLibs/autoload.php';
    $locale = $_SESSION['locale'];
	//$objMonit = new Monitor();
		$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;
        }
//-----------------------------------------------------------------show-------------------------------------------------------------    
    
    if ($_REQUEST['func']=='show')
    {
        $i=0;
        /*$query = "SELECT m.`id`,m.`message`,m.`id_sender`,m.`id_recipient`,m.`time` FROM `wm_message` m
LEFT JOIN `wm_users` u ON u.id = m.id_recipient AND u.`client_id` = ".$instance_id."
LEFT JOIN tms_device d ON d.id = m.id_recipient AND d.`Client_id` = ".$instance_id."
WHERE m.`deleted` = 0;";*/
		$query = "SELECT m.`id`,m.`message`,m.`time`,m.id_recipient AS RID, m.id_sender AS SID
,IF( (SELECT Login FROM tms_device WHERE ID = RID) IS NULL, (SELECT login FROM `wm_users` WHERE `id` = RID), (SELECT Login FROM tms_device WHERE ID = RID) ) AS `res`
,IF( (SELECT Login FROM tms_device WHERE ID = SID) IS NULL, (SELECT login FROM `wm_users` WHERE `id` = SID), (SELECT Login FROM tms_device WHERE ID = SID) ) AS `sen`
FROM `wm_message` m
LEFT JOIN `wm_users` u ON (u.id = m.id_recipient OR u.id = m.id_sender) AND u.`client_id` = ".$instance_id."
LEFT JOIN tms_device d ON (d.id = m.id_recipient OR u.id = m.id_sender) AND d.`Client_id` = ".$instance_id."
WHERE m.deleted = 0 GROUP BY m.`id`;";
	    if ($stmt = $db->prepare($query))
	    {
            $stmt->execute();
            $stmt->bind_result($id, $message, $time, $RID, $SID, $id_recipient, $id_sender);
            while ($stmt->fetch()) 
            {
              $Model [$i]= 
                array('id'=>$id,
                      'message'=>$message,
					  'id_sender'=>$id_sender,
					  'id_recipient'=>$id_recipient,
					  'time'=>$time,
                      );            
                $i++;
            } 
            $stmt->close();
            $db->close();
	    }
   		echo'{rows:'.json_encode($Model).'}';   
    }
	
	if ($_REQUEST['func']=='showUser')
    {
        $i=0;
        $query = "(SELECT d.`ID`,c.`car_name`
FROM `tms_device` d
LEFT JOIN `wm_car_info` c ON c.`imei` = d.`Login`
WHERE d.DeletedRecord = 0 AND d.`Client_id` = ".$instance_id."
ORDER BY c.`car_name` ASC)
UNION ALL
(SELECT u.id,u.`login` FROM `wm_users` u
WHERE u.`client_id` = ".$instance_id."
ORDER BY u.`login` ASC)";
	    if ($stmt = $db->prepare($query))
	    {
            $stmt->execute();
            $stmt->bind_result($id, $name);
            while ($stmt->fetch()) 
            {
				$Model[]=array(
                        'id'=>$id,
                        'name'=>addslashes($name)
				);            
                $i++;
            } 
            $stmt->close();
            $db->close();
	    }
   		echo'{rows:'.json_encode($Model).'}';   
    }
	
	
if (isset($_REQUEST['addedit']))
{
	$message = $_REQUEST['message'];
	$id_recipient = $_REQUEST['id_recipient'];
	$id_sender = $user_id;
	$time = date('Y-m-d H:i:s');
	$last_id = false;
	
	$query = "INSERT INTO `wm_message` (`message`,`id_sender`,`id_recipient`,`time`) VALUES ('".$message."',".$id_sender.",".$id_recipient.",'".$time."');";
	if($stmt = $db->prepare($query)){
	if($stmt->execute()){
		$last_id = $db->insert_id;
		$stmt->close();
	}else{ echo json_encode(array('success'=>false, 'message'=>$last_id .' '. $query)); exit; }
	}else{ echo json_encode(array('success'=>false, 'message'=>$last_id .' '. $query)); exit; }
	
	$db->close();
	
	echo json_encode(array('success'=>true, 'message'=>$last_id));
		
	exit;
}


if( $_REQUEST['func'] == 'delete' ){
	$arrayId = $_REQUEST['id'];
	$stringId = implode(",",$arrayId);
	
	$query = "UPDATE wm_message SET deleted = 1 WHERE id IN (".$stringId.")";
	if( $stmt = $db->prepare($query) ){
	if( $stmt->execute() ){
	$stmt->close();
		echo json_encode(array('success'=>true, 'message'=>''));
	}else{ echo json_encode(array('success'=>false, 'message'=>$db->errno . ' ' . $db->error)); }
	}else{ echo json_encode(array('success'=>false, 'message'=>$db->errno . ' ' . $db->error)); }
	
	$db->close();
	exit;
}
 
        
        

?>