<?php 
    include "settings.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 = $_POST['data'];
  //$data = "{\"func\":\"ms_visits\",\"id\":1,\"lastSynch\":\"2012-06-26 13:05:00\"}";//DebugBreak();
    $data = stripslashes($data);
	
	writeToLogFile( date('Y-m-d H:i:s').' | data | '.$data );
	
    $arraydata = (array)json_decode($data,true);
    //DebugBreak();
    if   (count($arraydata)==0)
    {
      $arr_data=explode('?',$data,2);
    }

  // echo $arraydata;
  writeToLogFile( date('Y-m-d H:i:s').' | arr_data[0] | '.$arr_data[0] );
    
if ($arraydata['func']=='tasks')
{
  
  $userId = $arraydata["id"];
  $date = $arraydata["date"];

    $i=0;
    $query = "SELECT id, client_id, nameProduct, tradeMark, code, part, count_warehouse, count_showcase, price, count_face, date, coment FROM mw_reporttasksdetails WHERE date>=".$date."";
    if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($id, $client_id, $nameProduct, $tradeMark, $code, $part, $count_warehouse, $count_showcase, $price, $count_face, $date, $coment);
            while($stmt->fetch()){
                $ModelTV [$i]=
        array('id'=>$id,
            'client_id'=>$client_id,
            'nameProduct'=>$nameProduct,
            'tradeMark'=>$tradeMark,
            'code'=>$code,
            'part'=>$part,
            'count_warehouse'=>$count_warehouse,
            'count_showcase'=>$count_showcase,
            'price'=>$price,
            'count_face'=>$count_face,
            'date'=>$date,
            'coment'=>$coment
            );
                $i++;
            } 
            $stmt->close();
            $db->close();
        }
      echo '{"rows":[{"taskvisits":'.json_encode($ModelTV).'}]}';
    
}  
        

if ($arraydata['func']=='clients')
{
    $userId = $arraydata["id"];

    $i=0;
        $query = "SELECT id,name,contactPerson,contactPhone,positionContactPerson,officePhone,postAddress,legalAddress,manager_id,standards FROM mw_clients";
        if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($id,$name,$contactPerson,$contactPhone,$positionContactPerson,$officePhone,$postAddress,$legalAddress,$manager_id,$standards);
            while($stmt->fetch()){
                $clients [$i]=
                array('id'=>$id,
                      'name'=>$name,
                      'contactPerson'=>$contactPerson,
                      'contactPhone'=>$contactPhone,
                      'positionContactPerson'=>$positionContactPerson,
                      'officePhone'=>$officePhone,
                      'postAddress'=>$postAddress,
                      'legalAddress'=>$legalAddress,
                      'manager_id'=>$manager_id,
                      'standards'=>$standards,
                      );
                $i++;
            } 
            $stmt->close();
            $db->close();
        }
        echo '{"rows":[{"clients":'.json_encode($clients).'}]}';
       //echo '11111';
        
}  

if ($arraydata['func']=='products')
{
    $userId = $arraydata["id"];

    $i=0;
           $query = "SELECT id, product_id, tpId, code, part, count_warehouse,count_showcase,price,count_faces,date,coment FROM mw_reporttasks" ;
        if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($id, $product_id, $tpId, $code, $part, $count_warehouse,$count_showcase,$price,$count_faces,$date,$coment);
            while ($stmt->fetch()) {
                  $Model [$i]= 
                array('id'=>$id,
                      'product_id'=>$product_id,
                      'tpId'=>$tpId,
                      'code'=>$code,
                      'part'=>$part,
                      'count_warehouse'=>$count_warehouse,
                      'count_showcase'=>$count_showcase,
                      'price'=>$price,
                      'count_faces'=>$count_faces,
                      'date'=>$date,
                      'coment'=>$coment
                );
                $i++;
            } 
            $stmt->close();
            $db->close();
        }
        echo '{"rows":[{"products":'.json_encode($Model).'}]}';
       //echo '11111';
        
}   


if ($arraydata['func']=='group_products')
{
    $userId = $arraydata["id"];

    $i=0;
           $query = "SELECT id,nameGroup,description FROM mw_tradegroups" ;
        if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($id, $name_group, $description);
            while ($stmt->fetch()) {
                  $Model [$i]= 
                array('id'=>$id,
                      'nameGroup'=>$name_group,
                      'description'=>$description
                );
                $i++;
            } 
            $stmt->close();
            $db->close();
        }
        echo '{"rows":[{"group_products":'.json_encode($Model).'}]}';
       //echo '11111';
        
}  


