<?php
include '../../conn.php';

$phone=$_GET['phone'];
$fcmtoken=$_GET['fcmtoken'];
include 'message.php';


$resultdata =$con->query("select * from `users` where phone='$phone' ");
$id=null;

while($row = mysqli_fetch_array($resultdata)){
    $id=$row['id'];
}
if($id > 0)
{ 

$insert = $con->query("UPDATE `users` SET `fcmtoken`='$fcmtoken' WHERE  id='$id'");
 
$j->status  = "101";
$j->message = "Already account Success";
$j->id=$id;
}
else{
$mycoupon = substr(md5(mt_rand()), 0, 6);
$insert = $con->query("INSERT INTO `users`(`phone`,`myCoupon`)values ('$phone','$mycoupon')");
$resultdata =$con->query("select * from `users` where phone='$phone' ");
$id=null;

while($row = mysqli_fetch_array($resultdata)){
    $id=$row['id'];
}
if($id > 0){
$insert = $con->query("UPDATE `users` SET `fcmtoken`='$fcmtoken' WHERE  id='$id'");
$j->status  = "101";
$j->message = "new registeration success";
$j->id=$id;
}
}

  
      $data = array("to" => $fcmtoken,
                  "notification" => array( "code"=> $logincodefcm,"title" => "$titlefcm", "body" => $loginmsg,"icon" => $logofcm));                                                                    
            $data_string = json_encode($data); 
            
             "The Json Data : ".$data_string; 
            
            $headers = array
            (
                 'Authorization: key=' . API_ACCESS_KEY, 
                 'Content-Type: application/json'
            );                                                                                 
                                                                                                                                 
            $ch = curl_init();  
            
            curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );                                                                  
            curl_setopt( $ch,CURLOPT_POST, true );  
            curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
            curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
            curl_setopt( $ch,CURLOPT_POSTFIELDS, $data_string);                                                                  
                                                                                                                                 
            $result = curl_exec($ch);
echo json_encode($j);         
?>