<?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;
    }
    $db1 = new mysqli ($DB_HOST,$DB_USER,$DB_PASS,$DB_NAME);
    $db1->query("SET CHARSET SET utf8");
    $db1->query("SET NAMES 'utf8'");
    if (mysqli_connect_errno()) {
        echo "Error connecting to DB";
        exit;
    }
    
	
	
	$data = $_REQUEST['data'];
    $data = stripslashes($data);
	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchroAndroid <> '.$data );
	
	$arraydata = (array)json_decode($data);
    $timeLastDownload  = $arraydata['lastSynch'];
    $name_master = $arraydata['name_master'];
	$id_user = $arraydata['id'];
	$instance_id = $arraydata['instance_id'];

    if 	(count($arraydata)==0)
    {
        $arr_data=explode('?',$data);
    }   
    
	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchroAndroid <> '.$arraydata['func'] );
	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchroAndroid arraydata <> '.$arr_data[0] );

//----- OUT -----

	
// ---------------------------------------- trip ---------------------------------------------------------------

	if ($arraydata['func']=='trip')
    {
		$i=0;
		$startLine = $arraydata["startLine"];
		$endLine = $startLine + 999;
		$Model = array();

		$query = "SELECT `id`,`Name`,`Distance`,`Time`,`StartTime`,`name_master`,`trip_route` FROM `toir_trip` WHERE `name_master`=".$id_user." AND `StartTime`>= '".$timeLastDownload."' ORDER BY `id` ASC LIMIT ".$startLine.",".$endLine.";";
		if ($stmt = $db->prepare($query))
        {
            $stmt->execute();
            $stmt->bind_result($id_trip,$name,$distance,$time,$starttime,$name_master,$trip_route);
            while($stmt->fetch()){
				$Model[$i]=array(
					'id_trip'=>iconv("windows-1251", "UTF-8", $id_trip),
					'name'=>$name,
					'distance'=>iconv("windows-1251", "UTF-8", $distance),
					'time'=>iconv("windows-1251", "UTF-8", $time),
					'starttime'=>$starttime,
					'name_master'=>iconv("windows-1251", "UTF-8", $name_master),
					'trip_route'=>$trip_route
                );
				$i++;
            } 
            $stmt->close();
            $db->close();                                                                                                                                         
        }else{
			$arrayEndModel = array('EndModel'=>'true');
			array_push($Model,$arrayEndModel);
			echo json_encode($Model);
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchroAndroid <> '.$query.' <> '.json_encode($Model) );
			exit;
		}
        
		if ($i < 999)
		{
		$arrayEndModel = array('EndModel'=>'true');
		array_push($Model,$arrayEndModel);
		}
		
		echo json_encode($Model);
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchroAndroid <> '.$query.' <> '.json_encode($Model) );
		$db->close();
		exit;
	}
	