//--------------------------- promo ----------------------------------------------------------------------------------------------------------
if ($arraydata['func']=='promotions')
{
    $i=0;
	$query = "SELECT `ID`,`SurveyNumber`,`SurveyName`,`SurveyStart`,`SurveyEnd`,`SurveyDescription`,`SurveyCategory`,`ProductCategory`,`Active` FROM `ms_promotions` WHERE `SurveyEnd` >= DATE(NOW())";
	if ($stmt = $db->prepare($query)){
        $stmt->execute();
        $stmt->bind_result($id,$SurveyNumber,$SurveyName,$SurveyStart,$SurveyEnd,$SurveyDescription,$SurveyCategory,$ProductCategory,$Active);
        while ($stmt->fetch()){
                  $Model [$i]= 
                array('id'=>$id,
                      'SurveyNumber'=>$SurveyNumber,
                      'SurveyName'=>$SurveyName,
                      'SurveyStart'=>$SurveyStart,
                      'SurveyEnd'=>$SurveyEnd,
                      'SurveyDescription'=>$SurveyDescription,
                      'SurveyCategory'=>$SurveyCategory, 
                      'ProductCategory'=>$ProductCategory, 
                      'Active'=>$Active
                );
                $i++;
            }
            $stmt->close();
            $db->close();
        }
    echo $msg = json_encode($Model);
	writeToLogFile(date('Y-m-d H:i:s').' '.$msg);
	
	/*$userId = $arraydata["id"];

    $i=0;
           $query = "SELECT id,idDateColumn,idRow,storeData,checkedRadio,activFoto,descr,descr_merch,estimate,task,complit FROM mw_planworking" ;
        if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($id,$idDateColumn,$idRow,$storeData,$checkedRadio,$activFoto,$descr,$descr_merch,$estimate,$task,$complit);

             
            while ($stmt->fetch()) {
                  $Model [$i]= 
                array('id'=>$id,
                      'idDateColumn'=>$idDateColumn,
                      'idRow'=>$idRow,
                      'storeData'=>$storeData,
                      'checkedRadio'=>$checkedRadio,
                      'activFoto'=>$activFoto,
                      'descr'=>$descr, 
                      'descr_merch'=>$descr_merch, 
                      'estimate'=>$estimate,
                      'task'=>$task,
                      'complit'=>$complit
                );
                //$Model[$i]['descr_merch'] = addslashes($Model[$i]['descr_merch']);
                $i++;
            } 
            $stmt->close();
            $db->close();
        }
        echo '{"rows":[{"promotions":'.json_encode($Model).'}]}';
       //echo '11111';
    */   
}  
if ($arraydata['func']=='promotions2')
{
    $i=0;
	$query = "SELECT p2t.`SurveyNumber`,p2t.`CustomerCode` FROM `ms_promotions2tradepoint` p2t LEFT JOIN `ms_promotions` pr ON pr.`SurveyNumber`=p2t.`SurveyNumber` WHERE pr.`SurveyEnd` >= DATE(NOW())";
	if ($stmt = $db->prepare($query)){
        $stmt->execute();
        $stmt->bind_result($SurveyNumber,$CustomerCode);
        while ($stmt->fetch()){
                  $Model [$i]= 
                array(
                      'SurveyNumber'=>$SurveyNumber,
                      'CustomerCode'=>$CustomerCode
                );
                $i++;
            }
            $stmt->close();
            $db->close();
        }
    echo $msg = json_encode($Model);
	writeToLogFile(date('Y-m-d H:i:s').' '.$msg);
}

if ($arraydata['func']=='promotions3'){
    $i=0;
	$query = "SELECT p2q.`id`,p2q.`SurveyNumber`,p2q.`Question`,p2q.`ResponseText` FROM `ms_promotions2question` p2q LEFT JOIN `ms_promotions` pr ON p2q.`SurveyNumber`=pr.`SurveyNumber` WHERE pr.`SurveyEnd` >= DATE(NOW())";
	if ($stmt = $db->prepare($query)){
        $stmt->execute();
        $stmt->bind_result($id,$SurveyNumber,$Question,$ResponseText);
        while ($stmt->fetch()){
                  $Model [$i]= 
                array('id'=>$id,
                      'SurveyNumber'=>$SurveyNumber,
                      'Question'=>$Question,
					  'ResponseText'=>$ResponseText
                );
                $i++;
            }
            $stmt->close();
            $db->close();
        }
    echo $msg = json_encode($Model);
	writeToLogFile(date('Y-m-d H:i:s').' '.$msg);
}


if ($arraydata['func']=='sendPromo')
{
    $i=0;
	$JSON = $arraydata["JSONPromo"];
	$strRack="";
    while ($i < count($JSON))
    {
       
        $strRack .= "(".$JSON[$i]['id_visit'].",".$JSON[$i]['id_promo'].",".$JSON[$i]['id_quest'].",'". $JSON[$i]['answer']."'),";   
        $i++;
    }
    $strRack = substr($strRack, 0, strlen($strRack)-1);
    $query =  "INSERT INTO `ms_promosquestion` (`id_visit`,`id_promo`,`id_quest`,`answer`) VALUES ".$strRack;
    $msg = "query: ".$query;
    writeToLogFile($msg);
    $stmt = $db->prepare($query);
    $stmt->execute();

    echo 'ok';
}



//----------------new synchronization------------------------------

if ($arraydata['func']=='ms_visits')
{
    $userId = $arraydata["id"];
    $lastSynch = $arraydata["lastSynch"];
	
	$query = "SELECT `diapsone_distr` FROM `ms_settings` WHERE `id_user`=".$userId.";";
	if($stmt = $db->prepare($query)){
	$stmt->execute();
	$stmt->bind_result($diap);
	$stmt->fetch();
	$stmt->close();
	
	}
	if(!$diap)$diap=1;
	
    $i=0;
           //$query = "SELECT id,date,description,id_trade_point,id_user,date_change,id_client FROM ms_visit WHERE date_change>'".$lastSynch."'";
           //$query = "SELECT id,DATE,description,id_trade_point,id_user,date_start,id_client FROM ms_visit WHERE close=0 ORDER BY date ASC";
$query = "SELECT id,`date`,description,id_trade_point,id_user,date_start,id_client,`close` FROM ms_visit WHERE `close`=0 UNION SELECT id,`date`,description,id_trade_point,id_user,date_start,id_client,`close` FROM ms_visit WHERE `close`=1 AND DATE(`date`)>=CURDATE()-INTERVAL ".$diap." DAY AND DATE(`date`)<=CURDATE() 
";
        if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($id,$date,$description,$id_trade_point,$id_user,$date_change,$id_client,$close);

             
            while ($stmt->fetch()) {
                  $Model [$i]= 
                array('id'=>$id,
                      'date'=>$date,
                      'description'=>$description,
                      'id_trade_point'=>$id_trade_point,
                      'id_user'=>$id_user,
                      'date_change'=>$date_change,
                      'id_client'=>$id_client,
					  'close'=>$close,
                );
                $i++;
            } 
            $stmt->close();
            $db->close();
        }
        //echo '{"rows":[{"ms_visits":'.json_encode($Model).'}]}';
	writeToLogFile($query);
    writeToLogFile(json_encode($Model));
        echo json_encode($Model);
} 

