<?php
include('db_connect.php');

$response= array();
if(isset($_POST['devicename']))
{
$devicename=$_POST['devicename'];
$uid=$_POST['uid'];
$model=$_POST['model'];
$token=$_POST['token'];
$latitude=$_POST['latitude'];
$longitude=$_POST['longitude'];
$android_id=$_POST['android_id'];
 $updateDate = isset($_POST['updateDate']) ? $_POST['updateDate'] : '';
 $is_location_on=$_POST['is_location_on'];
 $is_lock_on=$_POST['is_lock_on'];
 $is_erase_on=$_POST['is_erase_on'];



    // check if user already exists
    $result1=   $query=mysqli_query($con,"SELECT * FROM device_reg WHERE uid='$uid' and android_id='$android_id'");
 if(mysqli_num_rows($query)>=1)
   {
       $updateToken="UPDATE `device_reg` SET `token`='$token' WHERE `android_id`='$android_id' and uid='$uid'";
       mysqli_query($con,$updateToken);
       
       
    // fetch user id from db
    $dataresult="Select * from device_reg where uid='$uid'";
    $resultdata= mysqli_query($con,$dataresult);
    $row=$resultdata->fetch_all(MYSQLI_ASSOC);

        $response=array("error"=>"false","message"=>"record recived","data"=>$row);
 //   $response[]=$row;
    
   }
 else
    {
$query= "INSERT INTO `device_reg`(`uid`, `devicename`, `model`, `token`, `latitude`, `longitude`, `android_id`, `updateDate`, `is_location_on`, `is_lock_on`, `is_erase_on`)
 VALUES ('$uid','$devicename','$model','$token','$latitude','$longitude','$android_id','$updateDate', '$is_location_on', '$is_lock_on', '$is_erase_on')";
if(mysqli_query($con,$query)){
   

    // fetch device data from db
    $data="Select * from device_reg where uid='$uid'";
    $result= mysqli_query($con,$data);
    $row=$result->fetch_all(MYSQLI_ASSOC);

        $response=array("error"=>"false","message"=>"record recived","data"=>$row);
      //  $response[]=$row;

}else{
 
    $response=array("error"=>"true","message"=>"Error: " . $query . "<br>" . mysqli_error($con),"data"=>"null");

   // $response['error']="Error: " . $query . "<br>" . mysqli_error($con);

}
    }
}else{
    $response=array("error"=>"true","message"=>"Some error occured. Please try again!","data"=>"null");

//    $response['error']= true;
//    $response['message']="Some error occured. Please try again!";
}

echo json_encode($response);
mysqli_close($con);


?>