<?php
session_start();
require_once 'config.php';
require_once 'functions.php';

header('Content-Type: application/json');

requireLogin();
$userId = (int)$_SESSION['user_id'];
$withId = (int)($_GET['with']  ?? 0);
$after  = (int)($_GET['after'] ?? 0);

if (!$withId) { echo '[]'; exit; }

// Marquer comme lus
$pdo->prepare("UPDATE private_messages SET is_read=1 WHERE receiver_id=? AND sender_id=?")
    ->execute([$userId, $withId]);

try {
    $stmt = $pdo->prepare("
        SELECT pm.id, pm.sender_id, pm.content, u.username as sender_name,
               DATE_FORMAT(pm.created_at, '%d %b %H:%i') as created_at
        FROM private_messages pm
        JOIN users u ON u.id = pm.sender_id
        WHERE ((pm.sender_id=? AND pm.receiver_id=?) OR (pm.sender_id=? AND pm.receiver_id=?))
          AND pm.id > ?
        ORDER BY pm.id ASC
        LIMIT 50
    ");
    $stmt->execute([$userId, $withId, $withId, $userId, $after]);
    $msgs = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Échapper le contenu pour le HTML
    foreach ($msgs as &$m) {
        $m['content']     = htmlspecialchars($m['content']);
        $m['sender_name'] = htmlspecialchars($m['sender_name']);
    }

    echo json_encode($msgs);
} catch (Exception $e) {
    echo '[]';
}
?>