if ($arraydata['func']=='ms_trade_point')
{
		$userId = $arraydata["id"];
		$i=0;
           //$query = "SELECT id,number,name,address,id_city,latitude,longitude,id_network FROM ms_trade_point LIMIT 30";//.$arraydata['limitFrom'].",".$arraydata['limitTo'] ;     // WHERE id_trade_point IN ".$listIdTradePoints."   если выбираем торг точки по загруженым визитам
          // $query = "SELECT id,number,name,address,id_city,latitude,longitude,id_network FROM ms_trade_point WHERE number IN ('1010300653','1010508825','1009800315','1015108363','1004804153','1015404285','1009800307','1010401083','1009800300','1010506644','10001','10002','10003','10004','10005','10006','10007','10008')";
		  $query = "SELECT id,number,name,address,id_city,latitude,longitude,id_network FROM ms_trade_point WHERE instance_id=(SELECT `instance_id` FROM `ms_user` WHERE `id` = ".$userId.");";
		  writeToLogFile($query);
        if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($id,$number,$name,$address,$city,$latitude,$longitude,$id_network);

             
            while ($stmt->fetch()) 
            {
                $name = str_replace('"',"'",$name);
                $address = str_replace('"',"'",$address);
                $Model [$i]= 
                array('id'=>$id,
                      'number'=>$number,
                      'name'=>$name,
                      'address'=>$address,
                      'city'=>$city,
                      'latitude'=>$latitude,
                      'longitude'=>$longitude,
                      'id_network'=>$id_network
                );
                $i++;
            } 
            $stmt->close();
            $db->close();
        }
        echo json_encode($Model);
}

if ($arraydata['func']=='ms_article_trade_point')
{
        
    $i=0;
    $strTP = "";
    //$query = "SELECT number FROM ms_trade_point LIMIT 30";
    $query = "SELECT number FROM ms_trade_point WHERE number IN ('1010300653','1010508825','1009800315','1015108363','1004804153','1015404285','1009800307','1010401083','1009800300','1010506644')";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $stmt->bind_result($number);

             
    while ($stmt->fetch()) 
    {
        $strTP .= "'" . $number . "',";
        $i++;   
    }
    $strTP = substr($strTP, 0, strlen($strTP)-1);
    
    $i = 0;
    
           //$query = "SELECT id, article, trade_points FROM ms_article_trade_point WHERE trade_points IN (" . $strTP . ")";
           $query = "SELECT id, article, trade_points FROM ms_article_trade_point WHERE trade_points IN (" . $strTP . ")";
          
         
       if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($id,$article,$TP);

             
            while ($stmt->fetch()) 
            {
                $Model [$i]= 
                array(
                      'id'=>$id,
                      'article'=>$article,
                      'trade_point'=>$TP
                );
                $i++;
            } 
            $stmt->close();
            $db->close();
        }
        echo json_encode($Model);
}

if ($arraydata['func']=='ms_tasks')
{
    $arrayIdVisits = $arraydata["arrayIdVisits"];
    $listIdVisits = '('.$arrayIdVisits.')';

    $i=0;
            $query = "SELECT id,description,complit,id_visit,comment FROM ms_task WHERE id_visit IN ".$listIdVisits."" ;
			//$query = "SELECT taskID,bodyTask,clientID,complit,nameActive,priority,visitID FROM ms_tasks WHERE visitID IN ".$listIdVisits."" ;
           //$query = "SELECT taskID,bodyTask,clientID,complit,nameActive,priority,visitID FROM ms_tasks";
        if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($id,$description,$complit,$id_visit,$comment);

             
            while ($stmt->fetch()) {
                  $Model [$i]= 
                array('id'=>$id,
                      'description'=>$description,
                      'complit'=>$complit,
                      'id_visit'=>$id_visit,
                      'comment'=>$comment
                );
                $i++;
            } 
            $stmt->close();
            $db->close();
        }
        echo json_encode($Model);
}

if ($arraydata['func']=='ms_products')
{
    //$userId = $arraydata["id"];
    //$lastSynch = $arraydata["lastSynch"];
    
    $query = "SELECT number FROM ms_trade_point WHERE number IN ('1010300653','1010508825','1009800315','1015108363','1004804153','1015404285','1009800307','1010401083','1009800300','1010506644')";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $stmt->bind_result($number);

    $strTP = '';         
    while ($stmt->fetch()) 
    {
        $strTP .= "'" . $number . "',";
        $i++;   
    }
    $strTP = substr($strTP, 0, strlen($strTP)-1);
    
    $strProduct = '';          
         
    $query = "SELECT article FROM ms_article_trade_point WHERE trade_points IN (" . $strTP . ")";
          
    $stmt = $db->prepare($query);
    $stmt->execute();
    $stmt->bind_result($article);

    while ($stmt->fetch()) 
    {
        $arrArticle = explode(',',$article);
        $j = 0;
        while($j < count($arrArticle))
        {
            $strProduct .= "'" . $arrArticle[$j] . "',";    
            $j++;
        }    
    }
    $strProduct = substr($strProduct, 0, strlen($strProduct)-1);
     
   
    
    $startLine = $arraydata["startLine"];
    $endLine = $startLine + 999;
    $i=0;
           $query = "SELECT id,article,name,id_category_brand,barcode,info,price,unit,begin_date,end_date,photo,delivery_period,balance_stock FROM ms_product WHERE article IN (" . $strProduct . ")"; // WHERE id >= " . $startLine . " AND id <= " . $endLine . " LIMIT 30";
        if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($id,$article,$name,$id_category_brand,$barcode,$info,$price,$unit,$begin_date,$end_date,$photo,$delivery_period,$balance_stock);
             
            while ($stmt->fetch()) 
            {
                $name = str_replace('"',"'",$name);
                  $Model [$i]= 
                array('id'=>$id,
                      'article'=>$article,
                      'name'=>$name,
                      'id_category_brand'=>$id_category_brand,
                      'barcode'=>$barcode,
                      'info'=>$info,
                      'price'=>$price,
                      'unit'=>$unit,
                      'begin_date'=>$begin_date,
                      'end_date'=>$end_date,
                      'photo'=>$photo,
                      'delivery_period'=>$delivery_period,
                      'balance_stock'=>$balance_stock
                );
                $i++;
            } 
            $stmt->close();
            $db->close();
        }
        //echo '{"rows":[{"ms_visits":'.json_encode($Model).'}]}';
        echo json_encode($Model);
}