// ---------------------------------------- request ---------------------------------------------------------------

	if ($arraydata['func']=='request')
    {
		$i=0;
		$startLine = $arraydata["startLine"];
		$endLine = $startLine + 999;
		$Model = array();
		
/*		$query = "SELECT r.`id_request`,  t.name_job, r.`workshop`,  c.`client`, o.`name`, r.`region`,  r.`city`, r.`address`, r.`contact_number`, r.`contact_name`, r.`id_code_PSD`, 
  r.`contract_number`, r.`note`, r.`type_TT`, r.`sales_contact_number`, r.`time_change`, r.`time_execut`, r.`status`, r.`name_master`, r.`id_equipment` FROM ".$DB_PREFIX."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 `equipment` e ON e.`id_equipment`=r.`id_equipment`
  INNER JOIN ".$DB_PREFIX."outlets o ON o.`id_outlet`=r.`outlet_id` WHERE r.`name_master`=".$id_user." AND r.`time_execut` >= '".$timeLastDownload."' ORDER BY r.`id_request` ASC LIMIT ".$startLine.",".$endLine.";";
*/
  //LEFT JOIN ".$DB_PREFIX."users u ON u.id=r.`name_master`
	
$query = "SELECT 
r.`id_request`,  tj.name_job, r.`workshop`,  c.`client`, r.`outlet_id`, r.`region`,  r.`city`, r.`address`, r.`contact_number`, r.`contact_name`, r.`id_code_PSD`, 
r.`contract_number`, r.`note`, r.`type_TT`, r.`sales_contact_number`, r.`time_change`, r.`time_execut`, r.`status`, r.`name_master`, r.`id_equipment`,r.`place`,t.`id`
FROM `toir_trip` t
INNER JOIN `toir_trip_request` tr ON t.`id` = tr.`trip_id`
INNER JOIN `toir_request` r ON r.`id_request` = tr.`request_id`
INNER JOIN  `type_job` tj   ON tj.id_type_job= r.`id_type_job`
INNER JOIN `client` c ON c.id_client = r.`client_id`
WHERE t.`name_master`=".$id_user." AND t.`StartTime`>= '".$timeLastDownload."' GROUP BY r.`id_request` ASC LIMIT ".$startLine.",".$endLine.";";
	
	
		if ($stmt = $db->prepare($query))
        {
            $stmt->execute();
            $stmt->bind_result($id_request,$name_job,$workshop,$client,$name,$region,$city,$address,$contact_number,$contact_name,$id_code_PSD,$contract_number,$note,$type_TT,$sales_contact_number,$time_change,$time_execut,$status,$name_master,$id_equipment,$place,$id_trip);
            while($stmt->fetch()){
                $Model[$i]=array(
					'id_request'=>iconv("windows-1251", "UTF-8", $id_request),
					//'id_type_job'=>iconv("windows-1251", "UTF-8", $name_job),
					'id_type_job'=>$name_job,
					'workshop'=>iconv("windows-1251", "UTF-8", $workshop),
					//'client'=>iconv("windows-1251", "UTF-8", $client),
					'client'=>$client,
					'name_TT'=>iconv("windows-1251", "UTF-8", $name),
					//'name_TT'=>$name,
					//'region'=>iconv("windows-1251", "UTF-8", $region),
					'region'=>$region,
					//'city'=>iconv("windows-1251", "UTF-8", $city),
					'city'=>$city,
					//'address'=>iconv("windows-1251", "UTF-8", $address),
					'address'=>$address,
					'contact_number'=>iconv("windows-1251", "UTF-8", $contact_number),
					//'contact_name'=>iconv("windows-1251", "UTF-8", $contact_name),
					'contact_name'=>$contact_name,
					'id_code_PSD'=>iconv("windows-1251", "UTF-8", $id_code_PSD),
					'contract_number'=>iconv("windows-1251", "UTF-8", $contract_number),
					//'note'=>iconv("windows-1251", "UTF-8", $note),
					'note'=>$note,
					//'type_TT'=>iconv("windows-1251", "UTF-8", $type_TT),
					'type_TT'=>$type_TT,
					'sales_contact_number'=>iconv("windows-1251", "UTF-8", $sales_contact_number),
					'time_change'=>iconv("windows-1251", "UTF-8", $time_change),
					'time_execut'=>iconv("windows-1251", "UTF-8", $time_execut),
					'status'=>iconv("windows-1251", "UTF-8", $status),
					'name_master'=>iconv("windows-1251", "UTF-8", $name_master),
					'id_equipment'=>iconv("windows-1251", "UTF-8", $id_equipment),
					//+++
					'place'=>iconv("windows-1251", "UTF-8", $place),
					//+++
					'id_trip'=>iconv("windows-1251", "UTF-8", $id_trip)
                );
				$i++;
            } 
            $stmt->close();
            $db->close();                                                                                                                                         
        }else{
			$arrayEndModel = array('EndModel'=>'true');
			array_push($Model,$arrayEndModel);
			echo json_encode($Model);
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchroAndroid <> '.$query.' <> '.json_encode($Model) );
			exit;
		}
        
		if ($i < 999)
		{
		$arrayEndModel = array('EndModel'=>'true');
		array_push($Model,$arrayEndModel);
		}
		
		echo json_encode($Model);
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchroAndroid <> '.$query.' <> '.json_encode($Model) );
		$db->close();
		exit;
	}
	
	
	
  // ---------------------------------------- equipment ---------------------------------------------------------------

	if ($arraydata['func']=='equipment')
    {
		$i=0;
		$startLine = $arraydata["startLine"];
		$endLine = $startLine + 999;
		$Model = array();
		
		/*$query = "SELECT e.* FROM ".$DB_PREFIX."request r
  INNER JOIN `equipment` e ON e.`id_equipment`=r.`id_equipment`
  WHERE r.`name_master`=".$id_user." AND r.`time_execut` >= '".$timeLastDownload."' GROUP BY r.`id_equipment` ASC LIMIT ".$startLine.",".$endLine.";";
		*/
		
		
$query = "SELECT e.`id_equipment`,e.`maker`,e.`inventory_number`,e.`actual_number`,e.`serial_number`,e.`year_constr`,e.`logo`,e.`model`,e.`actual_model`,e.`type`,e.`date_end_warranty`,e.`planned_date_service`,e.`actual_date_last_service`,e.`master_last_service`,e.`date_last_service`,e.`count`,e.`date_count` FROM `toir_trip` t
INNER JOIN `toir_trip_request` tr ON t.`id` = tr.`trip_id`
INNER JOIN `toir_request` r ON r.`id_request` = tr.`request_id`  
INNER JOIN `equipment` e ON e.`id_equipment`=r.`id_equipment`
WHERE t.`name_master`=".$id_user." AND t.`StartTime` >= '".$timeLastDownload."'
GROUP BY e.`id_equipment` ASC LIMIT ".$startLine.",".$endLine.";";
		
		
		if ($stmt = $db->prepare($query))
        {
            $stmt->execute();
            $stmt->bind_result($id_equipment,$maker,$inventory_number,$actual_number,$serial_number,$year_constr,$logo,$model,$actual_model,$type,$date_end_warranty,$planned_date_service,$actual_date_last_service,$master_last_service,$date_last_service,$count,$date_count);
            while($stmt->fetch()){
                $Model[$i]=array(
					'id_equipment'=>iconv("windows-1251", "UTF-8", $id_equipment),
					'maker'=>$maker,
					'inventory_number'=>$inventory_number,
					'actual_number'=>$actual_number,
					'serial_number'=>$serial_number,
					'year_constr'=>iconv("windows-1251", "UTF-8", $year_constr),
					'logo'=>$logo,
					'model'=>$model,
					'actual_model'=>$actual_model,
					'type'=>$type,
					'date_end_warranty'=>$date_end_warranty,
					'planned_date_service'=>$planned_date_service,
					'actual_date_last_service'=>$actual_date_last_service,
					'master_last_service'=>$master_last_service,
					'date_last_service'=>$date_last_service,
					'count'=>$count
					//'count'=>iconv("windows-1251", "UTF-8", $count)
                );
				$i++;
            } 
            $stmt->close();
            $db->close();                                                                                                                                         
        }else{
			$arrayEndModel = array('EndModel'=>'true');
			array_push($Model,$arrayEndModel);
			echo json_encode($Model);
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchroAndroid <> '.$query.' <> '.json_encode($Model) );
			exit;
		}
        
		if ($i < 999)
		{
		$arrayEndModel = array('EndModel'=>'true');
		array_push($Model,$arrayEndModel);
		}
		
		echo json_encode($Model);
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchroAndroid <> '.$query.' <> '.json_encode($Model) );
		$db->close();
		exit;
	}

	
