<?php
include 'dbconnect.php';


$item = $_POST['item'];
$item = json_decode($item,true);
$id = $_POST['id'];
$sender = $item['requesting_party'];
$sender = substr($sender, -9);
$receiver =  $item['requested_contact_phone_number'];
$receiver = substr($receiver, -9);
$requested_bridge_contact = $item['bridge_requested'];
$requested_bridge_searchedQuery = $item['bridge_requested_name'];
$requested_bridge_savedName =  $item['bridge_requested_Savedname'];
$time = $item['time'];
$token = $item['token'];

$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", "0$sender requested bridge for $requested_bridge_searchedQuery [$requested_bridge_savedName]", $time, $id,$requested_bridge_contact,$requested_bridge_savedName,$requested_bridge_searchedQuery,"in");
saveBridge($requested_bridge_contact,$requested_bridge_savedName,$requested_bridge_searchedQuery, $receiver,$sender,$time, "out",$id);
saveBridge($requested_bridge_contact,$requested_bridge_savedName,$requested_bridge_searchedQuery, $sender, $receiver,$time, "in",$id);

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

);
echo json_encode($resultSuccess);

function sendPushNotification($deviceToken, $title, $body, $time, $id,$requested_bridge_contact,$requested_bridge_savedName,$requested_bridge_searchedQuery,$way)
{
    // 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' => $requested_bridge_contact,
        'requested_bridge_savedName' => $requested_bridge_savedName,
        'requested_bridge_searchedQuery' => $requested_bridge_searchedQuery,
        'time' => $time,
        'way' => $way,
        'state' => 0,
        'bridge_notification' =>"true",
        'requestingParty'=> $title

    );
    // 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 saveBridge($requested_bridge_contact, $requested_bridge_savedName, $requested_bridge_searchedQuery, $writer, $account, $time, $way, $id)
{
    // Create an array with the message data
    $bridgeData = array(
        'id' => $id,
        'requested_bridge_contact' => $requested_bridge_contact,
        'requested_bridge_savedName' => $requested_bridge_savedName,
        'requested_bridge_searchedQuery' => $requested_bridge_searchedQuery,
        'time' => $time,
        'way' => $way,
        'state' => 0
    );

    $filename = 'bridges/' . $account . '.json';

    if (file_exists($filename)) {
        // File exists, read the existing JSON data
        $json = json_decode(file_get_contents($filename), true);
    } else {
        // File doesn't exist, create a new JSON array
        $json = array();
    }

    if (isset($json[$writer])) {
        // Writer's array exists, add the new message to it
        array_unshift($json[$writer], $bridgeData);
    } else {
        // Writer's array doesn't exist, create a new array with the writer's key
        $json[$writer] = array($bridgeData);
    }

    // Save the updated JSON data to the file
    file_put_contents($filename, json_encode($json));
}


 echo json_encode($result);


?>