if ($arraydata['func']=='ms_category')
{
    $i=0;
           $query = "SELECT id,name FROM ms_category";
        if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($id,$name);

             
            while ($stmt->fetch()) {
                  $Model [$i]= 
                array('id'=>$id,
                      'name'=>$name
                );
                $i++;
            } 
            $stmt->close();
            $db->close();
        }
        
        echo json_encode($Model);
}

if ($arraydata['func']=='ms_brand')
{
    $i=0;
           $query = "SELECT id,name FROM ms_brand";
        if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($id,$name);

             
            while ($stmt->fetch()) {
                  $Model [$i]= 
                array('id'=>$id,
                      'name'=>$name
                );
                $i++;
            } 
            $stmt->close();
            $db->close();
        }
        
        echo json_encode($Model);
}

if ($arraydata['func']=='ms_category_brand')
{
    $i=0;
           $query = "SELECT id,id_category,id_brand FROM ms_category_brand";
        if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($id,$id_category,$id_brand);
             
            while ($stmt->fetch())
            {
              $Model [$i]= 
                array('id'=>$id,
                      'id_category'=>$id_category,
                      'id_brand'=>$id_brand
                );
                $i++;
            } 
            $stmt->close();
            $db->close();
        }
        
        echo json_encode($Model);
}

if ($arraydata['func']=='ms_product_trade_point_client')
{
    $i=0;
           $query = "SELECT id,product_id,trade_point_id,client_id FROM ms_product_trade_point_client";
        if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($id,$product_id,$trade_point_id,$client_id);

             
            while ($stmt->fetch()) {
                  $Model [$i]= 
                array('id'=>$id,
                      'product_id'=>$product_id,
                      'trade_point_id'=>$trade_point_id,
                      'client_id'=>$client_id
                );
                $i++;
            } 
            $stmt->close();
            $db->close();
        }
        
        echo json_encode($Model);
}

if ($arraydata['func']=='ms_users')
{
    //$userId = $arraydata["id"];
    //$lastSynch = $arraydata["lastSynch"];

    $i=0;
           $query = "SELECT id_user,bossId,login,password,firstName,lastName,middleName,position,email,tel,address,comments,role,client FROM ms_users";
        if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($id_user,$bossId,$login,$password,$firstName,$lastName,$middleName,$position,$email,$tel,$address,$comments,$role,$client);

             
            while ($stmt->fetch()) {
                  $Model [$i]= 
                array('id_user'=>$id_user,
                      'bossId'=>$bossId,
                      'login'=>$login,
                      'password'=>$password,
                      'firstName'=>$firstName,
                      'lastName'=>$lastName,
                      'middleName'=>$middleName,
                      'position'=>$position,
                      'email'=>$email,
                      'tel'=>$tel,
                      'address'=>$address,
                      'comments'=>$comments,
                      'role'=>$role,
                      'client'=>$client
                );
                $i++;
            } 
            $stmt->close();
            $db->close();
        }
        //echo '{"rows":[{"ms_visits":'.json_encode($Model).'}]}';
        echo json_encode($Model);
}

if ($arraydata['func']=='ms_question')
{
    //$userId = $arraydata["id"];
    //$lastSynch = $arraydata["lastSynch"];

    $i=0;
           $query = "SELECT id, id_client, id_trade_point, name, date_start, date_end, body, id_type_question, compulsory FROM ms_question";
        if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($id, $id_client, $id_trade_point, $name, $date_start, $date_end, $body, $id_type_question, $compulsory);

             
            while ($stmt->fetch()) {
                  $Model [$i]= 
                array('id'=>$id,
                      'id_client'=>$id_client,
                      'id_trade_point'=>$id_trade_point,
                      'name'=>$name,
                      'date_start'=>$date_start,
                      'date_end'=>$date_end,
                      'body'=>$body,
                      'id_type_question'=>$id_type_question,
                      'compulsory'=>$compulsory
                );
                $i++;
            } 
            $stmt->close();
            $db->close();
        }
        //echo '{"rows":[{"ms_visits":'.json_encode($Model).'}]}';
        echo json_encode($Model);
}

if ($arraydata['func']=='ms_type_question')
{
    //$userId = $arraydata["id"];
    //$lastSynch = $arraydata["lastSynch"];

    $i=0;
           $query = "SELECT id,name FROM ms_type_question";
        if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($id,$name);

             
            while ($stmt->fetch()) {
                  $Model [$i]= 
                array('id'=>$id,
                      'name'=>$name
                );
                $i++;
            } 
            $stmt->close();
            $db->close();
        }
        //echo '{"rows":[{"ms_visits":'.json_encode($Model).'}]}';
        echo json_encode($Model);
}

if ($arraydata['func']=='ms_client')
{
    //$userId = $arraydata["id"];
    //$lastSynch = $arraydata["lastSynch"];

    $i=0;
           $query = "SELECT id, name, phone, id_city, address, number, number_contract, date_end_contract FROM ms_client";
        if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($id, $name, $phone, $id_city, $address, $number, $number_contract, $date_end_contract);

             
            while ($stmt->fetch()) {
                  $Model [$i]= 
                array('id'=>$id,
                      'name'=>$name,
                      'phone'=>$phone,
                      'id_city'=>$id_city,
                      'address'=>$address,
					  'number'=>$number,
					  'number_contract'=>$number_contract,
					  'date_end_contract'=>$date_end_contract
                );
                $i++;
            } 
            $stmt->close();
            $db->close();
        }
        //echo '{"rows":[{"ms_visits":'.json_encode($Model).'}]}';
        echo json_encode($Model);
}