// ---------------------------------------- outlets ---------------------------------------------------------------	
	if ($arraydata['func']=='outlets')
    {
		$i=0;
		$startLine = $arraydata["startLine"];
		$endLine = $startLine + 999;
		$Model = array();
		
/*		$query = "SELECT o.* FROM toir_request r
INNER JOIN toir_outlets o ON o.`id_outlet`=r.`outlet_id` WHERE r.`name_master`=".$id_user." AND r.`time_execut` >= '".$timeLastDownload."' GROUP BY o.`id_outlet` ASC LIMIT ".$startLine.",".$endLine.";";
*/

$query = "SELECT o.`id_outlet`,o.`client_id`,o.`name`,o.`region`,o.`city`,o.`address`,o.`contact_number`,o.`contact_name`,o.`id_code_PSD`,o.`contract_number`,o.`note`,o.`type_TT`,o.`sales_contact_number`,o.`geoX`,o.`geoY`,o.`model` FROM `toir_trip` t
INNER JOIN `toir_trip_request` tr ON t.`id` = tr.`trip_id`
INNER JOIN `toir_request` r ON r.`id_request` = tr.`request_id`  
INNER JOIN toir_outlets o ON o.`id_outlet`=r.`outlet_id` 
WHERE t.`name_master`=".$id_user." AND t.`StartTime` >= '".$timeLastDownload."'
GROUP BY o.`id_outlet` ASC LIMIT ".$startLine.",".$endLine.";";
		
		if ($stmt = $db->prepare($query))
        {
            $stmt->execute();
            $stmt->bind_result($id_outlet,$client_id,$name,$region,$city,$address,$contact_number,$contact_name,$id_code_PSD,$contract_number,$note,$type_TT,$sales_contact_number,$geoX,$geoY,$model);
            while($stmt->fetch()){
                $Model[$i]=array(
					'id_outlet'=>iconv("windows-1251", "UTF-8", $id_outlet),
					'name'=>$name,
					'region'=>$region,
					'city'=>$city,
					'address'=>$address,
					'contact_number'=>$contact_number,
					'contact_name'=>$contact_name,
					'id_code_PSD'=>$id_code_PSD,
					'contract_number'=>$contract_number,
					'note'=>$note,
					'type_TT'=>$type_TT,
					'sales_contact_number'=>$sales_contact_number,
					'geoX'=>$geoX,
					'geoY'=>$geoY,
					'model'=>$model
                );
				$i++;
            } 
            $stmt->close();
            $db->close();                                                                                                                                         
        }else{
			$arrayEndModel = array('EndModel'=>'true');
			array_push($Model,$arrayEndModel);
			echo json_encode($Model);
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchroAndroid <> '.$query.' <> '.json_encode($Model) );
			exit;
		}
        
		if ($i < 999)
		{
		$arrayEndModel = array('EndModel'=>'true');
		array_push($Model,$arrayEndModel);
		}
		
		echo json_encode($Model);
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchroAndroid <> '.$query.' <> '.json_encode($Model) );
		$db->close();
		exit;
	}
