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

if (!isset($_SESSION['login'])) {
    die(SQLERROR3);
}

$currentUser = $_SESSION['user_id'];
$otherUser = $_GET['user'] ?? null;

if (!$otherUser) {
    die(SQLERROR4);
}

// Prépare la requête SQL
$query = $bdd->prepare("SELECT * FROM ".$prefix."_tchat WHERE 
    (sender_id = ? AND receiver_id = ?) OR 
    (sender_id = ? AND receiver_id = ?) 
    ORDER BY created_at DESC LIMIT 15");

// Vérifie si la préparation a réussi
if (!$query) {
    die(SQLERROR2." " . $bdd->error);
}

// Lie les paramètres (tous sont des strings "s")
$query->bind_param("ssss", $currentUser, $otherUser, $otherUser, $currentUser);

// Exécute la requête
$query->execute();

// Récupère le résultat
$result = $query->get_result();

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

$query->close();

// **On inverse l'ordre pour avoir du plus ancien au plus récent**
$messages = array_reverse($messages);

// **Affichage**
foreach ($messages as $message) {
    $login = mysqli_fetch_assoc(mysqli_query($bdd,"SELECT login FROM ".$prefix."_user WHERE id ='".$message['sender_id']."'"));
    $messageClass = ($message['sender_id'] == $_SESSION['user_id']) ? 'sender' : 'receiver'; // Déterminer la classe en fonction de l'expéditeur
    $formattedDate = date("d/m/Y - H:i", strtotime($message['created_at']));
    echo '<div class="message-container ' . $messageClass . '">';
    echo '<div class="message ' . $messageClass . '">';
    echo '<span class="message-sender">' . htmlspecialchars($login['login']) . '.</span>';
    echo '<span class="message-content"> ' . htmlspecialchars($message['message']) . '</span>';
    echo '<span class="message-time" style="font-size: 12px; color: white; display: block;">' . $formattedDate . '</span>';
    if ($message['sender_id'] == $_SESSION['user_id']) {
        echo ' <i class="fa-regular fa-trash-can delete-message" data-message-id="' . $message['tchat_id'] . '"></i>';
    }
    echo '</div></div>';
}
?>
