reportify_mncl/public/userarea/include/getNotifications.php

93 lines
3.0 KiB
PHP

<?php
include('../include/headscript.php');
include("../class/company.php");
header('Content-Type: application/json');
include '../../Connections/repnew.php';
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
die(json_encode(["code" => "error", "message" => "Connection failed: " . $conn->connect_error]));
}
$method = $_POST['method'];
$user_id = $_SESSION['iduserlogin'];
if ($method == 'getNotifications') {
$sql = "SELECT * FROM notifications";
$all_notifications = [];
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$all_notifications[] = $row;
}
}
// If there are no notifications, return an empty response
if (empty($all_notifications)) {
die(json_encode(
[
'code' => 'success',
'message' => 'No notifications found'
]
));
} else {
$all_notification_ids = array_column($all_notifications, 'id');
$all_notification_ids_str = implode(',', $all_notification_ids);
$sql = "SELECT notification_id
FROM seen_notifications
WHERE notification_id IN ($all_notification_ids_str)
AND user_id = $user_id";
$result = $conn->query($sql);
$seen_notification_ids = [];
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$seen_notification_ids[] = $row['notification_id'];
}
}
$seen_notifications = [];
foreach ($all_notifications as $notification) {
if (in_array($notification['id'], $seen_notification_ids)) {
$seen_notifications[] = $notification;
}
}
$unseen_notifications = array_udiff($all_notifications, $seen_notifications, function ($a, $b) {
return $a['id'] <=> $b['id'];
});
$new_unseen_notifications = [];
foreach ($unseen_notifications as $notification) {
array_push($new_unseen_notifications, $notification);
}
$new_seen_notifications = [];
foreach ($seen_notifications as $notification) {
array_push($new_seen_notifications, $notification);
}
$conn->close();
// Send JSON response without further encoding the arrays
die(json_encode(
[
'code' => 'success',
'all_notifications' => $all_notifications,
'seen_notifications' => $new_seen_notifications,
'unseen_notifications' => $new_unseen_notifications
]
));
}
}
if ($method == 'markAsSeen') {
$notification_id = $_POST['notification_id'];
$sql = "INSERT INTO seen_notifications (notification_id, user_id) VALUES ($notification_id, $user_id)";
$conn->query($sql);
$conn->close();
die(json_encode(['code' => 'success', 'message' => 'Notification marked as seen']));
}