//--------------------------------------- spares ----------------------------------------------

	if ($arraydata['func']=='spares')
    {
		$i=0;
		$startLine = $arraydata["startLine"];
		$endLine = $startLine + 999;
		$Model = array();
		
		$query = "SELECT `users_id`,`spares_group`,`spare`,`aticle`,`count`,spareRef FROM ".$DB_PREFIX."spares WHERE users_id=".$id_user." ORDER BY `aticle` ASC LIMIT ".$startLine.",".$endLine.";";
		if ($stmt = $db->prepare($query))
        {
            $stmt->execute();
            $stmt->bind_result($users_id,$spares_group,$spare,$aticle,$count,$spareRef);
            while($stmt->fetch()){
                $Model[$i]=array(
					'users_id'=>iconv("windows-1251", "UTF-8", $users_id),
					//'spares_group'=>iconv("windows-1251", "UTF-8", $spares_group),
					//'spare'=>iconv("windows-1251", "UTF-8", $spare),
					//'aticle'=>iconv("windows-1251", "UTF-8", $aticle),
					'spares_group'=>$spares_group,
					'spare'=>$spare,
					'aticle'=>$aticle,
					'count'=>iconv("windows-1251", "UTF-8", $count),
					'spareRef'=>$spareRef
                );
				$i++;
            } 
            $stmt->close();
            $db->close();                                                                                                                                         
        }else{
			$arrayEndModel = array('EndModel'=>'true');
			array_push($Model,$arrayEndModel);
			echo json_encode($Model);
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchroAndroid <> '.$query.' <> '.json_encode($Model) );
			exit;
		}
        
		if ($i < 999)
		{
		$arrayEndModel = array('EndModel'=>'true');
		array_push($Model,$arrayEndModel);
		}
		
		echo json_encode($Model);
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchroAndroid <> '.$query.' <> '.json_encode($Model) );
		$db->close();
		exit;
	}
//--------------------------------------- users ----------------------------------------------

	if ($arraydata['func']=='users')
    {
		$i=0;
		$startLine = $arraydata["startLine"];
		$endLine = $startLine + 999;
		$Model = array();
		
		$query = "SELECT `id`,`name`,`password`,`id_role` FROM ".$DB_PREFIX."users WHERE `id` NOT IN(".$id_user.") AND `instance_id` = ".$instance_id." ORDER BY `id` ASC LIMIT ".$startLine.",".$endLine.";";
		if ($stmt = $db->prepare($query))
        {
            $stmt->execute();
            $stmt->bind_result($id,$name,$password,$id_role);
            while($stmt->fetch()){
                $Model[$i]=array(
					'id_user'=>iconv("windows-1251", "UTF-8", $id),
					'login'=>iconv("windows-1251", "UTF-8", $name),
					'password'=>iconv("windows-1251", "UTF-8", $password),
					'role'=>iconv("windows-1251", "UTF-8", $id_role)
                );
				$i++;
            } 
            $stmt->close();
            $db->close();                                                                                                                                         
        }else{
			$arrayEndModel = array('EndModel'=>'true');
			array_push($Model,$arrayEndModel);
			echo json_encode($Model);
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchroAndroid <> '.$query.' <> '.json_encode($Model) );
			exit;
		}
        
		if ($i < 999)
		{
		$arrayEndModel = array('EndModel'=>'true');
		array_push($Model,$arrayEndModel);
		}
		
		echo json_encode($Model);
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchroAndroid <> '.$query.' <> '.json_encode($Model) );
		$db->close();
		exit;
	}

// ---------------------------------------- messages ---------------------------------------------------------------	
	
	if ($arraydata['func']=='message')
    {
		$i=0;
		$startLine = $arraydata["startLine"];
		$endLine = $startLine + 999;
		$Model = array();
		
		
		$query = "SELECT whom_message,from_message,topic,message,status,time_message FROM message WHERE status='forSend' AND `time_message` >= '".$timeLastDownload."' ORDER BY `id_message` ASC LIMIT ".$startLine.",".$endLine.";";
		if ($stmt = $db->prepare($query))
        {
            $stmt->execute();
            $stmt->bind_result($whom_message,$from_message,$topic,$message,$status,$time_message);
            while($stmt->fetch()){
                $Model[$i]=array(
					'whom_message'=>$whom_message,
                    'from_message'=>$from_message,
                    'topic'=>$topic,
                    'message'=>$message,
                    'status'=>$status,
                    'time_message'=>$time_message
                );
				$i++;
            } 
            $stmt->close();
            $db->close();                                                                                                                                         
        }else{
			$arrayEndModel = array('EndModel'=>'true');
			array_push($Model,$arrayEndModel);
			echo json_encode($Model);
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchroAndroid <> '.$query.' <> '.json_encode($Model) );
			exit;
		}
        
		if ($i < 999)
		{
		$arrayEndModel = array('EndModel'=>'true');
		array_push($Model,$arrayEndModel);
		}
		
		echo json_encode($Model);
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchroAndroid <> '.$query.' <> '.json_encode($Model) );
		$db->close();
		exit;
	}

	
	// ---------------------------------------- result_job ---------------------------------------------------------------	
	
	if ($arraydata['func']=='result_job')
    {
		$i=0;
		$startLine = $arraydata["startLine"];
		$endLine = $startLine + 999;
		$Model = array();
		
		
		$query = "SELECT `id_result_job`,`name_result_job` FROM `result_job` WHERE `instance_id`=".$instance_id." ORDER BY `id_result_job` ASC LIMIT ".$startLine.",".$endLine.";";
		if ($stmt = $db->prepare($query))
        {
            $stmt->execute();
            $stmt->bind_result($id_result_job,$name_result_job);
            while($stmt->fetch()){
                $Model[$i]=array(
					'id_result_job'=>iconv("windows-1251", "UTF-8", $id_result_job),
					'name_result_job'=>$name_result_job
                );
				$i++;
            } 
            $stmt->close();
            $db->close();                                                                                                                                         
        }else{
			$arrayEndModel = array('EndModel'=>'true');
			array_push($Model,$arrayEndModel);
			echo json_encode($Model);
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchroAndroid <> '.$query.' <> '.json_encode($Model) );
			exit;
		}
        
		if ($i < 999)
		{
		$arrayEndModel = array('EndModel'=>'true');
		array_push($Model,$arrayEndModel);
		}
		
		echo json_encode($Model);
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchroAndroid <> '.$query.' <> '.json_encode($Model) );
		$db->close();
		exit;
	}

	// ----------------------------------------    ---------------------------------------------------------------	
	
	
	
	
	
	// ---------------------------------------- result_history ---------------------------------------------------------------	