if ($arraydata['func']=='ms_client_trade_point')
{
    $i=0;
           $query = "SELECT id,id_client,id_trade_point FROM ms_client_trade_point";
        if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($id,$id_client,$id_trade_point);

             
            while ($stmt->fetch()) {
                  $Model [$i]= 
                array('id'=>$id,
                      'id_client'=>$id_client,
                      'id_trade_point'=>$id_trade_point
                );
                $i++;
            } 
            $stmt->close();
            $db->close();
        }
        //echo '{"rows":[{"ms_visits":'.json_encode($Model).'}]}';
        echo json_encode($Model);
}

if ($arraydata['func']=='ms_category_client')
{
    $i=0;
           $query = "SELECT id,id_category,id_client FROM ms_category_client";
        if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($id,$id_category,$id_client);

             
            while ($stmt->fetch()) {
                  $Model [$i]= 
                array('id'=>$id,
                      'id_category'=>$id_category,
                      'id_client'=>$id_client
                );
                $i++;
            } 
            $stmt->close();
            $db->close();
        }
        //echo '{"rows":[{"ms_visits":'.json_encode($Model).'}]}';
        echo json_encode($Model);
}

if ($arraydata['func']=='ms_person')
{
    $i=0;
           $query = "SELECT id,name,surname,lastname,phone,id_client,id_trade_point FROM ms_person";
        if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($id,$name,$surname,$lastname,$phone,$id_client,$id_trade_point);

             
            while ($stmt->fetch()) {
                  $Model [$i]= 
                array('id'=>$id,
                      'name'=>$name,
                      'surname'=>$surname,
                      'lastname'=>$lastname,
                      'phone'=>$phone,
                      'id_client'=>$id_client,
                      'id_trade_point'=>$id_trade_point
                );
                $i++;
            } 
            $stmt->close();
            $db->close();
        }
        echo json_encode($Model);
}


if ($arraydata['func']=='mw_client_point')
{
    $userId = $arraydata["id"];

    $i=0;
           $query = "SELECT mw_client_point.id_client,mw_client_point.id_trade_point FROM (SELECT DISTINCT mw_tradepoints.id FROM mw_planworking LEFT JOIN mw_tradepoints ON mw_planworking.idRow=mw_tradepoints.id WHERE complit=0) AS tradePointsId LEFT JOIN mw_client_point ON tradePointsId.id=mw_client_point.id_trade_point" ;
        if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($id_client,$id_trade_point);

             
            while ($stmt->fetch()) {
                  $Model [$i]= 
                array('id_client'=>$id_client,
                      'id_trade_point'=>$id_trade_point
                );
                $i++;
            } 
            $stmt->close();
            $db->close();
        }
        echo '{"rows":[{"mw_client_point":'.json_encode($Model).'}]}';
}

if ($arraydata['func']=='mw_tradecities')
{
    $userId = $arraydata["id"];

    $i=0;
           $query = "SELECT mw_tradecities.id,mw_tradecities.region_id,mw_tradecities.nameCity,mw_tradecities.phone_code FROM (SELECT mw_tradepoints.cityID FROM mw_planworking LEFT JOIN mw_tradepoints ON mw_planworking.idRow=mw_tradepoints.id WHERE complit=0) AS t_city_id LEFT JOIN mw_tradecities ON t_city_id.cityID=mw_tradecities.id" ;
        if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($id,$region_id,$nameCity,$phone_code);

             
            while ($stmt->fetch()) {
                  $Model [$i]= 
                array('id'=>$id,
                      'region_id'=>$region_id,
                      'nameCity'=>$nameCity,
                      'phone_code'=>$phone_code
                );
                $i++;
            } 
            $stmt->close();
            $db->close();
        }
        echo '{"rows":[{"mw_tradecities":'.json_encode($Model).'}]}';
}

if ($arraydata['func']=='mw_traderegion')
{
    $userId = $arraydata["id"];

    $i=0;
           $query = "SELECT mw_traderegion.id,mw_traderegion.name FROM (SELECT mw_tradecities.region_id FROM (SELECT mw_tradepoints.cityID FROM mw_planworking LEFT JOIN mw_tradepoints ON mw_planworking.idRow=mw_tradepoints.id WHERE complit=0) AS t_city_id LEFT JOIN mw_tradecities ON t_city_id.cityID=mw_tradecities.id) AS region_id LEFT JOIN mw_traderegion ON region_id.region_id=mw_traderegion.id" ;
        if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($id,$name);

             
            while ($stmt->fetch()) {
                  $Model [$i]= 
                array('id'=>$id,
                      'name'=>$name
                );
                $i++;
            } 
            $stmt->close();
            $db->close();
        }
        echo '{"rows":[{"mw_traderegion":'.json_encode($Model).'}]}';
}

if ($arraydata['func']=='mw_tradegroups')
{
    $userId = $arraydata["id"];

    $i=0;
           $query = "SELECT mw_tradegroups.id,mw_tradegroups.nameGroup FROM (SELECT DISTINCT groupID FROM mw_planworking LEFT JOIN mw_tradepoints ON mw_planworking.idRow=mw_tradepoints.id WHERE complit=0) AS groupID LEFT JOIN mw_tradegroups ON groupID.groupID=mw_tradegroups.id";
        if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($id,$nameGroup);

             
            while ($stmt->fetch()) {
                  $Model [$i]= 
                array('id'=>$id,
                      'nameGroup'=>$nameGroup
                );
                $i++;
            } 
            $stmt->close();
            $db->close();
        }
        echo '{"rows":[{"mw_tradegroups":'.json_encode($Model).'}]}';
}

