<?php
session_start();
include_once($_SERVER['DOCUMENT_ROOT'] . '/digital_pos/includes/config.php');

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

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'messages' => []]);
    exit;
}

$user_id = $_SESSION['user_id'];

$query = "
    SELECT m.id, m.subject, m.message, m.created_at, u.first_name, u.last_name
    FROM messages m
    JOIN users u ON m.sender_id = u.id
    WHERE m.receiver_id = ?
    ORDER BY m.created_at DESC
    LIMIT 5
";

$stmt = $conn->prepare($query);
$stmt->bind_param('i', $user_id);
$stmt->execute();
$result = $stmt->get_result();

$messages = [];
while ($row = $result->fetch_assoc()) {
    $messages[] = [
        'id' => $row['id'],
        'subject' => htmlspecialchars($row['subject']),
        'snippet' => htmlspecialchars(substr($row['message'], 0, 50)) . (strlen($row['message']) > 50 ? '...' : ''),
        'sender_name' => htmlspecialchars($row['first_name'] . ' ' . $row['last_name']),
        'created_at' => $row['created_at']
    ];
}

$stmt->close();
$conn->close();

echo json_encode(['success' => true, 'messages' => $messages]);