//+++	
	if ($arraydata['func']=='result_history')
    {
		$i=0;
		$startLine = $arraydata["startLine"];
		$endLine = $startLine + 999;
		$Model = array();
		
		
		/*$query = "SELECT u.`name`,r.`city`,r.`address`,DATE(r.`time_execut`),tj.`name_job`,ji.`comment`, ji.`possible_fault`,ji.`conclution_master`,r.`id_equipment` FROM `toir_request` r
INNER JOIN `toir_job_information` ji ON r.`id_request` = ji.`id_request`
INNER JOIN  `type_job` tj   ON tj.id_type_job = r.`id_type_job`
INNER JOIN  `toir_users` u   ON u.`id` = r.`name_master`
WHERE r.`id_equipment` IN (

SELECT e.`id_equipment` FROM `toir_trip` t
INNER JOIN `toir_trip_request` tr ON t.`id` = tr.`trip_id`
INNER JOIN `toir_request` r ON r.`id_request` = tr.`request_id`  
INNER JOIN `equipment` e ON e.`id_equipment`=r.`id_equipment`
WHERE t.`name_master` = ".$id_user." AND t.`StartTime`>= '".$timeLastDownload."'

) ORDER BY r.`time_beginning_work` DESC LIMIT ".$startLine.",".$endLine.";";
*/

$query = "SELECT r.`id_request` AS IDR,
u.`name`,r.region,r.`city`,r.`address`,DATE(r.`time_execut`),tj.`name_job`,ji.`comment`, ji.`possible_fault`,ji.`conclution_master`,r.`id_equipment`,
rj.`name_result_job`, c.`client`, (SELECT GROUP_CONCAT(CONCAT(`name`, ' (', `count`, ')') SEPARATOR ', ') FROM `toir_used_spares` WHERE `request_id` = IDR)
FROM `toir_request` r
INNER JOIN `toir_job_information` ji ON r.`id_request` = ji.`id_request`

INNER JOIN `result_job` rj ON rj.`id_result_job` = ji.`id_result_job`
INNER JOIN `client` c ON c.`id_client` = r.`client_id`


INNER JOIN  `type_job` tj   ON tj.id_type_job = r.`id_type_job`
INNER JOIN  `toir_users` u   ON u.`id` = r.`name_master`
WHERE r.`id_equipment` IN (

SELECT e.`id_equipment` FROM `toir_trip` t
INNER JOIN `toir_trip_request` tr ON t.`id` = tr.`trip_id`
INNER JOIN `toir_request` r ON r.`id_request` = tr.`request_id`  
INNER JOIN `equipment` e ON e.`id_equipment`=r.`id_equipment`
WHERE t.`name_master` = ".$id_user."
) ORDER BY r.`time_beginning_work` DESC LIMIT ".$startLine.",".$endLine.";";

		if ($stmt = $db->prepare($query))
        {
            $stmt->execute();
            $stmt->bind_result($id_request,$name,$region,$city,$address,$time_execut,$name_job,$comment,$possible_fault,$conclution_master,$id_equipment,$name_result_job,$client,$spares);
            while($stmt->fetch()){
                $Model[$i]=array(
					//'id_result_job'=>iconv("windows-1251", "UTF-8", $id_result_job),
					'id_request'=>iconv("windows-1251", "UTF-8", $id_request),
					'name'=>$name,
					'address'=>$region.' '.$city.', '.$address,
					'time_execut'=>$time_execut,
					'name_job'=>$name_job,
					'comment'=>$comment,
					'possible_fault'=>$possible_fault,
					'conclution_master'=>$conclution_master,
					'id_equipment'=>iconv("windows-1251", "UTF-8", $id_equipment),
					'name_result_job'=>$name_result_job,
					'client'=>$client,
					'spares'=>$spares
                );
				$i++;
            } 
            $stmt->close();
            $db->close();                                                                                                                                         
        }else{
			$arrayEndModel = array('EndModel'=>'true');
			array_push($Model,$arrayEndModel);
			echo json_encode($Model);
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchroAndroid <> '.$query.' <> '.json_encode($Model) );
			exit;
		}
        
		if ($i < 999)
		{
		$arrayEndModel = array('EndModel'=>'true');
		array_push($Model,$arrayEndModel);
		}
		
		echo json_encode($Model);
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchroAndroid <> '.$query.' <> '.json_encode($Model) );
		$db->close();
		exit;
	}
	