if ($arraydata['func']=='mw_reporttasksdetails')
{
    $userId = $arraydata["id"];

    $i=0;
           $query = "SELECT id,client_id,nameProduct,tradeMark,code,part,count_warehouse,count_showcase,price,count_face,coment FROM mw_reporttasksdetails WHERE client_id IN (SELECT DISTINCT mw_client_point.id_client FROM (SELECT DISTINCT mw_tradepoints.id FROM mw_planworking LEFT JOIN mw_tradepoints ON mw_planworking.idRow=mw_tradepoints.id WHERE complit=0) AS tradePointsId LEFT JOIN mw_client_point ON tradePointsId.id=mw_client_point.id_trade_point)";
        if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($id,$client_id,$nameProduct,$tradeMark,$code,$part,$count_warehouse,$count_showcase,$price,$count_face,$coment);

             
            while ($stmt->fetch()) {
                  $Model [$i]= 
                array('id'=>$id,
                      'client_id'=>$client_id,
                      'nameProduct'=>$nameProduct,
                      'tradeMark'=>$tradeMark,
                      'code'=>$code,
                      'part'=>$part,
                      'count_warehouse'=>$count_warehouse,
                      'count_showcase'=>$count_showcase,
                      'price'=>$price,
                      'count_face'=>$count_face,
                      'coment'=>$coment
                );
                $i++;
            } 
            $stmt->close();
            $db->close();
        }
        echo '{"rows":[{"mw_reporttasksdetails":'.json_encode($Model).'}]}';
}


if ($arraydata['func']=='sendDistribution')
{
    $JSONDistribution = $arraydata["JSONDistribution"];
    $strDestribution = '';
    $i = 0;
    while ($i < count($JSONDistribution))
    {
        $strDestribution .= "(".$JSONDistribution[$i][id_product].",'".$JSONDistribution[$i][price]."',".$JSONDistribution[$i][number_stock].",". $JSONDistribution[$i][novelty].','.$JSONDistribution[$i][lack_product].",".$JSONDistribution[$i][count_faces].",".$JSONDistribution[$i][out_price].",".$JSONDistribution[$i][id_visit]."),";    
        $i++;
    }
    $strDestribution = substr($strDestribution, 0, strlen($strDestribution)-1);
    $query =  "INSERT INTO ms_distribution_list (id_product,price,number_stock,novelty,lack_product,count_faces,out_price,id_visit) VALUES ".$strDestribution;
    $msg = "query: ".$query;
    $stmt = $db->prepare($query);
    $stmt->execute();

    //echo $JSONDistribution[0][id_product].'///'.$JSONDistribution[0][price];
    echo 'ok';
}
if ($arraydata['func']=='getDistribution')
{
    $userId = $arraydata["id"];
	$i=0;
    $query = "SELECT id FROM ms_visit WHERE `close`=1 AND DATE(`date`)>=CURDATE()-INTERVAL (SELECT `diapsone_distr` FROM `ms_settings` WHERE `id_user`=".$userId.") DAY AND DATE(`date`)<=CURDATE()";
    if($stmt = $db->prepare($query)){
		$stmt->execute();
		$stmt->bind_result($id);
		while ($stmt->fetch()){
            $Us[$i]=array('id'=>$id);
            $i++;
        } 
        $stmt->close();
    }
	writeToLogFile(date('Y-m-d H:i:s').' | getDistribution  | '.$query);
	$i=0;
	while($i<count($Us)){
	//$query = "SELECT `id`,`id_product`,`price`,`number_stock`,`novelty`,`lack_product`,`count_faces`,`out_price`,`id_visit` FROM `ms_distribution_list` WHERE `id_visit`=".$Us[$i]['id']."";
    $query = "SELECT dist.`id`,dist.`id_product`,dist.`price`,dist.`number_stock`,dist.`novelty`,dist.`lack_product`,dist.`count_faces`,dist.`out_price`,dist.`id_visit`,prod.`name` FROM `ms_distribution_list` dist LEFT JOIN `ms_product` prod ON dist.`id_product`=prod.`id` WHERE dist.`id_visit`=".$Us[$i]['id']."";
	if($stmt = $db->prepare($query)){
		$stmt->execute();
		$stmt->bind_result($id,$id_product,$price,$number_stock,$novelty,$lack_product,$count_faces,$out_price,$id_visit,$name);
		while ($stmt->fetch()){
            $Mo[$i]=array(
			'ID'=>$id,
			'IDP'=>$id_product,
			'P'=>$price,
			'NS'=>$number_stock,
			'N'=>$novelty,
			'LP'=>$lack_product,
			'CF'=>$count_faces,
			'OP'=>$out_price,
			'IDV'=>$id_visit,
			'NM'=>$name
			);
            $i++;
        } 
        $stmt->close();
    }
	$i++;
	}
	$db->close();
	echo json_encode($Mo);
	writeToLogFile(date('Y-m-d H:i:s').' | getDistribution  | '.$query);
	writeToLogFile(date('Y-m-d H:i:s').' | getDistribution  | '.json_encode($Mo));
}


if ($arraydata['func']=='sendRack')
{
    $type = 18;
    $JSONRack = $arraydata["JSONRack"];
    $strRack = '';
    $i = 0;
    while ($i < count($JSONRack))
    {
       
         $strRack .= "(".$JSONRack[$i][id_category].",".$JSONRack[$i][share_retail].",".$JSONRack[$i][width].",". $JSONRack[$i][id_visit]."),";   
        /*if ($JSONRack[$i][id_question] == '19')
        {
            $strRack = str_replace(",-1,",",".$JSONRack[$i][ansver_data].",",$strRack);   
        }*/           
        $i++;
    }
    $strRack = substr($strRack, 0, strlen($strRack)-1);
    $query =  "INSERT INTO ms_share_retail (id_category,share_retail,width,id_visit) VALUES ".$strRack;
    $msg = "query: ".$query;
    writeToLogFile($msg);
    $stmt = $db->prepare($query);
    $stmt->execute();

    //echo $JSONDistribution[0][id_product].'///'.$JSONDistribution[0][price];
    echo 'ok';
}

