<?php
session_start();
include 'dbconnect.php';
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 = 'Images/';
    $img = $targetDirectory . $fileName;
    $userid = $_POST['creator'];
    $timestamp = $_POST['time']; 
    $caption = $_POST['caption'];
    $myContacts = json_decode($_POST['myContacts']);
    
    // Move the uploaded file to the target directory
    if (move_uploaded_file($fileTmpPath, $img)) {
      tryUploadStatus($db, $img,$userid,$timestamp,$caption);
      
    include 'dbconnect2.php';
    $query = "SELECT token FROM reg_contacts WHERE search_token = $1";
    $stmt = pg_prepare($db, "select_query", $query);
    $lookupTable = [];
    foreach ($myContacts as $searchTokenInstance) {
        $result = pg_execute($db, "select_query", [$searchTokenInstance]);
        // Fetch the row for the current contact from the database
        $row = pg_fetch_assoc($result);
        if ($row) {
            $lookupTable[] = $row['token'];
        }
    }
    array_map('sendPushNotification', $lookupTable);

} 



else {
        // Failed to move the uploaded file
        $result = array(
            'success' => false,
            'message' => 'Failed to upload Status.'
        );
        echo json_encode($result);
        exit;
    }

}



    function tryUploadStatus($db, $img,$userid,$timestamp,$caption)
{
    
    $stmt = pg_prepare($db, "upload_status", 'INSERT INTO status(userid, img, timestamp,caption) VALUES ($1, $2, $3,$4) RETURNING id');
    $result = pg_execute($db, "upload_status", array($userid, $img, $timestamp,$caption));
    $row = pg_fetch_assoc($result); 
    $id = $row['id'];
 
    if ($id) {
        $_SESSION['userid'] = $userid;
        $_SESSION['img']= $img;
        $_SESSION['caption']=$caption;
        $_SESSION['id'] = $id;
        $_SESSION['time'] = $timestamp;
        $response = array(
            "success" => true,
            "response" => "Status uploaded"
        );

      echo json_encode($response);
    //   sendPushNotification($deviceToken);
}
}




function sendPushNotification($deviceToken)
{
    // 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
);
    
    // Data payload (optional)
    $data = array(
        'status'=>true,
        'userid' => $_SESSION['userid'],
        'image'=>$_SESSION['img'],
        'caption'=>$_SESSION['caption'],
        'time'=>$_SESSION['time'],
        'postid'=>$_SESSION['id']
    );
    // Request payload
   $payload = array(
    'to' => $deviceToken,
    '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.';
    }
}
?>