//+++	
	
	
	
	

//----- IN -----
	
	
// ---------------------------------------- get sendFoto ---------------------------------------------------------------
	if ($arr_data[0]=='sendFoto')            //http://localhost/Lesha/MobiTORServer/scripts/synchroAndroid.php?$arr_data[0]=sendFoto&$arr_data[1]=['rdghkherskhjeriohjeriohjeroihjeroihjrioehjerhjeriohjerio','aksmvcnvkdfnvkjdfnvjdfnvjkdfnzkjvnzdf'];8  
    {//
        $sendFotoData = $arr_data[1];        
        $sendFotoDataArray = explode(';;;;;', $sendFotoData);
        $fotoString = $sendFotoDataArray[0];          
     
        
        //$handle = fopen("d:/Photo/temp.png", 'a');    //открыть файл для записи, курсор в конец
        //$handle = fopen("C:/htdocs/monit2_task_ne_test/app/ExtJsGallery/images/temp.png", 'a');    //открыть файл для записи, курсор в конец
        $handle = fopen($IMAGE_PATH2."temp.png", 'a');
		fputs($handle, $fotoString);            // добавить строку в файл
        fclose($handle);
        
        $namePhoto = 'photo.png';
        
        if ($sendFotoDataArray[2]=="end")
        {
          //$handle = fopen("C:/htdocs/monit2_task_ne_test/app/ExtJsGallery/images/temp.png", 'r');
          $handle = fopen($IMAGE_PATH2."temp.png", 'r');
		  //$stringFile64 = file_get_contents("C:/htdocs/monit2_task_ne_test/app/ExtJsGallery/images/temp.png");
		  $stringFile64 = file_get_contents($IMAGE_PATH2."temp.png");
          fclose($handle);
                            // удалить временный файл
          //unlink("C:/htdocs/monit2_task_ne_test/app/ExtJsGallery/images/temp.png");// удалить временный файл
		  unlink($IMAGE_PATH2."temp.png");
          $stringFile64 = str_replace(" ","+",$stringFile64);       // \r\n
          $stringFile64 = str_replace("*****","\r",$stringFile64);       // \r\n
         
          
          $pathArray = explode("/",$sendFotoDataArray[1]);
          $namePhoto = $pathArray[4];
          //$handle = fopen("C:/htdocs/monit2_task_ne_test/app/ExtJsGallery/images/$namePhoto", 'w');
		  $handle = fopen($IMAGE_PATH2.$namePhoto, 'w');
          $stringFile = base64_decode($stringFile64);
          fwrite($handle,$stringFile);
          fclose($handle);
          //echo 'trueDelete';
        }
        //if (is_readable("C:/htdocs/monit2_task_ne_test/app/ExtJsGallery/images/$namePhoto")){echo 'delete';}
		if (is_readable($IMAGE_PATH2.$namePhoto)){echo 'delete';}
        else {echo 'true';}
        
        
        //$query = "INSERT INTO location (name,latitude,longitude,time) VALUES ('".$name."','".$latitude."','".$longitude."','".$time."')";
        //$stmt = $db->prepare($query);
        //$stmt->execute();
        //echo $fotoString64;
        
    }
	
// ---------------------------------------- get messages ---------------------------------------------------------------
	if ($arr_data[0]=='getMessage')  
	{
        $stringMessage = $arr_data[1];        
        $arrayMessage = explode(';', $stringMessage);
        
        $whom_message = $arrayMessage[0];
        $from_message = $arrayMessage[1];
        $topic = $arrayMessage[2];
        $message = $arrayMessage[3];
        $query = "INSERT INTO message (whom_message,from_message,topic,message,status) VALUES ('".$whom_message."','".$from_message."','".$topic."','".$message."','new')";
        if($stmt = $db->prepare($query)){
        $stmt->execute();
        echo 'true';
		}else{
		echo 'false';
		}
	}
	