if ($arraydata['func']=='sendJob')
{
  $JSONJob = $arraydata["JSONJob"];
  $strJob = '';
  $i = 0;
  
  while ($i < count($JSONJob))
  {
    $query = "DELETE FROM ms_job WHERE id=".$JSONJob[$i][id]."";
    $stmt = $db->prepare($query);
    $stmt->execute();
    
    $strJob .= "(".$JSONJob[$i][id].", ".$JSONJob[$i][id_user_created].", '".$JSONJob[$i][date]."', '".$JSONJob[$i][job]."', ". $JSONJob[$i][id_user_performer].", ". $JSONJob[$i][state]."),";   
    $i++;
  }
  $strJob = substr($strJob, 0, strlen($strJob)-1);
  $query =  "INSERT INTO ms_job (id, id_user_created, date, job, id_user_performer, state) VALUES ".$strJob;
  $msg = "query: ".$query;
  writeToLogFile($msg);
  $stmt = $db->prepare($query);
  $stmt->execute();

  echo 'ok';
}

if ($arraydata['func']=='sendVisit')
{
    $type = 18;
    $JSONVisit = $arraydata["JSONVisit"];
    $strVisit = "(";
    $i = 0;
    while ($i < count($JSONVisit))
    {
        //$strVisit .= $JSONVisit[$i][id_visit].",";
        $query =  "UPDATE  ms_visit SET date_start = '".$JSONVisit[$i][date_start]."',  date_finish = '".$JSONVisit[$i][date_finish]."', close = 1 WHERE  id = " . $JSONVisit[$i][id_visit];
        $msg = "query: ".$query;
        writeToLogFile($msg);
        $stmt = $db->prepare($query);
        $stmt->execute();
        $i++;
    }
    $strVisit = substr($strVisit, 0, strlen($strVisit)-1);
    $strVisit .= ")";   
    

    //echo $JSONDistribution[0][id_product].'///'.$JSONDistribution[0][price];
    echo 'ok';
}

if ($arraydata['func']=='ms_network')
  {
    /*if ($arraydata["id_user_temp"]){$userId = $arraydata["id_user_temp"];}
    else {$idCar = $arraydata["id_car"];}*/
    $startLine = $arraydata["startLine"];
    $endLine = $startLine + 999;
    
    $i=0;
    if (!$idCar)
    {
      $query = "SELECT id, name FROM ms_network LIMIT ".$startLine.", 1000 ";
      writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro ms_network <> '.$query );
      if ($stmt = $db->prepare($query)){
        $stmt->execute();
        $stmt->bind_result($id, $name);


        while ($stmt->fetch()) {
          $Model [$i]= 
          array('id'=>$id,
                'name'=>$name
          );
          $i++;
        } 
        $stmt->close();
        $db->close();
        
      }
    }
    if ($i < 999)
    {
      $arrayEndModel = array('EndModel'=>'true');
      if ($Model){array_push($Model,$arrayEndModel);}
      else {$Model = array();array_push($Model,$arrayEndModel);}
    }
    echo json_encode($Model);
  }
  
  if ($arraydata['func']=='ms_job')
  {
    $id_user = $arraydata['id_user'];
    $startLine = $arraydata["startLine"];
    $endLine = $startLine + 999;
    
    $i=0;
    if (!$idCar)
    {
      $query = "SELECT id, id_user_created, date, job, id_user_performer, state FROM ms_job WHERE id_user_performer IN (SELECT id FROM ms_user WHERE id_boss=".$id_user.") LIMIT ".$startLine.", 1000 ";
      writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro ms_job <> '.$query );
      if ($stmt = $db->prepare($query)){
        $stmt->execute();
        $stmt->bind_result($id, $id_user_created, $date, $job, $id_user_performer, $state);


        while ($stmt->fetch()) {
          $Model [$i]= 
          array('id'=>$id,
                'id_user_created'=>$id_user_created,
                'date'=>$date,
                'job'=>$job,
                'id_user_performer'=>$id_user_performer,
                'state'=>$state
          );
          $i++;
        } 
        $stmt->close();
        $db->close();
        
      }
    }
    if ($i < 999)
    {
      $arrayEndModel = array('EndModel'=>'true');
      if ($Model){array_push($Model,$arrayEndModel);}
      else {$Model = array();array_push($Model,$arrayEndModel);}
    }
    echo json_encode($Model);
  }
  
  if ($arraydata['func']=='ms_user')
  {
    //$id_user = $arraydata['id_user'];
    $startLine = $arraydata["startLine"];
    $endLine = $startLine + 999;
    
    $i=0;
    if (!$idCar)
    {
      $query = "SELECT id, id_boss, login, password, first_name, last_name, middle_name, position, email, phone, address, comments, id_role, client FROM ms_user LIMIT ".$startLine.", 1000 ";
      writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro ms_user <> '.$query );
      if ($stmt = $db->prepare($query)){
        $stmt->execute();
        $stmt->bind_result($id, $id_boss, $login, $password, $first_name, $last_name, $middle_name, $position, $email, $phone, $address, $comments, $id_role, $client);


        while ($stmt->fetch()) {
          $Model [$i]= 
          array('id'=>$id,
                'login'=>$login,
                'password'=>$password,
                'name'=>$first_name,
                'lastname'=>$last_name,
                'surname'=>$middle_name,
                'email'=>$email,
                'phone'=>$phone,
                'address'=>$address,
                'id_role'=>$id_role
          );
          $i++;
        } 
        $stmt->close();
        $db->close();
        
      }
    }
    if ($i < 999)
    {
      $arrayEndModel = array('EndModel'=>'true');
      if ($Model){array_push($Model,$arrayEndModel);}
      else {$Model = array();array_push($Model,$arrayEndModel);}
    }
    echo json_encode($Model);
  }
  
  
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];          
     
        //writeToLogFile( date('Y-m-d H:i:s').' | arr_data[0] | '.$arr_data[0] );
        //$handle = fopen("d:/Photo/temp.png", 'a');    //открыть файл для записи, курсор в конец
        //$handle = fopen("C:/htdocs/SFA/photo/temp.png", 'a');    //открыть файл для записи, курсор в конец
        $handle = fopen($IMAGE_PATH."temp.png", 'a');    //открыть файл для записи, курсор в конец
		
		fputs($handle, $fotoString);            // добавить строку в файл
        fclose($handle);
        
		writeToLogFile( date('Y-m-d H:i:s').' | fotoString | '.$fotoString );
		writeToLogFile( date('Y-m-d H:i:s').' | sendFotoDataArray[2] | '.$sendFotoDataArray[2] );
		
        $namePhoto = 'photo.png';
        
        if ($sendFotoDataArray[2]=="end")
        {
          //$handle = fopen("d:/Photo/temp.png", 'r');
          //$handle = fopen("C:/htdocs/SFA/photo/temp.png", 'r');
          $handle = fopen($IMAGE_PATH."temp.png", 'r');
		  //writeToLogFile( date('Y-m-d H:i:s').' | handle temp | '.$handle );
		  
		  
		  //$stringFile64 = file_get_contents("d:/Photo/temp.png");
          //$stringFile64 = file_get_contents("C:/htdocs/SFA/photo/temp.png");
          $stringFile64 = file_get_contents($IMAGE_PATH."temp.png");
		  
		  fclose($handle);
          //unlink("d:/Photo/temp.png");                              // удалить временный файл
          //unlink("C:/htdocs/SFA/photo/temp.png");                              // удалить временный файл
          unlink($IMAGE_PATH."temp.png");                              // удалить временный файл
		  
		  $stringFile64 = str_replace(" ","+",$stringFile64);       // \r\n
          $stringFile64 = str_replace("*****","\r",$stringFile64);       // \r\n
         
          
          $pathArray = explode("/",$sendFotoDataArray[1]);
		  writeToLogFile( date('Y-m-d H:i:s').' | pathArray | '.$sendFotoDataArray[1] );
		  
          $namePhoto = $pathArray[4];
		  writeToLogFile( date('Y-m-d H:i:s').' | pathArray | '.$namePhoto );
          //$handle = fopen("d:/Photo/$namePhoto", 'w');
          //$handle = fopen("C:/htdocs/SFA/photo/$namePhoto", 'w');
          $handle = fopen($IMAGE_PATH.$namePhoto, 'w');
		  
		  writeToLogFile( date('Y-m-d H:i:s').' |  namePhoto | '.$IMAGE_PATH.$namePhoto );
		  writeToLogFile( date('Y-m-d H:i:s').' | handle namePhoto | '.$handle );
		  
		  $stringFile = base64_decode($stringFile64);
          fwrite($handle,$stringFile);
          fclose($handle);
          //echo 'trueDelete';
		  
		  
		  if($sendFotoDataArray[4]==0){ $status = 'Черновик'; }else{ $status = 'Чистовик'; }
		  if($sendFotoDataArray[5]==0){ $type = 'Общий вид'; }elseif($sendFotoDataArray[5]==1){$type='Полка';}else{ $type = 'Стелаж'; }
		
        $query = "INSERT INTO `ms_photo` (`photo`,`description`,`status`,`type`,`date`,`latitude`,`longitude`,`id_cat`,`id_brand`,`id_visit`) VALUES('".$IMAGE_PATH2.$namePhoto."', '".$sendFotoDataArray[3]."', '".$status."', '".$type."', '".$sendFotoDataArray[6]."', '".$sendFotoDataArray[7]."', '".$sendFotoDataArray[8]."', ".$sendFotoDataArray[9].", ".$sendFotoDataArray[10].", ".$sendFotoDataArray[11].");";
		writeToLogFile( date('Y-m-d H:i:s').' | query | '.$query );
		$stmt = $db->prepare($query);
		$stmt->execute();
        $stmt->close();
		
		$query = "UPDATE ms_visit SET photo = 1 WHERE `id` = ".$sendFotoDataArray[11].";";
		writeToLogFile( date('Y-m-d H:i:s').' | query | '.$query );
		$stmt = $db->prepare($query);
		$stmt->execute();
        $stmt->close();
		
		$db->close();
		  
        }
        //if (is_readable("C:/htdocs/SFA/photo/$namePhoto")){echo 'delete';}
		if (is_readable($IMAGE_PATH.$namePhoto)){
			echo 'delete';
			writeToLogFile( date('Y-m-d H:i:s').' | is_readable | delete ' );
		}else{
			echo 'true';
			writeToLogFile( date('Y-m-d H:i:s').' | is_readable | true ' );
		}
		
		
        /*$query = "INSERT INTO location (name,latitude,longitude,time) VALUES ('".$name."','".$latitude."','".$longitude."','".$time."')";
        $stmt = $db->prepare($query);
        $stmt->execute();*/
        //echo $fotoString64;
        
    }
  

