<?php
include 'dbconnect.php';


$receiver = $_POST['receiver'];
$token = $_POST['token'];
$contact_requested = $_POST['contact'];
$contact_requested_owner =  $_POST['contact_requested_owner'];
$sender = $_POST['sender'];
$sender = substr($sender, -9);
$receiver = substr($receiver, -9);
$time = $_POST['time'];
$id = $_POST['id'];

$sql = "SELECT token FROM reg_contacts WHERE iphone = $1";
// Prepare the statement
$stmt = pg_prepare($db, "select_token", $sql);
// Bind the variable to the prepared statement
$result = pg_execute($db, "select_token", [$receiver]);
// Fetch the result
$token = pg_fetch_result($result, 0, 0);
// Close the database connection

sendPushNotification($token, $sender,"$contact_requested_owner contact is now available", $time,$contact_requested,$id);
updateBridgeState($id,$receiver,$sender);

$resultSuccess = array(
    'success' => true,
    'response' => "Bridge Response sent",
    'sender'=>$sender,
    'receiver'=>$receiver,
    'requested_bridge_savedName'=>$contact_requested,
    'requested_bridge_contact'=>$contact_requested_owner,
    'time'=>$time,
    'token'=>$token

);
echo json_encode($resultSuccess);

function sendPushNotification($deviceToken, $title, $body, $time, $contact_requested,$id)
{
    // FCM server key
    $serverKey = 'AAAAdGlOElM:APA91bELNPs_4odsNIZ_eOaRoLk3TLPRstRXc9yVTrEXqBFh1Y_vbjTvO8zWP5hngh3Scr9Q2KBa13rfoDy6MZrUj0iuNmqJe2a0WssA7AQs5M9Vvim9zERCUUA6X_Axc5H0notjGflz';
    // FCM API URL
    $url = 'https://fcm.googleapis.com/fcm/send';
    // Notification payload
    $notification = array(
        'title' => $title,
        'body' => $body,
        'sound' => 'default',
        'badge' => '1'
    );
    // Data payload (optional)
    $data = array(
        'id' => $id,
        'requested_bridge_contact' => $contact_requested,
        'sender'=>$title,
        'time' => $time,
        'state' => 1,
        'bridge_confirmed' =>"true"

    );
    // Request payload
    $payload = array(
        'to' => $deviceToken,
        'notification' => $notification,
        'data' => $data
    );
    // Headers
    $headers = array(
        'Authorization: key=' . $serverKey,
        'Content-Type: application/json'
    );
    // Send the POST request to FCM API
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    $result = curl_exec($ch);
    curl_close($ch);
    // Handle the response from FCM API
    if ($result === false) {
        // echo 'Failed to send push notification: ' . curl_error($ch);
    } else {
        // echo 'Push notification sent successfully.';
    }
}

function updateBridgeState($id,$account,$writer)
{
$filename = 'bridges/' . $account . '.json';
if (file_exists($filename)) {
    $json = json_decode(file_get_contents($filename), true);
} 

foreach ($json[$writer] as &$item) {
    if ($item["id"] == $id && $item["way"] == "out") {
        $item["state"] = 1;
       // Exit the loop once the ID is found
    }
    
}

file_put_contents($filename, json_encode($json));
  
  
  
  
  
  
  
  
$filename = 'bridges/' . $writer . '.json';
if (file_exists($filename)) {
    $json = json_decode(file_get_contents($filename), true);
} 

foreach ($json[$account] as &$item) {
    if ($item["id"] == $id && $item["way"] == "in") {
        $item["state"] = 2;
       // Exit the loop once the ID is found
    }
    
}

file_put_contents($filename, json_encode($json));  
  
  
  
  
  

//   $filename = 'bridges/' . $writer . '.json';
//     if (file_exists($filename)) {
//         $json = json_decode(file_get_contents($filename), true);
//     } 
//   foreach ($json[$writer] as $index => $item) {
//         if ($item["id"] == $id) {
//             unset($json[$writer][$index]);
//             break; // Exit the loop once the ID is found and removed
//         }
//     }

//   file_put_contents($filename, json_encode($json));
  
 
}
echo json_encode($result);

?>