// ---------------- location ------------------------------
    if ($arr_data[0]=='location')               //http://localhost/Lesha/MobiTORServer/scripts/synchroAndroid.php?$arr_data[0]=location&$arr_data[1]=x:50,450659;y:30,522938&$arr_data[2]=l
    {
        $stringLocation = $arr_data[1];
		//$stringLocation = stripslashes($arr_data[1]);
        $arrayLocation = explode(';', $stringLocation);
        //list($latitude) = sscanf($arrayLocation[0], "x:%s");
        //list($longitude) = sscanf($arrayLocation[1], "y:%s");
        $latitude = $arrayLocation[0];
        $longitude = $arrayLocation[1];
        $name = $arrayLocation[2];
        $time = $arrayLocation[3];
        
        //$query = "INSERT INTO location (name,latitude,longitude,time) VALUES ('".$name."','".$latitude."','".$longitude."','".$time."')";
		$query = "INSERT INTO ".$DB_PREFIX."location (user_id,latitude,longitude,time) VALUES ('".$name."','".$latitude."','".$longitude."','".$time."')";
        writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> location query <> '.$query );
		$stmt = $db->prepare($query);
        $stmt->execute();
        echo 'true';
        
    }

	//---------------- upload_request ----------------
    if ($arr_data[0]=='upload_request')
    {
        $result = stripslashes($arr_data[2]);
		$dateget = stripslashes($arr_data[1]);
		
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> upload_request <> '.$result );
        
		$arrayDataDecode = (array)json_decode($result, true);
        $res = count($arrayDataDecode);
        $i=0;
        for ($i;$i<$res;$i++)
        {
			//writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> upload_request id_request <> '.$arrayDataDecode[$i][id_request] );
			
			$sec = ( strtotime($arrayDataDecode[$i]['endworkdur']) - strtotime($arrayDataDecode[$i]['startworkdur']) );
			$fwd = floor(($sec%3600)/60);
			$query = "UPDATE toir_request SET status=".$arrayDataDecode[$i]['status'].", `fact_work_duration`=".$fwd.", `mobile_time_change`='".$arrayDataDecode[$i]['time_change']."', `mobile_time_getdata`='".$dateget."' WHERE id_request=".$arrayDataDecode[$i]['id_request']."";
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> upload_request query <> '.$query );
			if( $stmt = $db->prepare($query) ){
			$stmt->execute();
			$stmt->close();
			}
		
		  
        }
    }
	//---------------- upload_equipment ----------------
	if ($arr_data[0]=='upload_equipment')
    {
        $result = stripslashes($arr_data[1]);
		
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> upload_equipment <> '.$result );
        
		$arrayDataDecode = (array)json_decode($result, true);
        $res = count($arrayDataDecode);
        $i=0;
        for ($i;$i<$res;$i++)
        {
			//writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> upload_request id_request <> '.$arrayDataDecode[$i][id_request] );
			//$query = "UPDATE equipment SET count=".$arrayDataDecode[$i]['count'].",actual_number='".$arrayDataDecode[$i]['actual_number']."',actual_model='".$arrayDataDecode[$i]['actual_model']."',date_count='".$arrayDataDecode[$i]['date_count']."' WHERE id_equipment=".$arrayDataDecode[$i]['id_equipment']."";
			$query = "UPDATE equipment SET count='".$arrayDataDecode[$i]['count']."',actual_number='".$arrayDataDecode[$i]['actual_number']."',actual_model='".$arrayDataDecode[$i]['actual_model']."',date_count='".$arrayDataDecode[$i]['date_count']."' WHERE id_equipment=".$arrayDataDecode[$i]['id_equipment']."";
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> upload_equipment query <> '.$query );
			if( $stmt = $db->prepare($query) ){
			$stmt->execute();
			$stmt->close();
			}
        }
    }
	
	//---------------- upload_confirmation ----------------
	if ($arr_data[0]=='upload_confirmation')
    {
        $result = stripslashes($arr_data[1]);
        writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> upload_confirmation <> '.$result );
		$arrayDataDecode = (array)json_decode($result, true);
        $res = count($arrayDataDecode);
        $i=0;
        for ($i;$i<$res;$i++)
        {
			
			$query = "SELECT id_request FROM confirmation WHERE id_request=".$arrayDataDecode[$i]['id_request']."";
			$stmt = $db->prepare($query);
			$stmt->execute();
			$stmt->store_result();
			
			$sc = str_replace('/data/data/com.innotech.toir/', "", $arrayDataDecode[$i]['signature_client']);
			$sm = str_replace('/data/data/com.innotech.toir/', "", $arrayDataDecode[$i]['signature_master']);
			$ft = str_replace('/data/data/com.innotech.toir/', "", $arrayDataDecode[$i]['foto']);
			
			if ($stmt->num_rows)
			{
			$query = "UPDATE confirmation SET name_client='".$arrayDataDecode[$i]['name_client']."',post_client='".$arrayDataDecode[$i]['post_client']."',signature_client='".$sc."',signature_master='".$sm."',foto='".$ft."' WHERE id_request=".$arrayDataDecode[$i]['id_request']."";
			}else{
			$query = "INSERT INTO confirmation (id_request,name_client,post_client,signature_client,signature_master,foto) VALUES (".$arrayDataDecode[$i]['id_request'].",'".$arrayDataDecode[$i]['name_client']."','".$arrayDataDecode[$i]['post_client']."','".$sc."','".$sm."','".$ft."')";
			}
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> upload_confirmation query <> '.$query );
			if( $stmt = $db->prepare($query) ){
			$stmt->execute();
			$stmt->close();
			}
        }
    }
	
	
	
	//---------------- upload_confirmation ----------------
	if ($arr_data[0]=='upload_job_information')
    {
        $result = stripslashes($arr_data[1]);
        writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> upload_job_information <> '.$result );
		$arrayDataDecode = (array)json_decode($result, true);
        $res = count($arrayDataDecode);
        $i=0;
        for ($i;$i<$res;$i++)
        {
			
			//$query = "SELECT id_request FROM job_information WHERE id_request=".$arrayDataDecode[$i]['id_request']."";
			$query = "SELECT id_request FROM ".$DB_PREFIX."job_information WHERE id_request=".$arrayDataDecode[$i]['id_request']."";
			$stmt = $db->prepare($query);
			$stmt->execute();
			$stmt->store_result();
			if ($stmt->num_rows)
			{
            //$query = "UPDATE job_information SET id_result_job='".$arrayDataDecode[$i][id_result_job]."',comment='".$arrayDataDecode[$i][comment]."',possible_fault='".$arrayDataDecode[$i][possible_fault]."',conclution_master='".$arrayDataDecode[$i][conclution_master]."',id_preventive='".$arrayDataDecode[$i][id_preventive]."' WHERE id_request=".$arrayDataDecode[$i][id_request]."";
			$query = "UPDATE ".$DB_PREFIX."job_information SET id_result_job='".$arrayDataDecode[$i][id_result_job]."',comment='".$arrayDataDecode[$i][comment]."',possible_fault='".$arrayDataDecode[$i][possible_fault]."',conclution_master='".$arrayDataDecode[$i][conclution_master]."' WHERE id_request=".$arrayDataDecode[$i][id_request]."";
			}
			else
			{
            //$query = "INSERT INTO job_information (id_request,id_result_job,comment,possible_fault,conclution_master,id_preventive) VALUES (".$arrayDataDecode[$i][id_request].",'".$arrayDataDecode[$i][id_result_job]."','".$arrayDataDecode[$i][comment]."','".$arrayDataDecode[$i][possible_fault]."','".$arrayDataDecode[$i][conclution_master]."','".$arrayDataDecode[$i][id_preventive]."')";
			$query = "INSERT INTO ".$DB_PREFIX."job_information (id_request,id_result_job,comment,possible_fault,conclution_master) VALUES (".$arrayDataDecode[$i][id_request].",'".$arrayDataDecode[$i][id_result_job]."','".$arrayDataDecode[$i][comment]."','".$arrayDataDecode[$i][possible_fault]."','".$arrayDataDecode[$i][conclution_master]."')";
			}  
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> job_information query <> '.$query );
			if( $stmt = $db->prepare($query) ){
			$stmt->execute();
			$stmt->close();
			}
        }
    }
	
	
	//---------------- upload_spares_used ----------------
	if ($arr_data[0]=='upload_spares_used')
    {
        $result = stripslashes($arr_data[1]);
        writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> upload_spares_used <> '.$result );
		$arrayDataDecode = (array)json_decode($result, true);
        $res = count($arrayDataDecode);
        $i=0;
        for ($i;$i<$res;$i++)
        {
			
			//$query = "SELECT id_request FROM job_information WHERE id_request=".$arrayDataDecode[$i]['id_request']."";
			//$query = "SELECT `request_id` FROM ".$DB_PREFIX."used_spares WHERE `request_id`=".$arrayDataDecode[$i]['id_request'].";";
			//$stmt = $db->prepare($query);
			//$stmt->execute();
			//$stmt->store_result();
			//if ($stmt->num_rows)
			//{
			//$query = "UPDATE ".$DB_PREFIX."used_spares SET `article`='".$arrayDataDecode[$i]['aticle']."',`spares_group`='".$arrayDataDecode[$i]['spares_group']."',`name`='".$arrayDataDecode[$i]['spare']."',count=".$arrayDataDecode[$i]['count']." WHERE `request_id`=".$arrayDataDecode[$i]['id_request'].";";
			//}
			//else
			//{
            $query = "INSERT INTO ".$DB_PREFIX."used_spares (`request_id`,`article`,`spares_group`,`name`,`count`,`spareRef`) VALUES (".$arrayDataDecode[$i]['id_request'].",'".$arrayDataDecode[$i]['aticle']."','".$arrayDataDecode[$i]['spares_group']."','".$arrayDataDecode[$i]['spare']."',".$arrayDataDecode[$i]['count'].",'".$arrayDataDecode[$i]['spareRef']."');";
			//}  
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> upload_spares_used query <> '.$query );
			if( $stmt = $db->prepare($query) ){
			$stmt->execute();
			$stmt->close();
			}
        }
    }
	
	
	
	
	

    
?>
