<?php
include 'dbconnect.php';
$sender = $_POST['sender'];
$receiver = $_POST['receiver'];
$receiver = substr($receiver, -9);
$sender1 = substr($sender, -9);
$message = $_POST['message'];
$token = $_POST['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





$datetime = $_POST['time'];
$id = $_POST['id'];
$referenceId = $_POST['referenceId'];
$referenceTextMessage = $_POST['referenceTextMessage'];

if ($_FILES['file']['name']) {
    // File upload is present
    $fileName = $_FILES['file']['name'];
    $fileTmpPath = $_FILES['file']['tmp_name'];
    $fileSize = $_FILES['file']['size'];
    $fileType = $_FILES['file']['type'];
    $fileError = $_FILES['file']['error'];

    // Define the target directory and path to save the file
    $targetDirectory = 'transfers/';
    $targetPath = $targetDirectory . $fileName;

    // Move the uploaded file to the target directory
    if (move_uploaded_file($fileTmpPath, $targetPath)) {
        // File uploaded successfully
        $message = sha1("file_received");
         $result = array(
            'success' => true,
            'sender' => $sender,
            'receiver'=>$receiver,
            'message'=>$message,
            'fileName' => $fileName,
            'type' => "file"
        );
    } else {
        // Failed to move the uploaded file
        $result = array(
            'success' => false,
            'message' => 'Failed to upload the file.'
        );
        echo json_encode($result);
        exit;
    }
}

sendPushNotification($token, $sender1, $message, $datetime, $id, $referenceId, $referenceTextMessage);
saveMessage($message, $datetime, "out", $sender1, $receiver, $id, $referenceId, $referenceTextMessage);
saveMessage($message, $datetime, "in", $receiver, $sender1, $id, $referenceId, $referenceTextMessage);

$resultSuccess = array(
    'success' => true,
    'response' => ""
);
echo json_encode($resultSuccess);

function sendPushNotification($deviceToken, $title, $body, $time, $id, $referenceId, $referenceTextMessage)
{
    // 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(
        'sender_phone' => $title,
        'message' => $body,
        'id' => $id,
        'time' => $time,
        'referenceId' => $referenceId,
        'referenceTextMessage' => $referenceTextMessage
    );
    // 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 saveMessage($message, $datetime, $way, $account, $writer, $id, $referenceId, $referenceTextMessage)
{
    // Create an array with the message data
    $messageData = array(
        'id' => $id,
        'message' => $message,
        'time' => $datetime,
        'way' => $way,
        'referenceId' => $referenceId,
        'referenceTextMessage' => $referenceTextMessage
    );

    $filename = 'texts/' . $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 file with the data
        $json = array();
    }
    // Group messages by writer's phone number
    if (isset($json[$writer])) {
        // Move the writer's array to the beginning of the JSON
        $json = array($writer => $json[$writer]) + $json;

        // Add the new message to the writer's array
        $json[$writer]['messages'][] = $messageData;

        if ($way == 'in') {
            $json[$writer]['unreadMessages'] += 1;
        }
    } else {
        // Create a new array for the writer and add the message
        if ($way == 'in') {
            $unreadMessages = 1;
        } else {
            $unreadMessages = 0;
        }

        $json = array($writer => array(
            'messages' => array($messageData),
            'unreadMessages' => $unreadMessages
        )) + $json;
    }
    if (isset($json[$writer]['messages'])) {
        file_put_contents($filename, json_encode($json));
    }
}

 echo json_encode($result);



//     $sender = $_POST['sender'];
//     $receiver = $_POST['receiver'];
//     $receiver = substr($receiver,-9);
//     $sender1 = substr($sender,-9);
//     $message = $_POST['message'];
//     $token = $_POST['token'];
//     $datetime = $_POST['time'];
//     $id = $_POST['id'];
//     $referenceId = $_POST['referenceId'];
//     $referenceTextMessage = $_POST['referenceTextMessage'];
// sendPushNotification($token, $sender1, $message,$datetime,$id,$referenceId,$referenceTextMessage);
// saveMessage($message,$datetime,"out",$sender1,$receiver,$id,$referenceId,$referenceTextMessage);
// saveMessage($message,$datetime,"in",$receiver,$sender1,$id,$referenceId,$referenceTextMessage);
//  $resultSuccess= array(
//     'success' => true,
//     'response' => ""
// );
// echo json_encode($resultSuccess);

// function sendPushNotification($deviceToken, $title, $body,$time,$id,$referenceId,$referenceTextMessage) {
//     // 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(
//         'sender_phone' => $title,
//         'message' => $body,
//         'id'=>$id,
//         'time'=>$time,
//         'referenceId' =>$referenceId,
//         'referenceTextMessage' =>$referenceTextMessage
//     );
//     // 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 saveMessage($message, $datetime, $way, $account, $writer,$id,$referenceId,$referenceTextMessage) {
//     // Create an array with the message data
//     $messageData = array(
//         'id' => $id,  
//         'message' => $message,
//         'time' => $datetime,
//         'way' => $way,
//         'referenceId'=>$referenceId,
//         'referenceTextMessage'=>$referenceTextMessage
//     );
    
    
//     $filename = 'texts/' . $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 file with the data
//         $json = array();
//     }
//     // Group messages by writer's phone number
//     if (isset($json[$writer])) {
//         // Move the writer's array to the beginning of the JSON
//         $json = array($writer => $json[$writer]) + $json;

//         // Add the new message to the writer's array
//         $json[$writer]['messages'][] = $messageData;
        
        
//         if($way == 'in'){
//              $json[$writer]['unreadMessages'] +=1;
//         }
       
        
//     } else {
//         // Create a new array for the writer and add the message
//         if($way == 'in'){
//              $unreadMessages = 1;
//         }
//         else{
//             $unreadMessages = 0; 
//         }
        
        
//         $json = array($writer => array(
//             'messages' => array($messageData),
//             'unreadMessages' => $unreadMessages
//             )) + $json;
//     }
//     if (isset($json[$writer]['messages'])) {
//         file_put_contents($filename, json_encode($json));
//     }
    
   
    
    
// }
?>
