<?php
session_start();
include('../../config.php');
require_once(BASE_PATH . '/db/idl_connect.php');

$currentUser = $_SESSION['user_id'];

// Récupérer les messages non lus envoyés à l'utilisateur connecté
$query = $bdd->prepare("SELECT * FROM ".$prefix."_tchat WHERE receiver_id = ? AND is_read = 0 ORDER BY created_at DESC");
$query->bind_param("s", $currentUser);
$query->execute();
$result = $query->get_result();

$messages = [];
while ($message = $result->fetch_assoc()) {
    $messages[] = $message;
}

// Marquer ces messages comme "lus"
$updateQuery = $bdd->prepare("UPDATE ".$prefix."_tchat SET is_read = 1 WHERE receiver_id = ?");
$updateQuery->bind_param("s", $currentUser);
$updateQuery->execute();

$query->close();
$updateQuery->close();

echo json_encode($messages);
?>