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

require_once __DIR__ . '/../classes/Database.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../classes/Messaging.php';

try {
    session_start();
    if (empty($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'message' => 'Login required.']);
        exit;
    }

    $userId = (int)$_SESSION['user_id'];
    $conversationId = (int)($_GET['conversation_id'] ?? 0);
    $afterId = (int)($_GET['after_id'] ?? 0);

    $database = new Database();
    $conn = $database->getConnection();

    $messaging = new Messaging($conn);
    if (!$conversationId || !$messaging->isParticipant($conversationId, $userId)) {
        echo json_encode(['success' => false, 'message' => 'Conversation not found.']);
        exit;
    }

    $messages = $messaging->getMessages($conversationId, $afterId, $userId);
    $messaging->markRead($conversationId, $userId);

    echo json_encode(['success' => true, 'messages' => $messages]);
} catch (Throwable $e) {
    error_log('Fetching message thread failed: ' . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Unable to load messages.']);
}