if ($arraydata['func']=='sendTTEdited')
{
    $i=0;
	$JSON = $arraydata["JSONTT"];
	$str="";
    while ($i < count($JSON))
    {
		$query =  "UPDATE `ms_trade_point` SET `name`='".addslashes($JSON[$i]['name'])."',`address`='".addslashes($JSON[$i]['address'])."',`workday`='".addslashes($JSON[$i]['workd'])."',`comments`='".addslashes($JSON[$i]['comnts'])."' WHERE `id`=".$JSON[$i]['id'].";";
		$msg = "sendTTEdited: query: ".$query;
		writeToLogFile($msg);
		$stmt = $db->prepare($query);
		$stmt->execute(); 
        $stmt->close();
		
		$i++;
    }
	$db->close();
    echo 'ok';
}

 
/*$time = date("j-M-Y G:i:s");
$ip = getenv('REMOTE_ADDR');
$referrer = getenv('HTTP_REFERER');
$quer = getenv('QUERY_STRING');
$msg = "IP: ".$ip." || TIME: ".$time." || REFERRER: ".$referrer." || SEARCHSTRING: ".$quer." || DATA: ".$data;
writeToLogFile($msg);*/
function writeToLogFile($msg) {
     $today = date("Y_m_d");
     $logfile = $today."_log.txt";
     $dir = 'logs';
     $saveLocation=$dir . '/' . $logfile;
     if  (!$handle = @fopen($saveLocation, "a")) {
          exit;
     }
     else {
          if (@fwrite($handle,"$msg\r\n") === FALSE) {
               exit;
          }
        @fclose($handle);
     }
}
?>